Programs & Examples On #Ssrs grouping

Microsofts SQL Server Reporting Services (SSRS) allows creation of reports that contain Tablix controls where data is grouped by fields or expressions in row and/or column groups. Use the ssrs-grouping tag for questions about how to use group properties to change report behaviour.

Angular - "has no exported member 'Observable'"

The angular-split component is not supported in Angular 6, so to make it compatible with Angular 6 install following dependency in your application

To get this working until it's updated use:

"dependencies": {
"angular-split": "1.0.0-rc.3",
"rxjs": "^6.2.2",
    "rxjs-compat": "^6.2.2",
}

NULL value for int in Update statement

Provided that your int column is nullable, you may write:

UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>

How to recover MySQL database from .myd, .myi, .frm files

For those that have Windows XP and have MySQL server 5.5 installed - the location for the database is C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.5\data, unless you changed the location within the MySql Workbench installation GUI.

run program in Python shell

From the same folder, you can do:

import test

What's the difference between git clone --mirror and git clone --bare

The difference is that when using --mirror, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.

The new documentation pretty much says all this:

--mirror

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD, while the bare clone copies the branches directly.

Suppose origin has a few branches (master (HEAD), next, pu, and maint), some tags (v1, v2, v3), some remote branches (devA/master, devB/master), and some other refs (refs/foo/bar, refs/foo/baz, which might be notes, stashes, other devs' namespaces, who knows).

  • git clone origin-url (non-bare): You will get all of the tags copied, a local branch master (HEAD) tracking a remote branch origin/master, and remote branches origin/next, origin/pu, and origin/maint. The tracking branches are set up so that if you do something like git fetch origin, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --bare origin-url: You will get all of the tags copied, local branches master (HEAD), next, pu, and maint, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --mirror origin-url: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD), next, pu, and maint, remote branches devA/master and devB/master, other refs refs/foo/bar and refs/foo/baz. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.

Function to clear the console in R and RStudio

In Ubuntu-Gnome, simply pressing CTRL+L should clear the screen.

This also seems to also work well in Windows 10 and 7 and Mac OS X Sierra.

How to apply multiple transforms in CSS?

I'm adding this answer not because it's likely to be helpful but just because it's true.

In addition to using the existing answers explaining how to make more than one translation by chaining them, you can also construct the 4x4 matrix yourself

I grabbed the following image from some random site I found while googling which shows rotational matrices:

Rotation around x axis: Rotation around x axis
Rotation around y axis: Rotation around y axis
Rotation around z axis: Rotation around z axis

I couldn't find a good example of translation, so assuming I remember/understand it right, translation:

[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[x y z 1]

See more at the Wikipedia article on transformation as well as the Pragamatic CSS3 tutorial which explains it rather well. Another guide I found which explains arbitrary rotation matrices is Egon Rath's notes on matrices

Matrix multiplication works between these 4x4 matrices of course, so to perform a rotation followed by a translation, you make the appropriate rotation matrix and multiply it by the translation matrix.

This can give you a bit more freedom to get it just right, and will also make it pretty much completely impossible for anyone to understand what it's doing, including you in five minutes.

But, you know, it works.

Edit: I just realized that I missed mentioning probably the most important and practical use of this, which is to incrementally create complex 3D transformations via JavaScript, where things will make a bit more sense.

How to create an integer array in Python?

Use the array module. With it you can store collections of the same type efficiently.

>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))

For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.

The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.

You use it just like a list:

>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14

...or simply convert it to a list:

>>> l = list(a)
>>> len(l)
14

Surprisingly

>>> a = [0] * 10000000

is faster at construction than the array method. Go figure! :)

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

Section vs Article HTML5

Section

  • Use this for defining a section of your layout. It could be mid,left,right ,etc..
  • This has a meaning of connection with some other element, put simply, it's DEPENDENT.

Article

  • Use this where you have independent content which make sense on its own .

  • Article has its own complete meaning.

Get the latest record with filter in Django

last() latest()

Usign last():

ModelName.objects.last()

using latest():

ModelName.objects.latest('id')

Java function for arrays like PHP's join()?

If you've landed here looking for a quick array-to-string conversion, try Arrays.toString().

Creates a String representation of the Object[] passed. The result is surrounded by brackets ("[]"), each element is converted to a String via the String.valueOf(Object) and separated by ", ". If the array is null, then "null" is returned.

Why does foo = filter(...) return a <filter object>, not a list?

the reason why it returns < filter object > is that, filter is class instead of built-in function.

help(filter) you will get following: Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

Java variable number or arguments for a method

Variable number of arguments

It is possible to pass a variable number of arguments to a method. However, there are some restrictions:

  • The variable number of parameters must all be the same type
  • They are treated as an array within the method
  • They must be the last parameter of the method

To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:

private static int largest(int... numbers) {
     int currentLargest = numbers[0];
     for (int number : numbers) {
        if (number > currentLargest) {
            currentLargest = number;
        }
     }
     return currentLargest;
}

source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012

Creating runnable JAR with Gradle

Here is the solution I tried with Gradle 6.7

Runnable fat Jar (with all dependent libraries copied to the jar)

task fatJar(type: Jar) {
   
    manifest {
        attributes 'Main-Class': 'com.example.gradle.App'
    }
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    } with jar
    
}

Runnable jar with all dependencies copied to a directory and adding the classpath to the manifest

    def dependsDir = "${buildDir}/libs/dependencies/"
    task copyDependencies(type: Copy) {
        from configurations.compile
        into "${dependsDir}"
    }
    task createJar(dependsOn: copyDependencies, type: Jar) {
      
        manifest {
            attributes('Main-Class': 'com.example.gradle.App',
                    'Class-Path': configurations.compile.collect { 'dependencies/' + it.getName() }.join(' ')
            )
        }
        with jar
    }

How to use ?

  • Add the above tasks to build.gradle
  • Execute gradle fatJar //create fatJar
  • Execute gradle createJar // create jar with dependencies copied.

More details : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

Running an Excel macro via Python?

I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:

#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl

def runMacro():

    if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):

    # DispatchEx is required in the newest versions of Python.
    excel_macro = wincl.DispatchEx("Excel.application")
    excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
    workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
    excel_macro.Application.Run\
        ("ThisWorkbook.Template2G")
    #Save the results in case you have generated data
    workbook.Save()
    excel_macro.Application.Quit()  
    del excel_macro

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

E: Unable to locate package mongodb-org

This worked on Ubuntu 17.04

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

sudo apt-get update

sudo apt-get install -y mongodb-org

If you see a failure like:

dpkg: error processing archive /var/cache/apt/archives/mongodb-org-tools_3.6.2_amd64.deb (--unpack):
trying to overwrite '/usr/bin/bsondump', which is also in package mongo-tools 3.2.11-1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)

Then run this command:

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" |

sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

and

sudo apt update
sudo apt install mongodb-org

References:

Why is my Spring @Autowired field null?

Another solution would be putting call: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
To MileageFeeCalculator constructor like this:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- will be autowired when constructor is called

    public MileageFeeCalculator() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
    }

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); 
    }
}

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Add the following dependency to your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.2</version>
</dependency>

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

You must manually clear the ChildItems collection and append new items into it:

thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);

After that you can call DeleteOrphans extension method which will handle with orphaned entities (it must be called between DetectChanges and SaveChanges methods).

public static class DbContextExtensions
{
    private static readonly ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>> s_navPropMappings = new ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>>();

    public static void DeleteOrphans( this DbContext source )
    {
        var context = ((IObjectContextAdapter)source).ObjectContext;
        foreach (var entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
        {
            var entityType = entry.EntitySet.ElementType as EntityType;
            if (entityType == null)
                continue;

            var navPropMap = s_navPropMappings.GetOrAdd(entityType, CreateNavigationPropertyMap);
            var props = entry.GetModifiedProperties().ToArray();
            foreach (var prop in props)
            {
                NavigationProperty navProp;
                if (!navPropMap.TryGetValue(prop, out navProp))
                    continue;

                var related = entry.RelationshipManager.GetRelatedEnd(navProp.RelationshipType.FullName, navProp.ToEndMember.Name);
                var enumerator = related.GetEnumerator();
                if (enumerator.MoveNext() && enumerator.Current != null)
                    continue;

                entry.Delete();
                break;
            }
        }
    }

    private static ReadOnlyDictionary<string, NavigationProperty> CreateNavigationPropertyMap( EntityType type )
    {
        var result = type.NavigationProperties
            .Where(v => v.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
            .Where(v => v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || (v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && v.FromEndMember.GetEntityType() == v.ToEndMember.GetEntityType()))
            .Select(v => new { NavigationProperty = v, DependentProperties = v.GetDependentProperties().Take(2).ToArray() })
            .Where(v => v.DependentProperties.Length == 1)
            .ToDictionary(v => v.DependentProperties[0].Name, v => v.NavigationProperty);

        return new ReadOnlyDictionary<string, NavigationProperty>(result);
    }
}

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

Making a cURL call in C#

Late response but this is what I ended up doing. If you want to run your curl commands very similarly as you run them on linux and you have windows 10 or latter do this:

    public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
    {
        if (string.IsNullOrEmpty(curlCommand))
            return "";

        curlCommand = curlCommand.Trim();

        // remove the curl keworkd
        if (curlCommand.StartsWith("curl"))
        {
            curlCommand = curlCommand.Substring("curl".Length).Trim();
        }

        // this code only works on windows 10 or higher
        {

            curlCommand = curlCommand.Replace("--compressed", "");

            // windows 10 should contain this file
            var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

            if (System.IO.File.Exists(fullPath) == false)
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Windows 10 or higher is required to run this application");
            }

            // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
            List<string> parameters = new List<string>();


            // separate parameters to escape quotes
            try
            {
                Queue<char> q = new Queue<char>();

                foreach (var c in curlCommand.ToCharArray())
                {
                    q.Enqueue(c);
                }

                StringBuilder currentParameter = new StringBuilder();

                void insertParameter()
                {
                    var temp = currentParameter.ToString().Trim();
                    if (string.IsNullOrEmpty(temp) == false)
                    {
                        parameters.Add(temp);
                    }

                    currentParameter.Clear();
                }

                while (true)
                {
                    if (q.Count == 0)
                    {
                        insertParameter();
                        break;
                    }

                    char x = q.Dequeue();

                    if (x == '\'')
                    {
                        insertParameter();

                        // add until we find last '
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \' 
                            if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                            {
                                currentParameter.Append('\'');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '\'')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else if (x == '"')
                    {
                        insertParameter();

                        // add until we find last "
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \"
                            if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                            {
                                currentParameter.Append('"');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '"')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else
                    {
                        currentParameter.Append(x);
                    }
                }
            }
            catch
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Invalid curl command");
            }

            StringBuilder finalCommand = new StringBuilder();

            foreach (var p in parameters)
            {
                if (p.StartsWith("-"))
                {
                    finalCommand.Append(p);
                    finalCommand.Append(" ");
                    continue;
                }

                var temp = p;

                if (temp.Contains("\""))
                {
                    temp = temp.Replace("\"", "\\\"");
                }
                if (temp.Contains("'"))
                {
                    temp = temp.Replace("'", "\\'");
                }

                finalCommand.Append($"\"{temp}\"");
                finalCommand.Append(" ");
            }


            using (var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "curl.exe",
                    Arguments = finalCommand.ToString(),
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    WorkingDirectory = Environment.SystemDirectory
                }
            })
            {
                proc.Start();

                proc.WaitForExit(timeoutInSeconds*1000);

                return proc.StandardOutput.ReadToEnd();
            }
        }
    }

The reason why the code is a little bit long is because windows will give you an error if you execute a single quote. In other words, the command curl 'https://google.com' will work on linux and it will not work on windows. Thanks to that method I created you can use single quotes and run your curl commands exactly as you run them on linux. This code also checks for escaping characters such as \' and \".

For example use this code as

var output = ExecuteCurl(@"curl 'https://google.com' -H 'Accept: application/json, text/javascript, */*; q=0.01'");

If you where to run that same string agains C:\Windows\System32\curl.exe it will not work because for some reason windows does not like single quotes.

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

Remove spaces from a string in VB.NET

What about Regex.Replace solution?

myStr = Regex.Replace(myStr, "\s", "")

How to remove multiple indexes from a list at the same time?

There wasn't much hint on performance for the different ways so I performed a test on removing 5000 items from 50000 in all 3 generally different approaches, and for me numpy was the winner (if you have elements that fit in numpy):

  • 7.5 sec for the enumerated list comprehension [4.5 sec on another PC]
  • 0.08 sec for deleting items in reverse order [0.017 (!) sec]
  • 0.009 sec for numpy.delete [0.006 sec]

Here's the code I timed (in the third function conversion from/to list may be removed if working directly on numpy arrays is ok):

import time
import numpy as np
import random

def del_list_indexes(l, id_to_del):
    somelist = [i for j, i in enumerate(l) if j not in id_to_del]
    return somelist

def del_list_inplace(l, id_to_del):
    for i in sorted(id_to_del, reverse=True):
        del(l[i])

def del_list_numpy(l, id_to_del):
    arr = np.array(l, dtype='int32')
    return list(np.delete(arr, id_to_del))

l = range(50000)
random.shuffle(l)
remove_id = random.sample(range(len(l)), 5000) # 10% ==> 5000

# ...

How to read .pem file to get private and public key

Try this class.

package groovy;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RSA {

private static String getKey(String filename) throws IOException {
    // Read key from file
    String strKeyPEM = "";
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = br.readLine()) != null) {
        strKeyPEM += line + "\n";
    }
    br.close();
    return strKeyPEM;
}
public static RSAPrivateKey getPrivateKey(String filename) throws IOException, GeneralSecurityException {
    String privateKeyPEM = getKey(filename);
    return getPrivateKeyFromString(privateKeyPEM);
}

public static RSAPrivateKey getPrivateKeyFromString(String key) throws IOException, GeneralSecurityException {
    String privateKeyPEM = key;
    privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
    byte[] encoded = Base64.decodeBase64(privateKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
    RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
    return privKey;
}


public static RSAPublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
    String publicKeyPEM = getKey(filename);
    return getPublicKeyFromString(publicKeyPEM);
}

public static RSAPublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
    String publicKeyPEM = key;
    publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
    publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
    byte[] encoded = Base64.decodeBase64(publicKeyPEM);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
    return pubKey;
}

public static String sign(PrivateKey privateKey, String message) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
    Signature sign = Signature.getInstance("SHA1withRSA");
    sign.initSign(privateKey);
    sign.update(message.getBytes("UTF-8"));
    return new String(Base64.encodeBase64(sign.sign()), "UTF-8");
}


public static boolean verify(PublicKey publicKey, String message, String signature) throws SignatureException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    Signature sign = Signature.getInstance("SHA1withRSA");
    sign.initVerify(publicKey);
    sign.update(message.getBytes("UTF-8"));
    return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8")));
}

public static String encrypt(String rawText, PublicKey publicKey) throws IOException, GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.encodeBase64String(cipher.doFinal(rawText.getBytes("UTF-8")));
}

public static String decrypt(String cipherText, PrivateKey privateKey) throws IOException, GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return new String(cipher.doFinal(Base64.decodeBase64(cipherText)), "UTF-8");
}
}


Required jar library "common-codec-1.6"

How do you convert an entire directory with ffmpeg?

@Linux To convert a bunch, my one liner is this, as example (.avi to .mkv) in same directory:

for f in *.avi; do ffmpeg -i "${f}" "${f%%.*}.mkv"; done

please observe the double "%%" in the output statement. It gives you not only the first word or the input filename, but everything before the last dot.

Verify ImageMagick installation

Remember that after installing Imagick (or indeed any PHP module) you need to restart your web server and/or php-fpm if you're using it, for the module to appear in phpinfo().

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

Invalid column name sql error

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

int array to string

at.net 3.5 use:

 String.Join("", new List<int>(array).ConvertAll(i => i.ToString()).ToArray());

at.net 4.0 or above use: (see @Jan Remunda's answer)

 string result = string.Join("", array);

I want to delete all bin and obj folders to force all projects to rebuild everything

Nothing worked for me. I needed to delete all files in bin and obj folders for debug and release. My solution:

1.Right click project, unload, right click again edit, go to bottom

2.Insert

<Target Name="DeleteBinObjFolders" BeforeTargets="Clean">
  <RemoveDir Directories="..\..\Publish" />
  <RemoveDir Directories=".\bin" />
  <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
</Target>

3. Save, reload project, right click clean and presto.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Add the line below in application.properties file under resource folder and restart your application.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Getting list of pixel values from PIL

As I commented above, problem seems to be the conversion from PIL internal list format to a standard python list type. I've found that Image.tostring() is much faster, and depending on your needs it might be enough. In my case, I needed to calculate the CRC32 digest of image data, and it suited fine.

If you need to perform more complex calculations, tom10 response involving numpy might be what you need.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

Mine was not having @Entity on the many side entity

@Entity // this was commented
@Table(name = "some_table")
public class ChildEntity {
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @ManyToOne
    private ParentEntity parentEntity;
}

Purpose of ESI & EDI registers?

Opcodes like MOVSB and MOVSW that efficiently copy data from the memory pointed to by ESI to the memory pointed to by EDI. Thus,

mov esi, source_address
mov edi, destination_address
mov ecx, byte_count
cld
rep movsb ; fast!

Draw horizontal rule in React Native

You can also try react-native-hr-component

npm i react-native-hr-component --save

Your code:

import Hr from 'react-native-hr-component'

//..

<Hr text="Some Text" fontSize={5} lineColor="#eee" textPadding={5} textStyles={yourCustomStyles} hrStyles={yourCustomHRStyles} />

The number of method references in a .dex file cannot exceed 64k API 17

Just a side comment, Before adding support for multidex - make sure you are not adding unnecessary dependencies.

For example In the official Facebook analytics guide

They clearly state that you should add the following dependency:

implementation 'com.facebook.android:facebook-android-sdk:[4,5)'

which is actually the entire FacebookSDK - so if you need for example just the Analytics you need to replace it with:

implementation 'com.facebook.android:facebook-core:5.+'

Facebook partial SDK options

How to change the link color in a specific class for a div CSS

If you want to add CSS on a:hover to not all the tag, but the some of the tag, best way to do that is by using class. Give the class to all the tags which you want to give style - see the example below.

<style>
a.change_hover_color:hover { 
    color: white !important;
}
</style>

<a class="change_hover_color">FACEBOOK</a>
<a class="change_hover_color">GOOGLE</a>

Force "portrait" orientation mode

Set force Portrait or Landscape mode, Add lines respectively.

Import below line:

import android.content.pm.ActivityInfo;

Add Below line just above setContentView(R.layout.activity_main);

For Portrait:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait

For Landscap:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape

This will definitely work.

How do you transfer or export SQL Server 2005 data to Excel

Try the 'Import and Export Data (32-bit)' tool. Available after installing MS SQL Management Studio Express 2012.

With this tool it's very easy to select a database, a table or to insert your own SQL query and choose a destination (A MS Excel file for example).

getting the index of a row in a pandas apply function

To access the index in this case you access the name attribute:

In [182]:

df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
    return row['a'] + row['b'] * row['c']

def rowIndex(row):
    return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
   a  b  c   d  rowIndex
0  1  2  3   7         0
1  4  5  6  34         1

Note that if this is really what you are trying to do that the following works and is much faster:

In [198]:

df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
   a  b  c   d
0  1  2  3   7
1  4  5  6  34

In [199]:

%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop

EDIT

Looking at this question 3+ years later, you could just do:

In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df

Out[15]: 
   a  b  c   d  rowIndex
0  1  2  3   7         0
1  4  5  6  34         1

but assuming it isn't as trivial as this, whatever your rowFunc is really doing, you should look to use the vectorised functions, and then use them against the df index:

In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df

Out[16]: 
   a  b  c   d  rowIndex  newCol
0  1  2  3   7         0       6
1  4  5  6  34         1      16

Truncate with condition

The short answer is no: MySQL does not allow you to add a WHERE clause to the TRUNCATE statement. Here's MySQL's documentation about the TRUNCATE statement.

But the good news is that you can (somewhat) work around this limitation.

Simple, safe, clean but slow solution using DELETE

First of all, if the table is small enough, simply use the DELETE statement (it had to be mentioned):

1. LOCK TABLE my_table WRITE;
2. DELETE FROM my_table WHERE my_date<DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. UNLOCK TABLES;

The LOCK and UNLOCK statements are not compulsory, but they will speed things up and avoid potential deadlocks.

Unfortunately, this will be very slow if your table is large... and since you are considering using the TRUNCATE statement, I suppose it's because your table is large.

So here's one way to solve your problem using the TRUNCATE statement:

Simple, fast, but unsafe solution using TRUNCATE

1. CREATE TABLE my_table_backup AS
      SELECT * FROM my_table WHERE my_date>=DATE_SUB(NOW(), INTERVAL 1 MONTH);
2. TRUNCATE my_table;
3. LOCK TABLE my_table WRITE, my_table_backup WRITE;
4. INSERT INTO my_table SELECT * FROM my_table_backup;
5. UNLOCK TABLES;
6. DROP TABLE my_table_backup;

Unfortunately, this solution is a bit unsafe if other processes are inserting records in the table at the same time:

  • any record inserted between steps 1 and 2 will be lost
  • the TRUNCATE statement resets the AUTO-INCREMENT counter to zero. So any record inserted between steps 2 and 3 will have an ID that will be lower than older IDs and that might even conflict with IDs inserted at step 4 (note that the AUTO-INCREMENT counter will be back to it's proper value after step 4).

Unfortunately, it is not possible to lock the table and truncate it. But we can (somehow) work around that limitation using RENAME.

Half-simple, fast, safe but noisy solution using TRUNCATE

1. RENAME TABLE my_table TO my_table_work;
2. CREATE TABLE my_table_backup AS
     SELECT * FROM my_table_work WHERE my_date>DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. TRUNCATE my_table_work;
4. LOCK TABLE my_table_work WRITE, my_table_backup WRITE;
5. INSERT INTO my_table_work SELECT * FROM my_table_backup;
6. UNLOCK TABLES;
7. RENAME TABLE my_table_work TO my_table;
8. DROP TABLE my_table_backup;

This should be completely safe and quite fast. The only problem is that other processes will see table my_table disappear for a few seconds. This might lead to errors being displayed in logs everywhere. So it's a safe solution, but it's "noisy".

Disclaimer: I am not a MySQL expert, so these solutions might actually be crappy. The only guarantee I can offer is that they work fine for me. If some expert can comment on these solutions, I would be grateful.

How to create an exit message

The abort function does this. For example:

abort("Message goes here")

Note: the abort message will be written to STDERR as opposed to puts which will write to STDOUT.

How do I uninstall a Windows service if the files do not exist anymore?

-Windows+r open cmd.

-sc YourSeviceName this code remove your service.

-Uninstal "YourService Path" this code uninstall your service.

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

Finding median of list in Python

A simple function to return the median of the given list:

def median(lst):
    lst.sort()  # Sort the list first
    if len(lst) % 2 == 0:  # Checking if the length is even
        # Applying formula which is sum of middle two divided by 2
        return (lst[len(lst) // 2] + lst[(len(lst) - 1) // 2]) / 2
    else:
        # If length is odd then get middle value
        return lst[len(lst) // 2]

Some examples with the medain function:

>>> median([9, 12, 20, 21, 34, 80])  # Even
20.5
>>> median([9, 12, 80, 21, 34])  # Odd
21

If you want to use library you can just simply do:

>>> import statistics
>>> statistics.median([9, 12, 20, 21, 34, 80])  # Even
20.5
>>> statistics.median([9, 12, 80, 21, 34])  # Odd
21

Visual Studio: Relative Assembly References Paths

As mentioned before, you can manually edit your project's .csproj file in order to apply it manually.

I also noticed that Visual Studio 2013 attempts to apply a relative path to the reference hintpath, probably because of an attempt to make the project file more portable.

Computed / calculated / virtual / derived columns in PostgreSQL

A lightweight solution with Check constraint:

CREATE TABLE example (
    discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);

check null,empty or undefined angularjs

You can do

if($scope.test == null || $scope.test === ""){
  // null == undefined
}

if false, 0 and NaN can also be considered as false values you can just do

if($scope.test){
 //not any of the above
}

Which are more performant, CTE or temporary tables?

I'd say they are different concepts but not too different to say "chalk and cheese".

  • A temp table is good for re-use or to perform multiple processing passes on a set of data.

  • A CTE can be used either to recurse or to simply improved readability.
    And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query

  • A temp table is another table with some rules around scope

I have stored procs where I use both (and table variables too)

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How do I convert datetime.timedelta to minutes, hours in Python?

A datetime.timedelta corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).

If you want to convert a timedelta into hours and minutes, you can use the total_seconds() method to get the total number of seconds and then do some math:

x = datetime.timedelta(1, 5, 41038)  # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60

Trigger change() event when setting <select>'s value with val() function

As jQuery won't trigger native change event but only triggers its own change event. If you bind event without jQuery and then use jQuery to trigger it the callbacks you bound won't run !

The solution is then like below (100% working) :

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

Get column from a two dimensional array

Taking a column is easy with the map function.

// a two-dimensional array
var two_d = [[1,2,3],[4,5,6],[7,8,9]];

// take the third column
var col3 = two_d.map(function(value,index) { return value[2]; });

Why bother with the slice at all? Just filter the matrix to find the rows of interest.

var interesting = two_d.filter(function(value,index) {return value[1]==5;});
// interesting is now [[4,5,6]]

Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

Python Git Module experiences?

While this question was asked a while ago and I don't know the state of the libraries at that point, it is worth mentioning for searchers that GitPython does a good job of abstracting the command line tools so that you don't need to use subprocess. There are some useful built in abstractions that you can use, but for everything else you can do things like:

import git
repo = git.Repo( '/home/me/repodir' )
print repo.git.status()
# checkout and track a remote branch
print repo.git.checkout( 'origin/somebranch', b='somebranch' )
# add a file
print repo.git.add( 'somefile' )
# commit
print repo.git.commit( m='my commit message' )
# now we are one commit ahead
print repo.git.status()

Everything else in GitPython just makes it easier to navigate. I'm fairly well satisfied with this library and appreciate that it is a wrapper on the underlying git tools.

UPDATE: I've switched to using the sh module for not just git but most commandline utilities I need in python. To replicate the above I would do this instead:

import sh
git = sh.git.bake(_cwd='/home/me/repodir')
print git.status()
# checkout and track a remote branch
print git.checkout('-b', 'somebranch')
# add a file
print git.add('somefile')
# commit
print git.commit(m='my commit message')
# now we are one commit ahead
print git.status()

Batch file. Delete all files and folders in a directory

You could use robocopy to mirror an empty folder to the folder you are clearing.

robocopy "C:\temp\empty" "C:\temp\target" /E /MIR

It also works if you can't remove or recreate the actual folder.

It does require an existing empty directory.

Git's famous "ERROR: Permission to .git denied to user"

After Googling for few days, I found this is the only question similar to my situation.

However, I just solved the problem! So I am putting my answer here to help anyone else searching for this issue.

Here is what I did:

  1. Open "Keychain Access.app" (You can find it in Spotlight or LaunchPad)

  2. Select "All items" in Category

  3. Search "git"

  4. Delete every old & strange item

  5. Try to Push again and it just WORKED

How to get the month name in C#?

Use the "MMMM" format specifier:

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

How can I add the new "Floating Action Button" between two widgets/layouts

Here is one aditional free Floating Action Button library for Android. It has many customizations and requires SDK version 9 and higher

enter image description here

Full Demo Video

dependencies {
    compile 'com.scalified:fab:1.1.2'
}

response.sendRedirect() from Servlet to JSP does not seem to work

I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:

response.sendRedirect("simpleList.do")

In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.

Changing Node.js listening port

There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

If you're having problems finding a port that's open, you can go to the command line and type:

netstat -ano

To see a list of all ports in use per adapter.

Getting the last element of a split string array

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

Android Relative Layout Align Center

Is this what you need?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp" >

        <ImageView
            android:id="@+id/place_category_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:contentDescription="ss"
            android:paddingRight="15dp"
            android:paddingTop="10dp"
            android:src="@drawable/marker" />

        <TextView
            android:id="@+id/place_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Place Name"
            android:textColor="#F00F00"
            android:layout_gravity="center_vertical"
            android:textSize="14sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/place_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:layout_gravity="center_vertical"
            android:text="320" />
    </TableRow>

</RelativeLayout>

Python return statement error " 'return' outside function"

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Laravel Eloquent limit and offset

You can use skip and take functions as below:

$products = $art->products->skip($offset*$limit)->take($limit)->get();

// skip should be passed param as integer value to skip the records and starting index

// take gets an integer value to get the no. of records after starting index defined by skip

EDIT

Sorry. I was misunderstood with your question. If you want something like pagination the forPage method will work for you. forPage method works for collections.

REf : https://laravel.com/docs/5.1/collections#method-forpage

e.g

$products = $art->products->forPage($page,$limit);

Parse strings to double with comma and point

To treat both , and . as decimal point you must not only replace one with the other, but also make sure the Culture used parsing interprets it as a decimal point.

text = text.Replace(',', '.');
return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value);

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You were close:

IF EXISTS (SELECT * FROM Table WHERE FieldValue='')
   SELECT TableID FROM Table WHERE FieldValue=''
ELSE
BEGIN
   INSERT INTO TABLE (FieldValue) VALUES ('')
   SELECT TableID FROM Table WHERE TableID=SCOPE_IDENTITY()
END

Simple Pivot Table to Count Unique Values

You can make an additional column to store the uniqueness, then sum that up in your pivot table.

What I mean is, cell C1 should always be 1. Cell C2 should contain the formula =IF(COUNTIF($A$1:$A1,$A2)*COUNTIF($B$1:$B1,$B2)>0,0,1). Copy this formula down so cell C3 would contain =IF(COUNTIF($A$1:$A2,$A3)*COUNTIF($B$1:$B2,$B3)>0,0,1) and so on.

If you have a header cell, you'll want to move these all down a row and your C3 formula should be =IF(COUNTIF($A$2:$A2,$A3)*COUNTIF($B$2:$B2,$B3)>0,0,1).

Copy Paste in Bash on Ubuntu on Windows

That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.

Browser: Identifier X has already been declared

But I have declared that var in the top of the other files.

That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const.

Instead, use var, use only one declaration in your main file, or only assign to window.APP exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.

conditional Updating a list using LINQ

You need:

li.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);

Program code:

namespace Test
{
    class Program
    {
        class Myclass
        {
            public string name { get; set; }
            public decimal age { get; set; }
        }

        static void Main(string[] args)
        {
            var list = new List<Myclass> { new Myclass{name = "di", age = 0}, new Myclass{name = "marks", age = 0}, new Myclass{name = "grade", age = 0}};
            list.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
            list.ForEach(i => Console.WriteLine(i.name + ":" + i.age));
        }
    }
}

Output:

 di:10
 marks:0
 grade:0

Git blame -- prior commits?

Building on DavidN's answer and I want to follow renamed file:

LINE=8 FILE=Info.plist; for commit in $(git log --format='%h%%' --name-only --follow -- $FILE | xargs echo | perl -pe 's/\%\s/,/g'); do hash=$(echo $commit | cut -f1 -d ','); fileMayRenamed=$(echo $commit | cut -f2 -d ','); git blame -n -L$LINE,+1 $hash -- $fileMayRenamed; done | sed '$!N; /^\(.*\)\n\1$/!P; D'

ref: nicely display file rename history in git log

no match for ‘operator<<’ in ‘std::operator

Object is a collection of methods and variables.You can't print the variables in object by just cout operation . if you want to show the things inside the object you have to declare either a getter or a display text method in class.

ex

#include <iostream>

using namespace std;

class mystruct

{
private:
    int m_a;
    float m_b;

public:
    mystruct(int x, float y)
    {
            m_a = x;
            m_b = y;
    }
    public:
    void getm_aAndm_b()
    {
        cout<<m_a<<endl;
        cout<<m_b<<endl;
    }



};

int main()
{

    mystruct m = mystruct(5,3.14);

    cout << "my structure " << endl;
    m.getm_aAndm_b();
    return 0;

}

Not that this is just a one way of doing it

How can I make the browser wait to display the page until it's fully loaded?

Here's a solution using jQuery:

<script type="text/javascript">
$('#container').css('opacity', 0);
$(window).load(function() {
  $('#container').css('opacity', 1);
});
</script>

I put this script just after my </body> tag. Just replace "#container" with a selector for the DOM element(s) you want to hide. I tried several variations of this (including .hide()/.show(), and .fadeOut()/.fadeIn()), and just setting the opacity seems to have the fewest ill effects (flicker, changing page height, etc.). You can also replace css('opacity', 0) with fadeTo(100, 1) for a smoother transition. (No, fadeIn() won't work, at least not under jQuery 1.3.2.)

Now the caveats: I implemented the above because I'm using TypeKit and there's an annoying flicker when you refresh the page and the fonts take a few hundred milliseconds to load. So I don't want any text to appear on the screen until TypeKit has loaded. But obviously you're in big trouble if you use the code above and something on your page fails to load. There are two obvious ways that it could be improved:

  1. A maximum time limit (say, 1 second) after which everything appears whether the page is loaded or not
  2. Some kind of loading indicator (say, something from http://www.ajaxload.info/)

I won't bother implementing the loading indicator here, but the time limit is easy. Just add this to the script above:

$(document).ready(function() {
  setTimeout('$("#container").css("opacity", 1)', 1000);
});

So now, worst-case scenario, your page will take an extra second to appear.

Laravel where on relationship object

    return Deal::with(["redeem" => function($q){
        $q->where('user_id', '=', 1);
    }])->get();

this worked for me

How to do a SOAP Web Service call from Java class?

I understand your problem boils down to how to call a SOAP (JAX-WS) web service from Java and get its returning object. In that case, you have two possible approaches:

  1. Generate the Java classes through wsimport and use them; or
  2. Create a SOAP client that:
    1. Serializes the service's parameters to XML;
    2. Calls the web method through HTTP manipulation; and
    3. Parse the returning XML response back into an object.


About the first approach (using wsimport):

I see you already have the services' (entities or other) business classes, and it's a fact that the wsimport generates a whole new set of classes (that are somehow duplicates of the classes you already have).

I'm afraid, though, in this scenario, you can only either:

  • Adapt (edit) the wsimport generated code to make it use your business classes (this is difficult and somehow not worth it - bear in mind everytime the WSDL changes, you'll have to regenerate and readapt the code); or
  • Give up and use the wsimport generated classes. (In this solution, you business code could "use" the generated classes as a service from another architectural layer.)

About the second approach (create your custom SOAP client):

In order to implement the second approach, you'll have to:

  1. Make the call:
    • Use the SAAJ (SOAP with Attachments API for Java) framework (see below, it's shipped with Java SE 1.6 or above) to make the calls; or
    • You can also do it through java.net.HttpUrlconnection (and some java.io handling).
  2. Turn the objects into and back from XML:
    • Use an OXM (Object to XML Mapping) framework such as JAXB to serialize/deserialize the XML from/into objects
    • Or, if you must, manually create/parse the XML (this can be the best solution if the received object is only a little bit differente from the sent one).

Creating a SOAP client using classic java.net.HttpUrlConnection is not that hard (but not that simple either), and you can find in this link a very good starting code.

I recommend you use the SAAJ framework:

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "https://www.w3schools.com/xml/tempconvert.asmx";
        String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "https://www.w3schools.com/xml/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="https://www.w3schools.com/xml/">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:CelsiusToFahrenheit>
                        <myNamespace:Celsius>100</myNamespace:Celsius>
                    </myNamespace:CelsiusToFahrenheit>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
        soapBodyElem1.addTextNode("100");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

About using JAXB for serializing/deserializing, it is very easy to find information about it. You can start here: http://www.mkyong.com/java/jaxb-hello-world-example/.

dropping a global temporary table

  1. Down the apache server by running below in putty cd $ADMIN_SCRIPTS_HOME ./adstpall.sh
  2. Drop the Global temporary tables drop table t;

This will workout..

How do I find the parent directory in C#?

If you append ..\.. to your existing path, the operating system will correctly browse the grand-parent folder.

That should do the job:

System.IO.Path.Combine("C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug", @"..\..");

If you browse that path, you will browse the grand-parent directory.

MongoDB relationships: embed or reference?

Well, I'm a bit late but still would like to share my way of schema creation.

I have schemas for everything that can be described by a word, like you would do it in the classical OOP.

E.G.

  • Comment
  • Account
  • User
  • Blogpost
  • ...

Every schema can be saved as a Document or Subdocument, so I declare this for each schema.

Document:

  • Can be used as a reference. (E.g. the user made a comment -> comment has a "made by" reference to user)
  • Is a "Root" in you application. (E.g. the blogpost -> there is a page about the blogpost)

Subdocument:

  • Can only be used once / is never a reference. (E.g. Comment is saved in the blogpost)
  • Is never a "Root" in you application. (The comment just shows up in the blogpost page but the page is still about the blogpost)

How can I find WPF controls by name or type?

If you want to find ALL controls of a specific type, you might be interested in this snippet too

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject parent) 
        where T : DependencyObject
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);

            var childType = child as T;
            if (childType != null)
            {
                yield return (T)child;
            }

            foreach (var other in FindVisualChildren<T>(child))
            {
                yield return other;
            }
        }
    }

How to detect if CMD is running as Administrator/has elevated privileges?

I read many (most?) of the responses, then developed a bat file that works for me in Win 8.1. Thought I'd share it.

setlocal
set runState=user
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" > nul && set runState=admin
whoami /groups | findstr /b /c:"Mandatory Label\System Mandatory Level" > nul && set runState=system
echo Running in state: "%runState%"
if not "%runState%"=="user" goto notUser
  echo Do user stuff...
  goto end
:notUser
if not "%runState%"=="admin" goto notAdmin
  echo Do admin stuff...
  goto end
:notAdmin
if not "%runState%"=="system" goto notSystem
  echo Do admin stuff...
  goto end
:notSystem
echo Do common stuff...
:end

Hope someone finds this useful :)

Getting the index of a particular item in array

The previous answers will only work if you know the exact value you are searching for - the question states that only a partial value is known.

Array.FindIndex(authors, author => author.Contains("xyz"));

This will return the index of the first item containing "xyz".

How do I compare two strings in python?

>>> s1="abc def ghi"
>>> s2="def ghi abc"
>>> s1 == s2  # For string comparison 
False
>>> sorted(list(s1)) == sorted(list(s2)) # For comparing if they have same characters. 
True
>>> sorted(list(s1))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> sorted(list(s2))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

How to delete an element from an array in C#

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

Change window location Jquery

I'm writing common function for change window

this code can be used parallel in all type of project

function changewindow(url,userdata){
    $.ajax({
        type: "POST",
        url: url,
        data: userdata,
        dataType: "html",
        success: function(html){                
            $("#bodycontent").html(html);
        },
        error: function(html){
            alert(html);
        }
    });
}

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

IF a cell contains a string

SEARCH does not return 0 if there is no match, it returns #VALUE!. So you have to wrap calls to SEARCH with IFERROR.

For example...

=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")

or

=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))

Here, IFERROR returns the value from SEARCH when it works; the given value of 0 otherwise.

Passing an array as an argument to a function in C

Passing a multidimensional array as argument to a function. Passing an one dim array as argument is more or less trivial. Let's take a look on more interesting case of passing a 2 dim array. In C you can't use a pointer to pointer construct (int **) instead of 2 dim array. Let's make an example:

void assignZeros(int(*arr)[5], const int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 5; j++) {
            *(*(arr + i) + j) = 0;
            // or equivalent assignment
            arr[i][j] = 0;
        }
    }

Here I have specified a function that takes as first argument a pointer to an array of 5 integers. I can pass as argument any 2 dim array that has 5 columns:

int arr1[1][5]
int arr1[2][5]
...
int arr1[20][5]
...

You may come to an idea to define a more general function that can accept any 2 dim array and change the function signature as follows:

void assignZeros(int ** arr, const int rows, const int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            *(*(arr + i) + j) = 0;
        }
    }
}

This code would compile but you will get a runtime error when trying to assign the values in the same way as in the first function. So in C a multidimensional arrays are not the same as pointers to pointers ... to pointers. An int(*arr)[5] is a pointer to array of 5 elements, an int(*arr)[6] is a pointer to array of 6 elements, and they are a pointers to different types!

Well, how to define functions arguments for higher dimensions? Simple, we just follow the pattern! Here is the same function adjusted to take an array of 3 dimensions:

void assignZeros2(int(*arr)[4][5], const int dim1, const int dim2, const int dim3) {
    for (int i = 0; i < dim1; i++) {
        for (int j = 0; j < dim2; j++) {
            for (int k = 0; k < dim3; k++) {
                *(*(*(arr + i) + j) + k) = 0;
                // or equivalent assignment
                arr[i][j][k] = 0;
            }
        }
    }
}

How you would expect, it can take as argument any 3 dim arrays that have in the second dimensions 4 elements and in the third dimension 5 elements. Anything like this would be OK:

arr[1][4][5]
arr[2][4][5]
...
arr[10][4][5]
...

But we have to specify all dimensions sizes up to the first one.

Filter Java Stream to 1 and only 1 element

I think this way is more simple:

User resultUser = users.stream()
    .filter(user -> user.getId() > 0)
    .findFirst().get();

How to change the type of a field?

demo change type of field mid from string to mongo objectId using mongoose

 Post.find({}, {mid: 1,_id:1}).exec(function (err, doc) {
             doc.map((item, key) => {
                Post.findByIdAndUpdate({_id:item._id},{$set:{mid: mongoose.Types.ObjectId(item.mid)}}).exec((err,res)=>{
                    if(err) throw err;
                    reply(res);
                });
            });
        });

Mongo ObjectId is just another example of such styles as

Number, string, boolean that hope the answer will help someone else.

Mock functions in Go

I would do something like,

Main

var getPage = get_page
func get_page (...

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := getPage(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}

Test

func TestDownloader (t *testing.T) {
    origGetPage := getPage
    getPage = mock_get_page
    defer func() {getPage = origGatePage}()
    // The rest to be written
}

// define mock_get_page and rest of the codes
func mock_get_page (....

And I would avoid _ in golang. Better use camelCase

Java Interfaces/Implementation naming convention

The standard C# convention, which works well enough in Java too, is to prefix all interfaces with an I - so your file handler interface will be IFileHandler and your truck interface will be ITruck. It's consistent, and makes it easy to tell interfaces from classes.

catching stdout in realtime from subprocess

if you run something like this in a thread and save the ffmpeg_time property in a property of a method so you can access it, it would work very nice I get outputs like this: output be like if you use threading in tkinter

input = 'path/input_file.mp4'
output = 'path/input_file.mp4'
command = "ffmpeg -y -v quiet -stats -i \"" + str(input) + "\" -metadata title=\"@alaa_sanatisharif\" -preset ultrafast -vcodec copy -r 50 -vsync 1 -async 1 \"" + output + "\""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
for line in self.process.stdout:
    reg = re.search('\d\d:\d\d:\d\d', line)
    ffmpeg_time = reg.group(0) if reg else ''
    print(ffmpeg_time)

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll("[data-foo]")

will get you all elements with that attribute.

document.querySelectorAll("[data-foo='1']")

will only get you ones with a value of 1.

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

This type of problem can happen when you delete/move files around - in essence making changes to your directory structure. Subversion only checks for changes made in files already added to subversion, not changes made to the directory structure. Instead of using your OS's copy etc commands rather use svn copy etc. Please see http://svnbook.red-bean.com/en/1.7/svn.tour.cycle.html

Further, upon committing changes svn first stores a "summary" of changes in a todo list. Upon performing the svn operations in this todo list it locks the file to prevent other changes while these svn actions are performed. If the svn action is interrupted midway, say by a crash, the file will remain locked until svn could complete the actions in the todo list. This can be "reactivated" by using the svn cleanup command. Please see http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

How to read files and stdout from a running Docker container

A bit late but this is what I'm doing with journald. It's pretty powerful.

You need to be running your docker containers on an OS with systemd-journald.

docker run -d --log-driver=journald myapp

This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:

journalctl CONTAINER_NAME=myapp -f

which will feed it to your console as it is logged,

journalctl CONTAINER_NAME=myapp > output.log

which gives you the whole lot in a file to take away, or

journalctl CONTAINER_NAME=myapp --since=17:45

Plus you can still see the logs via docker logs .... if that's your preference.

No more > my.log or -v "/apps/myapp/logs:/logs" etc

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

I was trying to up the limit Wordpress sets on media uploads. I followed advice from some blog I’m not going to mention to raise the limit from 64MB to 2GB.

I did the following:

Created a (php.ini) file in WP ADMIN with the following integers:

upload_max_filesize = 2000MB
post_max_size = 2100MV
memory_limit = 2300MB

I immediately received this error when trying to log into my Wordpress dashboard to check if it worked:

“Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)"

The above information in this chain helped me tremendously. (Stack usually does BTW)

I modified the PHP.ini file to the following:

upload_max_filesize = 2000M
post_max_size = 2100M
memory_limit = 536870912M

The major difference was only use M, not MB, and set that memory limit high.

As soon as I saved the changed the PHP.ini file, I saved it, went to login again and the login screen reappeared.

I went in and checked media uploads, ands bang:

Image showing twordpress media folder “Add New” box, with limits stated as “MAXIMUM UPLOAD FILE SIZE: 2 GB”

I haven't restarted Apache yet… but all looks good.

Thanks everyone.

How do I show my global Git configuration?

You can also use cat ~/.gitconfig.

How to get the unix timestamp in C#

Updated code from Brad with few things: You don't need Math.truncate, conversion to int or long automatically truncates the value. In my version I am using long instead of int (We will run out of 32 bit signed integers in 2038 year). Also, added timestamp parsing.

public static class DateTimeHelper
{
    /// <summary>
     /// Converts a given DateTime into a Unix timestamp
     /// </summary>
     /// <param name="value">Any DateTime</param>
     /// <returns>The given DateTime in Unix timestamp format</returns>
    public static long ToUnixTimestamp(this DateTime value)
    {
        return (long)(value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Gets a Unix timestamp representing the current moment
    /// </summary>
    /// <param name="ignored">Parameter ignored</param>
    /// <returns>Now expressed as a Unix timestamp</returns>
    public static long UnixTimestamp(this DateTime ignored)
    {
        return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Returns a local DateTime based on provided unix timestamp
    /// </summary>
    /// <param name="timestamp">Unix/posix timestamp</param>
    /// <returns>Local datetime</returns>
    public static DateTime ParseUnixTimestamp(long timestamp)
    {
        return (new DateTime(1970, 1, 1)).AddSeconds(timestamp).ToLocalTime();
    }

}

Remove credentials from Git

In my case, Git is using Windows to store credentials.

All you have to do is remove the stored credentials stored in your Windows account:

Windows credentials menu

Use table row coloring for cells in Bootstrap

Updated html for the newer bootstrap

    .table-hover > tbody > tr.danger:hover > td {
     background-color: red !important;
}
.table-hover > tbody > tr.warning:hover > td {
     background-color: yellow !important;
}
.table-hover > tbody > tr.success:hover > td {
     background-color: blue !important;
}

Test method is inconclusive: Test wasn't run. Error?

For me, the problem was a corrupt NUnit/ReSharper settings XML-file (due to an unexpected power shortage).

To identify the error I started Visual Studio with this command:

devenv.exe /ReSharper.LogFile C:\temp\resharper.log /ReSharper.LogLevel Verbose

Examining the file revealed the following exception:

09:45:31.894 |W| UnitTestLaunch                | System.ApplicationException: Error loading settings file
System.ApplicationException: Error loading settings file ---> System.Xml.XmlException: Root element is missing.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
   at NUnit.Engine.Internal.SettingsStore.LoadSettings()
   --- End of inner exception stack trace ---
   at NUnit.Engine.Internal.SettingsStore.LoadSettings()
   at NUnit.Engine.Services.SettingsService.StartService()
   at NUnit.Engine.Services.ServiceManager.StartServices()
   at NUnit.Engine.TestEngine.Initialize()
   at NUnit.Engine.TestEngine.GetRunner(TestPackage package)
   at JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.<>c__DisplayClass1.<RunTests>b__0()
   at JetBrains.ReSharper.UnitTestRunner.nUnit30.BuiltInNUnitRunner.WithExtensiveErrorHandling(IRemoteTaskServer server, Action action)

Note that this is NOT the test project's app.config!

A quick googling around identified the following file as the culprit:

%LOCALAPPDATA%\NUnit\Nunit30Settings.xml

It existed, but was empty. Deleting it and restarting Visual Studio solved the problem.

(Using Visual Studio Professional 2017 v15.3.5 and ReSharper 2017.2.1).

Input text dialog Android

It's work for me

private void showForgotDialog(Context c) {
        final EditText taskEditText = new EditText(c);
        AlertDialog dialog = new AlertDialog.Builder(c)
                .setTitle("Forgot Password")
                .setMessage("Enter your mobile number?")
                .setView(taskEditText)
                .setPositiveButton("Reset", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String task = String.valueOf(taskEditText.getText());
                    }
                })
                .setNegativeButton("Cancel", null)
                .create();
        dialog.show();
    }

How to call? (Current activity name)

showForgotDialog(current_activity_name.this);

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

In addition to the accepted answer, there's a third option that can be useful in some cases:

v1 with random MAC ("v1mc")

You can make a hybrid between v1 & v4 by deliberately generating v1 UUIDs with a random broadcast MAC address (this is allowed by the v1 spec). The resulting v1 UUID is time dependant (like regular v1), but lacks all host-specific information (like v4). It's also much closer to v4 in it's collision-resistance: v1mc = 60 bits of time + 61 random bits = 121 unique bits; v4 = 122 random bits.

First place I encountered this was Postgres' uuid_generate_v1mc() function. I've since used the following python equivalent:

from os import urandom
from uuid import uuid1
_int_from_bytes = int.from_bytes  # py3 only

def uuid1mc():
    # NOTE: The constant here is required by the UUIDv1 spec...
    return uuid1(_int_from_bytes(urandom(6), "big") | 0x010000000000)

(note: I've got a longer + faster version that creates the UUID object directly; can post if anyone wants)


In case of LARGE volumes of calls/second, this has the potential to exhaust system randomness. You could use the stdlib random module instead (it will probably also be faster). But BE WARNED: it only takes a few hundred UUIDs before an attacker can determine the RNG state, and thus partially predict future UUIDs.

import random
from uuid import uuid1

def uuid1mc_insecure():
    return uuid1(random.getrandbits(48) | 0x010000000000)

How can I view all historical changes to a file in SVN

Slightly different from what you described, but I think this might be what you actually need:

svn blame filename

It will print the file with each line prefixed by the time and author of the commit that last changed it.

Why java.security.NoSuchProviderException No such provider: BC?

You can add security provider by editing java.security with using following code with creating static block:

static {
    Security.addProvider(new BouncyCastleProvider());
}

If you are using maven project, then you will have to add dependency for BouncyCastleProvider as follows in pom.xml file of your project.

<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.47</version>
</dependency>

If you are using normal java project, then you can add download bcprov-jdk15on-147.jar from the link given below and edit your classpath.

http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm

FIND_IN_SET() vs IN()

Let me explain when to use FIND_IN_SET and When to use IN.

Let's take table A which has columns named "aid","aname". Let's take table B which has columns named "bid","bname","aids".

Now there are dummy values in Table A and Table B as below.

Table A

aid aname

1 Apple

2 Banana

3 Mango

Table B

bid bname aids

1 Apple 1,2

2 Banana 2,1

3 Mango 3,1,2

enter code here

Case1: if you want to get those records from table b which has 1 value present in aids columns then you have to use FIND_IN_SET.

Query: select * from A JOIN B ON FIND_IN_SET(A.aid,b.aids) where A.aid = 1 ;

Case2: if you want to get those records from table a which has 1 OR 2 OR 3 value present in aid columns then you have to use IN.

Query: select * from A JOIN B ON A.aid IN (b.aids);

Now here upto you that what you needs through mysql query.

getResources().getColor() is deprecated

You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

ContextCompat.getColor(context, R.color.my_color)

As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.

You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

compile 'com.android.support:support-v4:23.0.1'

Java difference between FileWriter and BufferedWriter

BufferedWriter is more efficient if you

  • have multiple writes between flush/close
  • the writes are small compared with the buffer size.

In your example, you have only one write, so the BufferedWriter just add overhead you don't need.

so does that mean the first example writes the characters one by one and the second first buffers it to the memory and writes it once

In both cases, the string is written at once.

If you use just FileWriter your write(String) calls

 public void write(String str, int off, int len) 
        // some code
        str.getChars(off, (off + len), cbuf, 0);
        write(cbuf, 0, len);
 }

This makes one system call, per call to write(String).


Where BufferedWriter improves efficiency is in multiple small writes.

for(int i = 0; i < 100; i++) {
    writer.write("foorbar");
    writer.write(NEW_LINE);
}
writer.close();

Without a BufferedWriter this could make 200 (2 * 100) system calls and writes to disk which is inefficient. With a BufferedWriter, these can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write.

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

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

jQuery scroll to element

For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling. In our case we don't scroll the full body, but just particular elements with overflow: auto; within a larger layout.

It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.

var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');

$scrollTo.prepend(inputElem);
inputElem.css({
  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();

How can I ping a server port with PHP?

function ping($ip){
    $output = shell_exec("ping $ip");
    var_dump($output);
}
ping('127.0.0.1');

UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.

But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec function: If the IP comes from an untrusted source, at least check it with a filter before using it.

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

Free tool to Create/Edit PNG Images?

Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.

Note--Inkscape is open source and available for free on multiple platforms.

Perl: Use s/ (replace) and return new string

require 5.013002; # or better:    use Syntax::Construct qw(/r);
print "bla: ", $myvar =~ s/a/b/r, "\n";

See perl5132delta:

The substitution operator now supports a /r option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.

my $old = 'cat';
my $new = $old =~ s/cat/dog/r;
# $old is 'cat' and $new is 'dog'

How to make sure you don't get WCF Faulted state exception?


Update:

This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.


Original post

This is Microsoft's recommended way to handle WCF client calls:

For more detail see: Expected Exceptions

try
{
    ...
    double result = client.Add(value1, value2);
    ...
    client.Close();
}
catch (TimeoutException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}
catch (CommunicationException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}

Additional information

So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:

c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client

Download the sample: C# or VB

Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I had this error too because in the file where I used @Transactional annotation, I was importing the wrong class

import javax.transaction.Transactional; 

Instead of javax, use

import org.springframework.transaction.annotation.Transactional; 

Converting string into datetime

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

The resulting datetime object is timezone-naive.

Links:

Notes:

  • strptime = "string parse time"
  • strftime = "string format time"
  • Pronounce it out loud today & you won't have to search for it again in 6 months.

Editor does not contain a main type in Eclipse

For me, classpath entry in .classpath file isn't pointing to the right location. After modifying it to <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/> fixed the issue

MySQL Multiple Where Clause

This might be what you are after, although depending on how many style_id's there are, it would be tricky to implement (not sure if those style_id's are static or not). If this is the case, then it is not really possible what you are wanting as the WHERE clause works on a row to row basis.

WITH cte as (
  SELECT
    image_id,
    max(decode(style_id,24,style_value)) AS style_colour,
    max(decode(style_id,25,style_value)) AS style_size,
    max(decode(style_id,27,style_value)) AS style_shape
  FROM
    list
  GROUP BY
    image_id
)
SELECT
  image_id
FROM
  cte
WHERE
  style_colour = 'red'
  and style_size = 'big'
  and style_shape = 'round'

http://sqlfiddle.com/#!4/fa5cf/18

Has Facebook sharer.php changed to no longer accept detailed parameters?

Facebook no longer supports custom parameters in sharer.php

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Use dialog/feeds instead of sharer.php

https://www.facebook.com/dialog/feed?
  app_id=145634995501895
  &display=popup&caption=An%20example%20caption 
  &link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
  &redirect_uri=https://developers.facebook.com/tools/explorer

Official answer from fb team

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

How do I modify the URL without reloading the page?

You can add anchor tags. I use this on my site so that I can track with Google Analytics what people are visiting on the page.

I just add an anchor tag and then the part of the page I want to track:

var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);

How to find longest string in the table column data

you have to do some changes by applying group by or query with in query.

"SELECT CITY,LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;"

it will return longest cityname from city.

Trying to use fetch and pass in mode: no-cors

Very easy solution (2 min to config) is to use local-ssl-proxy package from npm

The usage is straight pretty forward:
1. Install the package: npm install -g local-ssl-proxy
2. While running your local-server mask it with the local-ssl-proxy --source 9001 --target 9000

P.S: Replace --target 9000 with the -- "number of your port" and --source 9001 with --source "number of your port +1"

how to get the host url using javascript from the current page

I like this one depending of purpose

window.location.href.split("/")[2] == "localhost:17000" //always domain + port

You can apply it on any url-string

var url = "http://localhost:17000/sub1/sub2/mypage.html?q=12";
url.split("/")[2] == "localhost:17000"
url.split("/")[url.split("/").length-1] == "mypage.html?q=12"

Removing protocol, domain & path from url-string (relative path)

var arr = url.split("/");
if (arr.length>3)
   "/" + arr.splice(3, arr.length).join("/") == "/sub1/sub2/mypage.html?q=12"

jQuery UI dialog positioning

a bit late but you can do this now by using $j(object).offset().left and .top accordingly.

Python JSON encoding

I think you are simply exchanging dumps and loads.

>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]

The first returns as a (JSON encoded) string its data argument:

>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

The second does the opposite, returning the data corresponding to its (JSON encoded) string argument:

>>> decoded_data = json.loads( encoded_str )
>>> decoded_data
[[u'apple', u'cat'], [u'banana', u'dog'], [u'pear', u'fish']]
>>> decoded_data == data
True

CR LF notepad++ removal

"View -> Show Symbol -> uncheck Show All characters" may not work if you have pending update for notepad++. So update Notepad++ and then View -> Show Symbol -> uncheck Show All characters

Hope this is helpful!

How can I conditionally require form inputs with AngularJS?

Simple you can use angular validation like :

 <input type='text'
   name='name'
   ng-model='person.name'
   ng-required='!person.lastname'/>

   <input type='text'
   name='lastname'
   ng-model='person.lastname'             
   ng-required='!person.name' /> 

You can now fill the value in only one text field. Either you can fill name or lastname. In this way you can use conditional required fill in AngularJs.

Maintaining href "open in new tab" with an onClick handler in React

Most Secure Solution, JS only

As mentioned by alko989, there is a major security flaw with _blank (details here).

To avoid it from pure JS code:

const openInNewTab = (url) => {
  const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
  if (newWindow) newWindow.opener = null
}

Then add to your onClick

onClick={() => openInNewTab('https://stackoverflow.com')}

The third param can also take these optional values, based on your needs.

How to: "Separate table rows with a line"

HTML

<table cellspacing="0">
  <tr class="top bottom row">
    <td>one one</td>
    <td>one two</td>
  </tr>
  <tr class="top bottom row">
    <td>two one</td>
    <td>two two</td>
  </tr>
  <tr class="top bottom row">
    <td>three one</td>
    <td>three two</td>
  </tr>

</table>?

CSS:

tr.top td { border-top: thin solid black; }
tr.bottom td { border-bottom: thin solid black; }
tr.row td:first-child { border-left: thin solid black; }
tr.row td:last-child { border-right: thin solid black; }?

DEMO

Call method in directive controller from other controller

I got much better solution .

here is my directive , I have injected on object reference in directive and has extend that by adding invoke function in directive code .

app.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
        /*The object that passed from the cntroller*/
        objectToInject: '=',
        },
        templateUrl: 'templates/myTemplate.html',

        link: function ($scope, element, attrs) {
            /*This method will be called whet the 'objectToInject' value is changes*/
            $scope.$watch('objectToInject', function (value) {
                /*Checking if the given value is not undefined*/
                if(value){
                $scope.Obj = value;
                    /*Injecting the Method*/
                    $scope.Obj.invoke = function(){
                        //Do something
                    }
                }    
            });
        }
    };
});

Declaring the directive in the HTML with a parameter:

<my-directive object-to-inject="injectedObject"></ my-directive>

my Controller:

app.controller("myController", ['$scope', function ($scope) {
   // object must be empty initialize,so it can be appended
    $scope.injectedObject = {};

    // now i can directly calling invoke function from here 
     $scope.injectedObject.invoke();
}];

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

SVN: Is there a way to mark a file as "do not commit"?

Guys I just found a solution. Given that TortoiseSVN works the way we want, I tried to install it under Linux - which means, running on Wine. Surprisingly it works! All you have to do is:

  1. Add files you want to skip commit by running: "svn changelist 'ignore-on-commit' ".
  2. Use TortoiseSVN to commit: "~/.wine/drive_c/Program\ Files/TortoiseSVN/bin/TortoiseProc.exe /command:commit /path:'
  3. The files excluded will be unchecked for commit by default, while other modified files will be checked. This is exactly the same as under Windows. Enjoy!

(The reason why need to exclude files by CLI is because the menu entry for doing that was not found, not sure why. Any way, this works great!)

Why is SQL Server 2008 Management Studio Intellisense not working?

I'm posting this here as I am sure more people will be comeing across this issue. I installed Security Update for microsoft Visual Studio 2010 Service Pack 1 (KB2565057) and lost Intellisense in SQL Server Management studio 2008 (not R2).

An uninstall of the SP restored Intellisense .. Don't you just love Microsoft????

Regular expression to extract numbers from a string

you could use something like:

[^0-9]+([0-9]+)[^0-9]+([0-9]+).+

Then get the first and second capture groups.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

Go to PhpMyAdmin, click on desired database, go to Privilages tab and create new user "remote", and give him all privilages and in host field set "Any host" option(%).

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

How to lay out Views in RelativeLayout programmatically?

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);

All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.

TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);

Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

IE7 Z-Index Layering Issues

If the previously mentioned higher z-indexing in parent nodes wont suit your needs, you can create alternative solution and target it to problematic browsers either by IE conditional comments or using the (more idealistic) feature detection provided by Modernizr.

Quick (and obviously working) test for Modernizr:

Modernizr.addTest('compliantzindex', function(){
    var test  = document.createElement('div'),
        fake = false,
        root = document.body || (function () {
            fake = true;
            return document.documentElement.appendChild(document.createElement('body'));
        }());

    root.appendChild(test);
    test.style.position = 'relative';
    var ret = (test.style.zIndex !== 0);
    root.removeChild(test);

    if (fake) {
        document.documentElement.removeChild(root);
    }

    return ret;
});

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

This should make it work in both cases

function onDateChange() {
   // Do something here
}

$('#dpd1').bind('changeDate', onDateChange);
$('#dpd1').bind('input', onDateChange);

How to split a string by spaces in a Windows batch file?

Here is a solution based on a "function" which processes each character until it finds the delimiter character.

It is relatively slow, but it is at least not a brain teaser (except for the function part).

:: Example #1:
set data=aa bb cc
echo Splitting off from "%data%":
call :split_once "%data%" " " "left" "right"
echo Split off: %left%
echo Remaining: %right%
echo.

:: Example #2:
echo List of paths in PATH env var:
set paths=%PATH%
:loop
    call :split_once "%paths%" ";" "left" "paths"
    if "%left%" equ "" goto loop_end
    echo %left%
goto loop
:loop_end



:: HERE BE FUNCTIONS
goto :eof

:: USAGE:
::   call :split_once "string to split once" "delimiter_char" "left_var" "right_var"
:split_once
    setlocal
    set right=%~1
    set delimiter_char=%~2
    set left=

    if "%right%" equ "" goto split_once_done

    :split_once_loop
        if "%right:~0,1%" equ "%delimiter_char%" set right=%right:~1%&& goto split_once_done
        if "%right:~0,1%" neq "%delimiter_char%" set left=%left%%right:~0,1%
        if "%right:~0,1%" neq "%delimiter_char%" set right=%right:~1%
        if "%right%" equ "" goto split_once_done
    goto split_once_loop

    :split_once_done
    endlocal & set %~3=%left%& set %~4=%right%
goto:eof

git rm - fatal: pathspec did not match any files

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won't be tracked further.

How can I use "e" (Euler's number) and power operation in python 2.7

Power is ** and e^ is math.exp:

x.append(1 - math.exp(-0.5 * (value1*value2)**2))

Call an activity method from a fragment

((your_activity) getActivity).method_name()

Where your_activity is the name of your activity and method_name() is the name of the method you want to call.

PHP not displaying errors even though display_errors = On

I also face the same issue, I have the following settings in my php.inni file

display_errors = On
error_reporting=E_ALL & ~E_DEPRECATED & ~E_STRICT

But still, PHP errors are not displaying on the webpage. I just restart my apache server and this problem was fixed.

Bootstrap 3 Align Text To Bottom of Div

You can do this:

CSS:

#container {
    height:175px;
}

#container h3{
    position:absolute;
    bottom:0;
    left:0;
}

Then in HTML:

<div class="row">
    <div class="col-sm-6">
        <img src="//placehold.it/600x300" alt="Logo" />
    </div>
    <div id="container" class="col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

EDIT: add the <

How do I upload a file with the JS fetch API?

Here is my code:

html:

_x000D_
_x000D_
const upload = (file) => {_x000D_
    console.log(file);_x000D_
_x000D_
    _x000D_
_x000D_
    fetch('http://localhost:8080/files/uploadFile', { _x000D_
    method: 'POST',_x000D_
    // headers: {_x000D_
    //   //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'",_x000D_
    //   "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" //  ? // multipart/form-data _x000D_
    // },_x000D_
    body: file // This is your file object_x000D_
  }).then(_x000D_
    response => response.json() // if the response is a JSON object_x000D_
  ).then(_x000D_
    success => console.log(success) // Handle the success response object_x000D_
  ).catch(_x000D_
    error => console.log(error) // Handle the error response object_x000D_
  );_x000D_
_x000D_
  //cvForm.submit();_x000D_
};_x000D_
_x000D_
const onSelectFile = () => upload(uploadCvInput.files[0]);_x000D_
_x000D_
uploadCvInput.addEventListener('change', onSelectFile, false);
_x000D_
<form id="cv_form" style="display: none;"_x000D_
          enctype="multipart/form-data">_x000D_
          <input id="uploadCV" type="file" name="file"/>_x000D_
          <button type="submit" id="upload_btn">upload</button>_x000D_
</form>_x000D_
<ul class="dropdown-menu">_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Bootstrap carousel width and height

just put height="400px" into image attribute like

<img class="d-block w-100" src="../assets/img/natural-backdrop.jpg" height="400px" alt="First slide">

After installing SQL Server 2014 Express can't find local db

Just download and install LocalDB 64BIT\SqlLocalDB.msi can also solve this problem. You don't really need to uninstall and reinstall SQL Server 2014 Express with Advanced Services.

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

General sibling combinator

The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.

More info

Copy rows from one table to another, ignoring duplicates

I hope this query will help you

INSERT INTO `dTable` (`field1`, `field2`)
SELECT field1, field2 FROM `sTable` 
WHERE `sTable`.`field1` NOT IN (SELECT `field1` FROM `dTable`)

how to make div click-able?

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

`ui-router` $stateParams vs. $state.params

Another reason to use $state.params is for non-URL based state, which (to my mind) is woefully underdocumented and very powerful.

I just discovered this while googling about how to pass state without having to expose it in the URL and answered a question elsewhere on SO.

Basically, it allows this sort of syntax:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

how to import csv data into django models

This is based off of Erik's answer from earlier, but I've found it easiest to read in the .csv file using pandas and then create a new instance of the class for every row in the in data frame.

This example is updated using iloc as pandas no longer uses ix in the most recent version. I don't know about Erik's situation but you need to create the list outside of the for loop otherwise it will not append to your array but simply overwrite it.

import pandas as pd
df = pd.read_csv('path_to_file', sep='delimiter')
products = []
for i in range(len(df)):
    products.append(
        Product(
        name=df.iloc[i][0]
        description=df.iloc[i][1]
        price=df.iloc[i][2]
        )
    )
Product.objects.bulk_create(products)

This is just breaking the DataFrame into an array of rows and then selecting each column out of that array off the zero index. (i.e. name is the first column, description the second, etc.)

Hope that helps.

Regex AND operator

Maybe just an OR operator | could be enough for your problem:

String: foo,bar,baz

Regex: (foo)|(baz)

Result: ["foo", "baz"]

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

How can I set the default timezone in node.js?

Update for node.js v13

As @Tom pointed out, full icu support is built in v13 now. So the setup steps can be omitted. You can still customize how you want to build or use icu in runtime: https://nodejs.org/api/intl.html

For node.js on Windows, you can do the following:

  1. Install full-icu if it has been installed, which applies date locales properly

    npm i full-icu or globally: npm i -g full-icu

  2. Use toLocaleString() in your code, e.g.:

    new Date().toLocaleString('en-AU', { timeZone: 'Australia/Melbourne' })

    This will produce something like: 25/02/2019, 3:19:22 pm. If you prefer 24 hours, 'en-GB' will produce: 25/02/2019, 15:19:22

For node.js as Azure web app, in addition to application settings of WEBSITE_TIME_ZONE, you also need to set NODE_ICU_DATA to e.g. <your project>\node_modules\full-icu, of course after you've done the npm i full-icu. Installing the package globally on Azure is not suggested as that directory is temporary and can be wiped out.

Ref: 1. NodeJS not applying date locales properly

  1. You can also build node.js with intl options, more information here

How do I size a UITextView to its content?

Using UITextViewDelegate is the easiest way:

func textViewDidChange(_ textView: UITextView) {
    textView.sizeToFit()
    textviewHeight.constant = textView.contentSize.height
}

HTML5 - mp4 video does not play in IE9

Ended up using http://videojs.com/ to support all browsers.

But to get the video working in IE9 and Chrome I just added html5 doc type and used mp4:

<!DOCTYPE html>
<html>
<body>
  <video src="video.mp4" width="400" height="300" preload controls>
  </video>
</body>
</html>

Load local HTML file in a C# WebBrowser

Windows 10 uwp application.

Try this:

webview.Navigate(new Uri("ms-appx-web:///index.html"));

Endless loop in C/C++

The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.

Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.

The while(1), while(true) and for(;;) are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.


for(;;)

  • This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:

    K&R 2nd ed 3.5:

    for (;;) {
    ...
    }
    

    is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.

    For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;), this would have been regarded as the most correct form at least up until the C standardization in 1990.

    However, K&R themselves already stated that it was a matter of preference.

    And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.

    But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;).

  • The argument against the for(;;) loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:

    ISO 9899:2011 6.8.5.3:

    for ( clause-1 ; expression-2 ; expression-3 ) statement
    

    /--/

    Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

    Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.


while(1)

  • This is supposedly a more readable form than for(;;). However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.

  • There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1), when the programmer intended to write while(i == 1).

    Also, external static code analysers are likely to whine about "condition is always true".


while(true)

  • To make while(1) even more readable, some use while(true) instead. The consensus among programmers seem to be that this is the most readable form.

  • However, this form has the same problem as while(1), as described above: "condition is always true" warnings.

  • When it comes to C, this form has another disadvantage, namely that it uses the macro true from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool exists as a primitive data type and true is a language keyword.

  • Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.


So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.

Personally, I always use for(;;) just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:

If even a C beginner knows that for(;;) means an eternal loop, then who are you trying to make the code more readable for?

I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.

And since everyone who should be reading your code already knows what for(;;) means, there is no point in making it further readable - it is already as readable as it gets.

Shift elements in a numpy array

Benchmarks & introducing Numba

1. Summary

  • The accepted answer (scipy.ndimage.interpolation.shift) is the slowest solution listed in this page.
  • Numba (@numba.njit) gives some performance boost when array size smaller than ~25.000
  • "Any method" equally good when array size large (>250.000).
  • The fastest option really depends on
        (1)  Length of your arrays
        (2)  Amount of shift you need to do.
  • Below is the picture of the timings of all different methods listed on this page (2020-07-11), using constant shift = 10. As one can see, with small array sizes some methods are use more than +2000% time than the best method.

Relative timings, constant shift (10), all methods

2. Detailed benchmarks with the best options

  • Choose shift4_numba (defined below) if you want good all-arounder

Relative timings, best methods (Benchmarks)

3. Code

3.1 shift4_numba

  • Good all-arounder; max 20% wrt. to the best method with any array size
  • Best method with medium array sizes: ~ 500 < N < 20.000.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift4_numba(arr, num, fill_value=np.nan):
    if num >= 0:
        return np.concatenate((np.full(num, fill_value), arr[:-num]))
    else:
        return np.concatenate((arr[-num:], np.full(-num, fill_value)))

3.2. shift5_numba

  • Best option with small (N <= 300.. 1500) array sizes. Treshold depends on needed amount of shift.
  • Good performance on any array size; max + 50% compared to the fastest solution.
  • Caveat: Numba jit (just in time compiler) will give performance boost only if you are calling the decorated function more than once. The first call takes usually 3-4 times longer than the subsequent calls.
import numba

@numba.njit
def shift5_numba(arr, num, fill_value=np.nan):
    result = np.empty_like(arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else:
        result[:] = arr
    return result

3.3. shift5

  • Best method with array sizes ~ 20.000 < N < 250.000
  • Same as shift5_numba, just remove the @numba.njit decorator.

4 Appendix

4.1 Details about used methods

  • shift_scipy: scipy.ndimage.interpolation.shift (scipy 1.4.1) - The option from accepted answer, which is clearly the slowest alternative.
  • shift1: np.roll and out[:num] xnp.nan by IronManMark20 & gzc
  • shift2: np.roll and np.put by IronManMark20
  • shift3: np.pad and slice by gzc
  • shift4: np.concatenate and np.full by chrisaycock
  • shift5: using two times result[slice] = x by chrisaycock
  • shift#_numba: @numba.njit decorated versions of the previous.

The shift2 and shift3 contained functions that were not supported by the current numba (0.50.1).

4.2 Other test results

4.2.1 Relative timings, all methods

4.2.2 Raw timings, all methods

4.2.3 Raw timings, few best methods

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

How to load a jar file at runtime

I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

In my case i solved this issue by:
1) placing NgxMaterialTimepickerModule in app module imports:[ ]
2) placing NgxMaterialTimepickerModule in testmodule.ts imports:[ ]
3) placing testcomponent in declartions:[ ] and entryComponents:[ ]

(I'm using angular 8+ version)

Undo working copy modifications of one file in Git?

I restore my files using the SHA id, What i do is git checkout <sha hash id> <file name>

Show all current locks from get_lock

If you just want to determine whether a particular named lock is currently held, you can use IS_USED_LOCK:

SELECT IS_USED_LOCK('foobar');

If some connection holds the lock, that connection's ID will be returned; otherwise, the result is NULL.

Program "make" not found in PATH

If you are using GNU MCU Eclipse on Windows, make sure Windows Build Tools are installed, then check the installation path and fill the "Global Build Tools Path" inside Eclipse Window/Preferences... :

Global Build Tools Path

How to draw circle by canvas in Android?

@Override
public void onDraw(Canvas canvas){
    canvas.drawCircle(xPos, yPos,radius, paint);
}

Above is the code to render a circle. Tweak the parameters to your suiting.

Post parameter is always null

I'm a little late to the party, but anyone who stumbles across a NULL value passed when using a controller simply add "=" to the front of your POST request.

The controller also passed a NULL value when I used the application/json Content-Type. Note the "application/x-www-form-urlencoded" Content-Type below. The return type from the API however is "application/json".

 public static string HttpPostRequest(string url, Dictionary<string, string> postParameters)
    {
        string postData = "=";

        foreach (string key in postParameters.Keys)
        {
            postData += HttpUtility.UrlEncode(key) + "="
                  + HttpUtility.UrlEncode(postParameters[key]) + ",";
        }

        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
        myHttpWebRequest.Method = "POST";

        byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

        myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
        myHttpWebRequest.ContentLength = data.Length;

        Stream requestStream = myHttpWebRequest.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

        Stream responseStream = myHttpWebResponse.GetResponseStream();

        StreamReader myStreamReader = new StreamReader(responseStream, System.Text.Encoding.Default);

        string pageContent = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        responseStream.Close();

        myHttpWebResponse.Close();

        return pageContent;
    }

Rerender view on browser resize with React

Update in 2020. For React devs who care performance seriously.

Above solutions do work BUT will re-render your components whenever the window size changes by a single pixel.

This often causes performance issues so I wrote useWindowDimension hook that debounces the resize event for a short period of time. e.g 100ms

import React, { useState, useEffect } from 'react';

export function useWindowDimension() {
  const [dimension, setDimension] = useState([
    window.innerWidth,
    window.innerHeight,
  ]);
  useEffect(() => {
    const debouncedResizeHandler = debounce(() => {
      console.log('***** debounced resize'); // See the cool difference in console
      setDimension([window.innerWidth, window.innerHeight]);
    }, 100); // 100ms
    window.addEventListener('resize', debouncedResizeHandler);
    return () => window.removeEventListener('resize', debouncedResizeHandler);
  }, []); // Note this empty array. this effect should run only on mount and unmount
  return dimension;
}

function debounce(fn, ms) {
  let timer;
  return _ => {
    clearTimeout(timer);
    timer = setTimeout(_ => {
      timer = null;
      fn.apply(this, arguments);
    }, ms);
  };
}

Use it like this.

function YourComponent() {
  const [width, height] = useWindowDimension();
  return <>Window width: {width}, Window height: {height}</>;
}

How to style an asp.net menu with CSS

The thing to look at is what HTML is being spit out by the control. In this case it puts out a table to create the menu. The hover style is set on the TD and once you select a menu item the control posts back and adds the selected style to the A tag of the link within the TD.

So you have two different items that are being manipulated here. One is a TD element and another is an A element. So, you have to make your CSS work accordingly. If I add the below CSS to a page with the menu then I get the expected behavior of the background color changing in either case. You may be doing some different CSS manipulation that may or may not apply to those elements.

<style>
    .StaticHoverStyle
    {
        background: #000000;
    }

    .StaticSelectedStyle
    {
        background: blue;
    }
</style>

How to make an HTML back link?

For going back to previous page using Anchor Tag <a>, below are 2 working methods and out of them 1st one is faster and have one great advantage in going back to previous page.

I have tried both methods.

1)

<a href="#" onclick="location.href = document.referrer; return false;">Go Back</a>

Above method (1) works great if you have clicked on a link and opened link in a New Tab in current browser window.

2)

<a href="javascript:history.back()">Go Back</a>

Above method (2) only works ok if you have clicked on a link and opened link in a Current Tab in current browser window.

It will not work if you have open link in New Tab. Here history.back() will not work if link is opened in New Tab of web browser.

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

How does Spring autowire by name when more than one matching bean is found?

One more solution with resolving by name:

@Resource(name="country")

It uses javax.annotation package, so it's not Spring specific, but Spring supports it.

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS