Programs & Examples On #Spotlight

Spotlight on Mac OS X is a fast desktop search technology that allows users to organize and search for files based on metadata. Spotlight is extensible, allowing developers to provide metadata importers for their application’s documents.

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

As programmers we want the quickest, most fool-proof way to get our tools in order so we can start hacking. Here are how I got it to work in MacOS 10.13.1 (High Sierra):

  • Option 1: Go to System Preferences | Keyboard | Shortcut | Services. Under Files and Folders section, enable New Terminal at Folder and/or New Terminal Tab at Folder and assign a shortcut key to it. Keyboard shortcut config

  • Option 2: If you want the shortcut key to work anywhere, create a new Service using Automator, then go to the Keyboard Shortcut to assign a shortcut key to it. Known limitation: not work from the desktop

enter image description here

Notes:

  • If the shortcut doesn't work, it might be in conflict with another key binding (and the OS wouldn't warn you), try something else, e.g. if ??T doesn't work, try ??T.
  • Don't spell-correct MacOS, that's not necessary.

How to get first N number of elements from an array

You can filter using index of array.

_x000D_
_x000D_
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
_x000D_
_x000D_

How to run iPhone emulator WITHOUT starting Xcode?

The solutions above didn't work for me in ZSH. I needed to escape the dot in the iPhoneSimulator.platform. This works for me:

alias simulator="open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app"

This could be even more resilient version:

alias simulator="open -a 'iOS Simulator'"

Symbolicating iPhone App Crash Reports

I also put dsym, app bundle, and crash log together in the same directory before running symbolicate crash

Then I use this function defined in my .profile to simplify running symbolicatecrash:

function desym
{
    /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash -A -v $1 | more
}

The arguments added there may help you.

You can check to make sure spotlight "sees" your dysm files by running the command:

mdfind 'com_apple_xcode_dsym_uuids = *'

Look for the dsym you have in your directory.

NOTE: As of the latest Xcode, there is no longer a Developer directory. You can find this utility here:

/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Vers??ions/A/Resources/symbolicatecrash

How does one get started with procedural generation?

(More than 10 years later ...)

Procedural generation only means that code is used to generate the data instead of it being hand made. For example if you want to generate a forest with various trees you are not going to design each tree by hand, thus coding is more efficient to generate the variations. It could be the generation of the tree graphics, size, structure, placement ...

In general there is some kind of interation with a few rules, in addition to that you can add some randomness and logic of your own, combine all of these techniques ... Anything somewhat chaotic but not too chaotic can yield interesting results.

Here are a few notable techniques:

A few games famous for their procedural generation:

Video tutorial about Procedural Landmass Generation.

Conference on procedural content generation for games, has a lot of videos on the topic: everythingprocedural

Have fun.

How to disable input conditionally in vue.js

To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string 'false'.

So, if the value for validated is either a 1 or a 0, then conditionally set the disabled prop based off that value. E.g.:

<input type="text" :disabled="validated == 1">

Here is an example.

_x000D_
_x000D_
var app = new Vue({_x000D_
  el: '#app',_x000D_
_x000D_
  data: {_x000D_
    disabled: 0,_x000D_
  },_x000D_
}); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="app">_x000D_
  <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>_x000D_
  <input type="text" :disabled="disabled == 1">_x000D_
    _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Could not open input file: composer.phar

Try in command line:

curl -sS https://getcomposer.org/installer | php

iOS: how to perform a HTTP POST request?

EDIT: ASIHTTPRequest has been abandoned by the developer. It's still really good IMO, but you should probably look elsewhere now.

I'd highly recommend using the ASIHTTPRequest library if you are handling HTTPS. Even without https it provides a really nice wrapper for stuff like this and whilst it's not hard to do yourself over plain http, I just think the library is nice and a great way to get started.

The HTTPS complications are far from trivial in various scenarios, and if you want to be robust in handling all the variations, you'll find the ASI library a real help.

how to hide a vertical scroll bar when not needed

Add this class in .css class

.scrol  { 
font: bold 14px Arial; 
border:1px solid black; 
width:100% ; 
color:#616D7E; 
height:20px; 
overflow:scroll; 
overflow-y:scroll;
overflow-x:hidden;
}

and use the class in div. like here.

<div> <p class = "scrol" id = "title">-</p></div>

I have attached image , you see the out put of the above code enter image description here

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

Workaround I found:

Press Ctrl + Alt + I or navigate to "Debug Tab" ---> "Windows" ---> "Immediate".

In your code write:

Trace.WriteLine("This is one of the workaround");

Error Running React Native App From Terminal (iOS)

Check out this link (Running react-native run-ios occurs an error?). It appears to be a problem with the location of Command line tools.

In Xcode, select Xcode menu, then Preferences, then Locations tab. Select your Xcode version from the dropdown and exit Xcode.

XCode location tab

What is inf and nan?

I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:

# initial value of the temperature
t = float('nan')          
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')      
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')     
while True:
    # measure temperature, if sensor is broken t is not changed
    t = measure()     
    # find new minimum temperature
    t_min = min(t_min, t) 
    # find new maximum temperature
    t_max = max(t_max, t) 

The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.

Matplotlib legends in subplot

This does what you want and overcomes some of the problems in other answers:

import matplotlib.pyplot as plt

labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]

f,axs = plt.subplots(3, sharex=True, sharey=True)

# ---- loop over axes ----
for i,ax in enumerate(axs):
  axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
  axs[i].legend(loc="upper right")

plt.show()

... produces ... subplots

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

rsync: how can I configure it to create target directory on server?

from rsync manual (man rsync)

--mkpath create the destination's path component

A select query selecting a select statement

Not sure if Access supports it, but in most engines (including SQL Server) this is called a correlated subquery and works fine:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        (
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

This can be made more efficient by indexing Type and Bread and distributing the subqueries over the UNION:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
        )
FROM    [Sandwiches Types]
UNION ALL
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
        )
FROM    [Breads]

Adding items to an object through the .push() method

stuff is an object and push is a method of an array. So you cannot use stuff.push(..).

Lets say you define stuff as an array stuff = []; then you can call push method on it.

This works because the object[key/value] is well formed.

stuff.push( {'name':$(this).attr('checked')} );

Whereas this will not work because the object is not well formed.

stuff.push( {$(this).attr('value'):$(this).attr('checked')} );

This works because we are treating stuff as an associative array and added values to it

stuff[$(this).attr('value')] = $(this).attr('checked');

filemtime "warning stat failed for"

For me the filename involved was appended with a querystring, which this function didn't like.

$path = 'path/to/my/file.js?v=2'

Solution was to chop that off first:

$path = preg_replace('/\?v=[\d]+$/', '', $path);
$fileTime = filemtime($path);

Check if value exists in the array (AngularJS)

U can use something like this....

  function (field,value) {

         var newItemOrder= value;
          // Make sure user hasnt already added this item
        angular.forEach(arr, function(item) {
            if (newItemOrder == item.value) {
                arr.splice(arr.pop(item));

            } });

        submitFields.push({"field":field,"value":value});
    };

How do I get NuGet to install/update all the packages in the packages.config?

In Visual Studio 2017 - When you compile using IDE - It will download all the missing nuget packages and save in the folder "packages".

But on the build machine compilation was done using msbuild.exe. In that case, I downloaded nuget.exe.

During each build process before executing msbuild.exe. It will execute -> nuget.exe restore NAME_OF_SLN_File (if there is only one .SLN file then you can ignore that parameter).

Only local connections are allowed Chrome and Selenium webdriver

Sorry for late post but still for info,I also facing same problem so I Used updated version of chromedriver ie.2.28 for updated chrome browser ie. 55 to 57 which resolved my problem.

Using 'make' on OS X

I found the Developer Tools not as readily available as others. In El Capitan, in terminal I just used gcc -v, it then said gcc wasn't available and asked if I wanted to install the command line Apple Developer Tools. No downloading of Xcode required. Terminal session below:

Pauls-MBP:~ paulhillman$ gcc -v
xcode-select: note: no developer tools were found at '/Applications/Xcode.app', requesting install. Choose an option in the dialog to download the command line developer tools.
Pauls-MBP:~ paulhillman$ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Getting the length of two-dimensional array

int secondDimensionSize = nir[0].length;

Each element of the first dimension is actually another array with the length of the second dimension.

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

public static void main(String[] args) throws ParseException {
    java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    Date date;
    date = (Date)formatter.parse(fecha.toString());
    System.out.println(date);        

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String formatedDate = cal.get(Calendar.DATE) + "/" + 
            (cal.get(Calendar.MONTH) + 1) + 
            "/" +         cal.get(Calendar.YEAR);
    System.out.println("formatedDate : " + formatedDate);
}

Changing background colour of tr element on mouseover

its easy . Just add !important at the end of your css line :

tr:hover {    background: #000 !important; }

How do I overload the [] operator in C#

I believe this is what you are looking for:

Indexers (C# Programming Guide)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get => arr[i];
        set => arr[i] = value;
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

jQuery $(document).ready and UpdatePanels?

I would use one of the following approaches:

  1. Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.

  2. Use the livequery plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.

The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.

The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

Sending commands and strings to Terminal.app with Applescript

Petruza,

Instead of using keystroke use key code.
The following example should work for you.

tell application "System Events"
    tell application process "Terminal"
        set frontmost to true
        key code {2, 0, 17, 14}
        keystroke return
    end tell
end tell

The above example will send the characters {d a t e} to Terminal and then
keystroke return will enter and run the command. Use the above example
with whatever key codes you need and you'll be able to do what you're trying to do.

Remove special symbols and extra spaces and replace with underscore using the replace method

var str = "hello world & hello universe"

In order to replace both Spaces and Symbols in one shot, we can use the below regex code.

str.replaceAll("\\W+","")

Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches

Try it!

Input type "number" won't resize

Seem like the input type number does not support size attribute or it's not compatible along browsers, you can set it through CSS instead:

input[type=number]{
    width: 80px;
} 

Updated Fiddle

What is the garbage collector in Java?

To put it in the most simple terms that even a non-programmer can understand, when a program processes data it creates intermediate data and storage space (variables, arrays, certain object metadata etc.) for that data.

When these objects are accessed across functions or over a certain size, they are allocated from a central heap. Then when they are no long needed, they need to be cleaned up.

There are some very good articles online about how this works, so I'll just cover the very basic definition.

The GC is basically the function that does this cleanup. To do this is clears table entries that aren't referenced by any active objects, effectively deleting the objects, than copies and compacts the memory. It's a little more complicated than this, but you get the idea.

The big problem is some parts this process often requires the entire Java VM to require to be stopped temporarily to take place, as well as this entire process being very processor and memory bandwidth intensive. The various options as of GCs and tuning options for each one are designed to balance these various issues with the whole GC process.

Today's Date in Perl in MM/DD/YYYY format

Perl Code for Unix systems:

# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;

# Remove newline character
$current_date = substr($current_date,0,-1);

print $current_date, "\n";

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

Convert a dataframe to a vector (by rows)

c(df$x, df$y)
# returns: 26 21 20 34 29 28

if the particular order is important then:

M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28 

Or more generally:

m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
  q = c(q, m[i,])
}

# returns 26 34 21 29 20 28

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

Using Java with Nvidia GPUs (CUDA)

There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.

Node.js fs.readdir recursive directory search

Yet another answer, but this time using TypeScript:

_x000D_
_x000D_
/**_x000D_
 * Recursively walk a directory asynchronously and obtain all file names (with full path)._x000D_
 *_x000D_
 * @param dir Folder name you want to recursively process_x000D_
 * @param done Callback function, returns all files with full path._x000D_
 * @param filter Optional filter to specify which files to include, _x000D_
 *   e.g. for json files: (f: string) => /.json$/.test(f)_x000D_
 */_x000D_
const walk = (_x000D_
  dir: string,_x000D_
  done: (err: Error | null, results ? : string[]) => void,_x000D_
  filter ? : (f: string) => boolean_x000D_
) => {_x000D_
  let results: string[] = [];_x000D_
  fs.readdir(dir, (err: Error, list: string[]) => {_x000D_
    if (err) {_x000D_
      return done(err);_x000D_
    }_x000D_
    let pending = list.length;_x000D_
    if (!pending) {_x000D_
      return done(null, results);_x000D_
    }_x000D_
    list.forEach((file: string) => {_x000D_
      file = path.resolve(dir, file);_x000D_
      fs.stat(file, (err2, stat) => {_x000D_
        if (stat && stat.isDirectory()) {_x000D_
          walk(file, (err3, res) => {_x000D_
            if (res) {_x000D_
              results = results.concat(res);_x000D_
            }_x000D_
            if (!--pending) {_x000D_
              done(null, results);_x000D_
            }_x000D_
          }, filter);_x000D_
        } else {_x000D_
          if (typeof filter === 'undefined' || (filter && filter(file))) {_x000D_
            results.push(file);_x000D_
          }_x000D_
          if (!--pending) {_x000D_
            done(null, results);_x000D_
          }_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
};
_x000D_
_x000D_
_x000D_

How do I fix a NoSuchMethodError?

To answer the original question. According to java docs here:

"NoSuchMethodError" Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.

  1. If it happens in the run time, check the class containing the method is in class path.
  2. Check if you have added new version of JAR and the method is compatible.

Passing HTML input value as a JavaScript Function Parameter

Firstly an elements ID should always be unique. If your element IDs aren't unique then you would always get conflicting results. Imagine in your case using two different elements with the same ID.

<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>

<script>
  function add() {
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;

    var sum = parseInt(a) + parseInt(b);
    alert(sum);
  }
</script>

How to round the minute of a datetime object

The shortest way I know

min = tm.minute // 10 * 10

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

export PATH=$PATH:/usr/local/mysql/bin/

should fix the issue for you as the system is not able to find the mysql_config file.

is the + operator less performant than StringBuffer.append()

JavaScript doesn't have a native StringBuffer object, so I'm assuming this is from a library you are using, or a feature of an unusual host environment (i.e. not a browser).

I doubt a library (written in JS) would produce anything faster, although a native StringBuffer object might. The definitive answer can be found with a profiler (if you are running in a browser then Firebug will provide you with a profiler for the JS engine found in Firefox).

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

`React/RCTBridgeModule.h` file not found

For me didn't work any from the above solutions and below it is what worked (I had already checked out Parallelize Build and added React)

1. Open XCode --> To Libraries add `$LibraryWhichDoesNotWork.xcodeproj$`
2. Then for your app in the `Build Phases` add to the `Link Binary with Libraries` the file `lib$LibraryWhichDoesNotWork$.a`

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

if you are handling the config changes in your fragment activity specified in android manifest like this

<activity
    android:name=".courses.posts.EditPostActivity"
    android:configChanges="keyboardHidden|orientation"
    android:screenOrientation="unspecified" />

then the onSaveInstanceState of the fragment will not be invoked and the savedInstanceState object will always be null.

Android WSDL/SOAP service client

Icesoap, which I found yesterday, looks promising. It worked on a basic test, but it lacks more examples.

Multiple aggregate functions in HAVING clause

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

document.all vs. document.getElementById

document.all works in Chrome now (not sure when since), but I've been missing it the last 20 years.... Simply a shorter method name than the clunky document.getElementById. Not sure if it works in Firefox, those guys never had any desire to be compatible with the existing web, always creating new standards instead of embracing the existing web.

How to get script of SQL Server data?

From the SQL Server Management Studio you can right click on your database and select:

Tasks -> Generate Scripts

Then simply proceed through the wizard. Make sure to set 'Script Data' to TRUE when prompted to choose the script options.

SQL Server 2008 R2

alt text

Further reading:

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Index of element in NumPy array

This problem can be solved efficiently using the numpy_indexed library (disclaimer: I am its author); which was created to address problems of this type. npi.indices can be viewed as an n-dimensional generalisation of list.index. It will act on nd-arrays (along a specified axis); and also will look up multiple entries in a vectorized manner as opposed to a single item at a time.

a = np.random.rand(50, 60, 70)
i = np.random.randint(0, len(a), 40)
b = a[i]

import numpy_indexed as npi
assert all(i == npi.indices(a, b))

This solution has better time complexity (n log n at worst) than any of the previously posted answers, and is fully vectorized.

Resource u'tokenizers/punkt/english.pickle' not found

My issue was that I called nltk.download('all') as the root user, but the process that eventually used nltk was another user who didn't have access to /root/nltk_data where the content was downloaded.

So I simply recursively copied everything from the download location to one of the paths where NLTK was looking to find it like this:

cp -R /root/nltk_data/ /home/ubuntu/nltk_data

CSS disable hover effect

Here is way to to unset the hover effect.

.table-hover > tbody > tr.hidden-table:hover > td {
    background-color: unset !important;
    color: unset !important;
}

How to write new line character to a file in Java

This approach always works for me:

String newLine = System.getProperty("line.separator");
String textInNewLine = "this is my first line " + newLine + "this is my second 
line ";

Create a tag in a GitHub repository

Creating Tags

Git uses two main types of tags: lightweight and annotated.

Annotated Tags:

To create an annotated tag in Git you can just run the following simple commands on your terminal.

$ git tag -a v2.1.0 -m "xyz feature is released in this tag."
$ git tag
v1.0.0
v2.0.0
v2.1.0

The -m denotes message for that particular tag. We can write summary of features which is going to tag here.

Lightweight Tags:

The other way to tag commits is lightweight tag. We can do it in the following way:

$ git tag v2.1.0
$ git tag
v1.0.0
v2.0.0
v2.1.0

Push Tag

To push particular tag you can use below command:

git push origin v1.0.3

Or if you want to push all tags then use the below command:

git push --tags

List all tags:

To list all tags, use the following command.

git tag

how to call a onclick function in <a> tag?

Fun! There are a few things to tease out here:

  • $leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
  • Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
  • <a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>.
  • You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
  • Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>.
  • Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
  • Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
  • Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: <a href="http://www.google.com" target="_blank">Google homepage</a>.

Hope those are useful.

'Missing contentDescription attribute on image' in XML

If you don't care at all do this:

    android:contentDescription="@null"

Although I would advise the accepted solutions, this is a hack :D

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

How to set underline text on textview?

You can easily add a View with the height of 1dp aligning start and the end of TextView, right below it. You can also use marginTop with negative value to make the underline closer to TextView. If you use your TextView and the under inside a relative layout, it would be much easier for alignments. here is the example:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<View
  android:id="@+id/viewForgotPasswordUnderline"
  android:layout_width="wrap_content"
  android:layout_height="1dp"
  android:layout_below="@id/txtForgotPassword"
  android:layout_alignStart="@id/txtForgotPassword"
  android:layout_alignEnd="@id/txtForgotPassword"
  android:layout_marginTop="-2dp"
  android:background="@color/lightGray" />

<androidx.appcompat.widget.AppCompatTextView
  android:id="@+id/txtForgotPassword"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerHorizontal="true"
  android:paddingTop="8dp"
  android:text="@string/userLoginForgotPassword"
  android:textColor="@color/lightGray"
  android:textSize="16dp" />
</RelativeLayout>

Exit Shell Script Based on Process Exit Code

After each command, the exit code can be found in the $? variable so you would have something like:

ls -al file.ext
rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi

You need to be careful of piped commands since the $? only gives you the return code of the last element in the pipe so, in the code:

ls -al file.ext | sed 's/^/xx: /"

will not return an error code if the file doesn't exist (since the sed part of the pipeline actually works, returning 0).

The bash shell actually provides an array which can assist in that case, that being PIPESTATUS. This array has one element for each of the pipeline components, that you can access individually like ${PIPESTATUS[0]}:

pax> false | true ; echo ${PIPESTATUS[0]}
1

Note that this is getting you the result of the false command, not the entire pipeline. You can also get the entire list to process as you see fit:

pax> false | true | false; echo ${PIPESTATUS[*]}
1 0 1

If you wanted to get the largest error code from a pipeline, you could use something like:

true | true | false | true | false
rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done
echo $rc

This goes through each of the PIPESTATUS elements in turn, storing it in rc if it was greater than the previous rc value.

How do I select child elements of any depth using XPath?

Also, you can do it with css selectors:

form#myform input[type='submit']

space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element

node.js http 'get' request with query string parameters

I have been struggling with how to add query string parameters to my URL. I couldn't make it work until I realized that I needed to add ? at the end of my URL, otherwise it won't work. This is very important as it will save you hours of debugging, believe me: been there...done that.

Below, is a simple API Endpoint that calls the Open Weather API and passes APPID, lat and lon as query parameters and return weather data as a JSON object. Hope this helps.

//Load the request module
var request = require('request');

//Load the query String module
var querystring = require('querystring');

// Load OpenWeather Credentials
var OpenWeatherAppId = require('../config/third-party').openWeather;

router.post('/getCurrentWeather', function (req, res) {
    var urlOpenWeatherCurrent = 'http://api.openweathermap.org/data/2.5/weather?'
    var queryObject = {
        APPID: OpenWeatherAppId.appId,
        lat: req.body.lat,
        lon: req.body.lon
    }
    console.log(queryObject)
    request({
        url:urlOpenWeatherCurrent,
        qs: queryObject
    }, function (error, response, body) {
        if (error) {
            console.log('error:', error); // Print the error if one occurred

        } else if(response && body) {
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            res.json({'body': body}); // Print JSON response.
        }
    })
})  

Or if you want to use the querystring module, make the following changes

var queryObject = querystring.stringify({
    APPID: OpenWeatherAppId.appId,
    lat: req.body.lat,
    lon: req.body.lon
});

request({
   url:urlOpenWeatherCurrent + queryObject
}, function (error, response, body) {...})

How to find my php-fpm.sock?

I encounter this issue when I first run LEMP on centos7 refer to this post.

I restart nginx to test the phpinfo page, but get this

http://xxx.xxx.xxx.xxx/info.php is not unreachable now.

Then I use tail -f /var/log/nginx/error.log to see more info. I find is the php-fpm.sock file not exist. Then I reboot the system, everything is OK.

Here may not need to reboot the system as Fath's post, just reload nginx and php-fpm.

restart php-fpm

reload nginx config

How to get height of Keyboard?

Swift 3.0 and Swift 4.1

1- Register the notification in the viewWillAppear method:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

2- Method to be called:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        print(keyboardHeight)
    }
}

Comparing two input values in a form validation with AngularJS

No need a function or a directive. Just compare their $modelValue from the view:

ng-show="formName.email.$modelValue !== formName.confirmEmail.$modelValue"

More detailed example:

<span ng-show="(formName.email.$modelValue !== formName.confirmEmail.$modelValue) 
                && formName.confirmEmail.$touched
                && !formName.confirmEmail.$error.required">Email does not match.</span>

Please note that the ConfirmEmail is outside the ViewModel; it's property of the $scope. It doesn't need to be submitted.

Add padding to HTML text input field

<input class="form-control search-query input_style" placeholder="Search…"  name="" title="Search for:" type="text">


.input_style
{
    padding-left:20px;
}

How to have comments in IntelliSense for function in Visual Studio?

read http://msdn.microsoft.com/en-us/library/3260k4x7.aspx Just specifying the comments will not show the help comments in intellisense.

Session 'app': Error Launching activity

I was facing the same problem in android studio 2.1.2 but worked after selecting Build -> Clean Project or alternatively Run -> Clean and Rerun

How to set custom location for local installation of npm package?

For OSX, you can go to your user's $HOME (probably /Users/yourname/) and, if it doesn't already exist, create an .npmrc file (a file that npm uses for user configuration), and create a directory for your npm packages to be installed in (e.g., /Users/yourname/npm). In that .npmrc file, set "prefix" to your new npm directory, which will be where "globally" installed npm packages will be installed; these "global" packages will, obviously, be available only to your user account.

In .npmrc:

prefix=${HOME}/npm

Then run this command from the command line:

npm config ls -l

It should give output on both your own local configuration and the global npm configuration, and you should see your local prefix configuration reflected, probably near the top of the long list of output.

For security, I recommend this approach to configuring your user account's npm behavior over chown-ing your /usr/local folders, which I've seen recommended elsewhere.

How to tell which commit a tag points to in Git?

If you would like to see the details of the tag SOMETAG (tagger, date, etc), the hash of the commit it points to and a bit of info about the commit but without the full diff, try

git show --name-status SOMETAG

Example output:

tag SOMETAG
Tagger: ....
Date:   Thu Jan 26 17:40:53 2017 +0100

 .... tag message .......

commit 9f00ce27c924c7e972e96be7392918b826a3fad9
Author: .............
Date:   Thu Jan 26 17:38:35 2017 +0100

 .... commit message .......

..... list of changed files with their change-status (like git log --name-status) .....

How to enable mod_rewrite for Apache 2.2

In order to use mod_rewrite you can type the following command in the terminal:

sudo a2enmod rewrite

Restart apache2 after

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

or as per new unified System Control Way

sudo systemctl restart apache2

Then, if you'd like, you can use the following .htaccess file.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

The above .htaccess file (if placed in your DocumentRoot) will redirect all traffic to an index.php file in the DocumentRoot unless the file exists.

So, let's say you have the following directory structure and httpdocs is the DocumentRoot

httpdocs/
    .htaccess
    index.php
    images/
        hello.png
    js/
        jquery.js
    css/
        style.css
includes/
    app/
        app.php

Any file that exists in httpdocs will be served to the requester using the .htaccess shown above, however, everything else will be redirected to httpdocs/index.php. Your application files in includes/app will not be accessible.

How to fix the height of a <div> element?

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

Crop image in PHP

You can use imagecrop function in (PHP 5 >= 5.5.0, PHP 7)

Example:

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
    imagedestroy($im2);
}
imagedestroy($im);
?>

How to solve PHP error 'Notice: Array to string conversion in...'

Array to string conversion in latest versions of php 7.x is error, rather than notice, and prevents further code execution.

Using print, echo on array is not an option anymore.

Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.

Use var_dump,print_r, iterate through input value using foreach or for to output input data for names that are declared as input arrays ('name[]')

Most common practice to catch errors is using try/catch blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try block.

  try{  //wrap around possible cause of error or notice
    
    if(!empty($_POST['C'])){
        echo $_POST['C'];
    }

  }catch(Exception $e){

    //handle the error message $e->getMessage();
  }

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

Convert Uri to String and String to Uri

Try this to convert string to uri

String mystring="Hello"
Uri myUri = Uri.parse(mystring);

Uri to String

Uri uri;
String uri_to_string;
uri_to_string= uri.toString();

Execute bash script from URL

Use:

curl -s -L URL_TO_SCRIPT_HERE | bash

For example:

curl -s -L http://bitly/10hA8iC | bash

Better naming in Tuple classes than "Item1", "Item2"

Up to C# 7.0, there was no way to do this short of defining your own type.

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

bootstrap 3 - how do I place the brand in the center of the navbar?

To fix the overlap, you only need modify the .navbar-toggle in your own css styles

something like this, it works for me:

.navbar-toggle{
z-index: 10;
}

Preferred way of loading resources in Java

Well, it partly depends what you want to happen if you're actually in a derived class.

For example, suppose SuperClass is in A.jar and SubClass is in B.jar, and you're executing code in an instance method declared in SuperClass but where this refers to an instance of SubClass. If you use this.getClass().getResource() it will look relative to SubClass, in B.jar. I suspect that's usually not what's required.

Personally I'd probably use Foo.class.getResourceAsStream(name) most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo, that's the most robust way of doing it IMO.

Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.

MySQL: #126 - Incorrect key file for table

Error #126 usually occurs when you got a corrupt table. The best way to solve this is to perform repair. This article might help:

http://dev.mysql.com/doc/refman/5.0/en/repair-table.html

Adding values to Arraylist

Actually, a third is preferred:

ArrayList<Object> array = new ArrayList<Object>();
array.add(Integer.valueOf(3));
array.add("ss");

This avoids autoboxing (Integer.valueOf(3) versus 3) and doesn't create an unnecessary String object.

Eclipse complains when you don't use type arguments with a generic type like ArrayList, because you are using something called a raw type, which is discouraged. If a class is generic (that is, it has type parameters), then you should always use type arguments with that class.

Autoboxing, on the other hand, is a personal preference. Some people are okay with it, and some not. I don't like it, and I turn on the warning for autoboxing/autounboxing.

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

Clearing coverage highlighting in Eclipse

If you would like to remove active session/project/folder then you can follow

Click the "Remove Active Session" button in the toolbar of the "Coverage" view.

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:

encodeURIComponent() 

and in PHP:

urldecode($_POST['field']);

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

After creating the project go to properties --> build path --> configure build path --> order and export tab and check jre and maven dependencies. You will then have the folder.

Tkinter scrollbar for frame

Please see my class that is a scrollable frame. It's vertical scrollbar is binded to <Mousewheel> event as well. So, all you have to do is to create a frame, fill it with widgets the way you like, and then make this frame a child of my ScrolledWindow.scrollwindow. Feel free to ask if something is unclear.

Used a lot from @ Brayan Oakley answers to close to this questions

class ScrolledWindow(tk.Frame):
    """
    1. Master widget gets scrollbars and a canvas. Scrollbars are connected 
    to canvas scrollregion.

    2. self.scrollwindow is created and inserted into canvas

    Usage Guideline:
    Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
    to get them inserted into canvas

    __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
    docstring:
    Parent = master of scrolled window
    canv_w - width of canvas
    canv_h - height of canvas

    """


    def __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs):
        """Parent = master of scrolled window
        canv_w - width of canvas
        canv_h - height of canvas

       """
        super().__init__(parent, *args, **kwargs)

        self.parent = parent

        # creating a scrollbars
        self.xscrlbr = ttk.Scrollbar(self.parent, orient = 'horizontal')
        self.xscrlbr.grid(column = 0, row = 1, sticky = 'ew', columnspan = 2)         
        self.yscrlbr = ttk.Scrollbar(self.parent)
        self.yscrlbr.grid(column = 1, row = 0, sticky = 'ns')         
        # creating a canvas
        self.canv = tk.Canvas(self.parent)
        self.canv.config(relief = 'flat',
                         width = 10,
                         heigh = 10, bd = 2)
        # placing a canvas into frame
        self.canv.grid(column = 0, row = 0, sticky = 'nsew')
        # accociating scrollbar comands to canvas scroling
        self.xscrlbr.config(command = self.canv.xview)
        self.yscrlbr.config(command = self.canv.yview)

        # creating a frame to inserto to canvas
        self.scrollwindow = ttk.Frame(self.parent)

        self.canv.create_window(0, 0, window = self.scrollwindow, anchor = 'nw')

        self.canv.config(xscrollcommand = self.xscrlbr.set,
                         yscrollcommand = self.yscrlbr.set,
                         scrollregion = (0, 0, 100, 100))

        self.yscrlbr.lift(self.scrollwindow)        
        self.xscrlbr.lift(self.scrollwindow)
        self.scrollwindow.bind('<Configure>', self._configure_window)  
        self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
        self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)

        return

    def _bound_to_mousewheel(self, event):
        self.canv.bind_all("<MouseWheel>", self._on_mousewheel)   

    def _unbound_to_mousewheel(self, event):
        self.canv.unbind_all("<MouseWheel>") 

    def _on_mousewheel(self, event):
        self.canv.yview_scroll(int(-1*(event.delta/120)), "units")  

    def _configure_window(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight())
        self.canv.config(scrollregion='0 0 %s %s' % size)
        if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canv.config(width = self.scrollwindow.winfo_reqwidth())
        if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():
            # update the canvas's width to fit the inner frame
            self.canv.config(height = self.scrollwindow.winfo_reqheight())

How do I get a list of files in a directory in C++?

C++11/Linux version:

#include <dirent.h>

if (auto dir = opendir("some_dir/")) {
    while (auto f = readdir(dir)) {
        if (!f->d_name || f->d_name[0] == '.')
            continue; // Skip everything that starts with a dot

        printf("File: %s\n", f->d_name);
    }
    closedir(dir);
}

How to vertically center <div> inside the parent element with CSS?

Centering the child elements in a div. It works for all screen sizes

#parent {
    padding: 5% 0;
}

#child {
    padding: 10% 0;
}

<div id="parent">
    <div id="child">Content here</div>
</div>

for more details, you can visit to this link

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

Assigning out/ref parameters in Moq

I struggled with this for an hour this afternoon and could not find an answer anywhere. After playing around on my own with it I was able to come up with a solution which worked for me.

string firstOutParam = "first out parameter string";
string secondOutParam = 100;
mock.SetupAllProperties();
mock.Setup(m=>m.Method(out firstOutParam, out secondOutParam)).Returns(value);

The key here is mock.SetupAllProperties(); which will stub out all of the properties for you. This may not work in every test case scenario, but if all you care about is getting the return value of YourMethod then this will work fine.

How to get a string between two characters?

By using regular expression :

 String s = "test string (67)";
 Pattern p = Pattern.compile("\\(.*?\\)");
 Matcher m = p.matcher(s);
 if(m.find())
    System.out.println(m.group().subSequence(1, m.group().length()-1)); 

How to hash a password

Based on csharptest.net's great answer, I have written a Class for this:

public static class SecurePasswordHasher
{
    /// <summary>
    /// Size of salt.
    /// </summary>
    private const int SaltSize = 16;

    /// <summary>
    /// Size of hash.
    /// </summary>
    private const int HashSize = 20;

    /// <summary>
    /// Creates a hash from a password.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="iterations">Number of iterations.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password, int iterations)
    {
        // Create salt
        byte[] salt;
        new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);

        // Create hash
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
        var hash = pbkdf2.GetBytes(HashSize);

        // Combine salt and hash
        var hashBytes = new byte[SaltSize + HashSize];
        Array.Copy(salt, 0, hashBytes, 0, SaltSize);
        Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);

        // Convert to base64
        var base64Hash = Convert.ToBase64String(hashBytes);

        // Format hash with extra information
        return string.Format("$MYHASH$V1${0}${1}", iterations, base64Hash);
    }

    /// <summary>
    /// Creates a hash from a password with 10000 iterations
    /// </summary>
    /// <param name="password">The password.</param>
    /// <returns>The hash.</returns>
    public static string Hash(string password)
    {
        return Hash(password, 10000);
    }

    /// <summary>
    /// Checks if hash is supported.
    /// </summary>
    /// <param name="hashString">The hash.</param>
    /// <returns>Is supported?</returns>
    public static bool IsHashSupported(string hashString)
    {
        return hashString.Contains("$MYHASH$V1$");
    }

    /// <summary>
    /// Verifies a password against a hash.
    /// </summary>
    /// <param name="password">The password.</param>
    /// <param name="hashedPassword">The hash.</param>
    /// <returns>Could be verified?</returns>
    public static bool Verify(string password, string hashedPassword)
    {
        // Check hash
        if (!IsHashSupported(hashedPassword))
        {
            throw new NotSupportedException("The hashtype is not supported");
        }

        // Extract iteration and Base64 string
        var splittedHashString = hashedPassword.Replace("$MYHASH$V1$", "").Split('$');
        var iterations = int.Parse(splittedHashString[0]);
        var base64Hash = splittedHashString[1];

        // Get hash bytes
        var hashBytes = Convert.FromBase64String(base64Hash);

        // Get salt
        var salt = new byte[SaltSize];
        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        // Create hash with given salt
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
        byte[] hash = pbkdf2.GetBytes(HashSize);

        // Get result
        for (var i = 0; i < HashSize; i++)
        {
            if (hashBytes[i + SaltSize] != hash[i])
            {
                return false;
            }
        }
        return true;
    }
}

Usage:

// Hash
var hash = SecurePasswordHasher.Hash("mypassword");

// Verify
var result = SecurePasswordHasher.Verify("mypassword", hash);

A sample hash could be this:

$MYHASH$V1$10000$Qhxzi6GNu/Lpy3iUqkeqR/J1hh8y/h5KPDjrv89KzfCVrubn

As you can see, I also have included the iterations in the hash for easy usage and the possibility to upgrade this, if we need to upgrade.


If you are interested in .net core, I also have a .net core version on Code Review.

The model backing the <Database> context has changed since the database was created

Create custom context initializer:

public class MyDbContextInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Migrations.Configuration>
{
    public override void InitializeDatabase(MyDbContext context)
    {
        bool exists = context.Database.Exists();

        base.InitializeDatabase(context);

        if (!exists)
        {         
            MyDbSeed.Seed(context);
        }
    }       
}

Note that Migrations.Configuration is a class generating by migration command line in Package Manager Console. You may need to change internal to public modifier of the Migrations.Configuration class.

And register it from your OmModelCreating:

public partial class MyDbContext : DbContext
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<MyDbContext>(new MyDbContextInitializer());

        //other code for creating model
    }
}

How to uncheck checked radio button

This simple script allows you to uncheck an already checked radio button. Works on all javascript enabled browsers.

_x000D_
_x000D_
var allRadios = document.getElementsByName('re');_x000D_
var booRadio;_x000D_
var x = 0;_x000D_
for(x = 0; x < allRadios.length; x++){_x000D_
  allRadios[x].onclick = function() {_x000D_
    if(booRadio == this){_x000D_
      this.checked = false;_x000D_
      booRadio = null;_x000D_
    } else {_x000D_
      booRadio = this;_x000D_
    }_x000D_
  };_x000D_
}
_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I encountered the same error. JAVA_HOME pointing to the correct version of JDK. All support libraries and build tools updated. Was still facing the same issue.

I am using Android annotations in my project. I added a new View..and there was already an existing view with the same name in the Java file. When I run the project, instead of indicating the view already exists, I was receiving the above error.

Check your java files errors if other solutions does not work.

How to increase MySQL connections(max_connections)?

If you need to increase MySQL Connections without MySQL restart do like below

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 100   |
+-----------------+-------+
1 row in set (0.00 sec)

mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 150   |
+-----------------+-------+
1 row in set (0.00 sec)

These settings will change at MySQL Restart.


For permanent changes add below line in my.cnf and restart MySQL

max_connections = 150

How to pass parameters to ThreadStart method in Thread?

According to your question...

How to pass parameters to Thread.ThreadStart() method in C#?

...and the error you encountered, you would have to correct your code from

Thread thread = new Thread(new ThreadStart(download(filename));

to

Thread thread = new Thread(new ThreadStart(download));
thread.Start(filename);



However, the question is more complex as it seems at first.

The Thread class currently (4.7.2) provides several constructors and a Start method with overloads.

These relevant constructors for this question are:

public Thread(ThreadStart start);

and

public Thread(ParameterizedThreadStart start);

which either take a ThreadStart delegate or a ParameterizedThreadStart delegate.

The corresponding delegates look like this:

public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);

So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart delegate so that some method conform to the specified signature of the delegate can be started by the thread.

A simple example for instanciating the Thread class would be

Thread thread = new Thread(new ParameterizedThreadStart(Work));

or just

Thread thread = new Thread(Work);

The signature of the corresponding method (called Work in this example) looks like this:

private void Work(object data)
{
   ...
}

What is left is to start the thread. This is done by using either

public void Start();

or

public void Start(object parameter);

While Start() would start the thread and pass null as data to the method, Start(...) can be used to pass anything into the Work method of the thread.

There is however one big problem with this approach: Everything passed into the Work method is cast into an object. That means within the Work method it has to be cast to the original type again like in the following example:

public static void Main(string[] args)
{
    Thread thread = new Thread(Work);

    thread.Start("I've got some text");
    Console.ReadLine();
}

private static void Work(object data)
{
    string message = (string)data; // Wow, this is ugly

    Console.WriteLine($"I, the thread write: {message}");
}



Casting is something you typically do not want to do.

What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException which you probably will not notice because it simply terminates the thread.

As a solution you would expect to get a generic ParameterizedThreadStart delegate like ParameterizedThreadStart<T> where T would be the type of data you want to pass into the Work method. Unfortunately something like this does not exist (yet?).

There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:

public class ThreadWithState
{
    private string message;

    public ThreadWithState(string message)
    {
        this.message = message;
    }

    public void Work()
    {
        Console.WriteLine($"I, the thread write: {this.message}");
    }
}

With this approach you would start the thread like this:

ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);

thread.Start();

So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)

IndentationError: unexpected indent error

As the error says you have not correctly indented code, check_exists_sql is not aligned with line above it cursor = db.cursor() .

Also use 4 spaces for indentation.

Read this http://diveintopython.net/getting_to_know_python/indenting_code.html

How to print multiple lines of text with Python

You can use triple quotes (single ' or double "):

a = """
text
text
text
"""

print(a)

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

Evenly distributing n points on a sphere

Take the two largest factors of your N, if N==20 then the two largest factors are {5,4}, or, more generally {a,b}. Calculate

dlat  = 180/(a+1)
dlong = 360/(b+1})

Put your first point at {90-dlat/2,(dlong/2)-180}, your second at {90-dlat/2,(3*dlong/2)-180}, your 3rd at {90-dlat/2,(5*dlong/2)-180}, until you've tripped round the world once, by which time you've got to about {75,150} when you go next to {90-3*dlat/2,(dlong/2)-180}.

Obviously I'm working this in degrees on the surface of the spherical earth, with the usual conventions for translating +/- to N/S or E/W. And obviously this gives you a completely non-random distribution, but it is uniform and the points are not bunched together.

To add some degree of randomness, you could generate 2 normally-distributed (with mean 0 and std dev of {dlat/3, dlong/3} as appropriate) and add them to your uniformly distributed points.

How to Remove Array Element and Then Re-Index Array?

If you use array_merge, this will reindex the keys. The manual states:

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

http://php.net/manual/en/function.array-merge.php

This is where i found the original answer.

http://board.phpbuilder.com/showthread.php?10299961-Reset-index-on-array-after-unset()

Change Circle color of radio button

I made it short way like this (Working on API pre 21 as well as post 21)

Your radio button in xml should look like this

  <RadioButton android:id="@+id/radioid"                    
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"                 
                android:button="@drawable/radiodraw" />

in radiodraw.xml

  <?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">    
      <item android:state_checked="false" >
          <shape  android:shape="oval" >
              <stroke android:width="1dp" android:color="#000"/>
              <size android:width="30dp" android:height="30dp"/>
              <solid android:color="@android:color/transparent"/>
          </shape>
      </item>
      <item android:state_checked="true">
          <layer-list>
              <item>
                  <shape android:shape="oval">
                      <stroke android:width="1dp" android:color="#000"/>
                      <size android:width="30dp" android:height="30dp"/>
                      <solid android:color="@android:color/transparent"/>
                  </shape>
              </item>
              <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
                  <shape android:shape="oval">
                      <solid android:width="1dp" android:color="#000"/>
                      <size android:width="10dp" android:height="10dp"/>
                  </shape>
              </item>
          </layer-list>
      </item>
  </selector>

have to add color transparent for drawing the unchecked status ;else it draw solid black oval.

Using Java 8's Optional with Stream::flatMap

Late to the party, but what about

things.stream()
    .map(this::resolve)
    .filter(Optional::isPresent)
    .findFirst().get();

You can get rid of the last get() if you create a util method to convert optional to stream manually:

things.stream()
    .map(this::resolve)
    .flatMap(Util::optionalToStream)
    .findFirst();

If you return stream right away from your resolve function, you save one more line.

How to remove a Gitlab project?

As per January 13,2018 Do as follow:

  1. Click on Project you want to delete.
  2. Click Setting on right buttom corner.
  3. Locate the Advanced settings section and click on the 'Expand' button
  4. Then Scroll down the page and click on the Remove Project button.
  5. Type your project name. Note : Removed project CANNOT be restored! and click on confirm.
  6. Then project will be deleted and soon 404 page error will be displayed for that project.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

As far as I remember, I used the update-java-alternatives script instead of the update-alternatives. And it did set the JAVA_HOME for me correctly.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

How do I concatenate const/literal strings in C?

Also malloc and realloc are useful if you don't know ahead of time how many strings are being concatenated.

#include <stdio.h>
#include <string.h>

void example(const char *header, const char **words, size_t num_words)
{
    size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */
    char *message = (char*) malloc(message_len);
    strncat(message, header, message_len);

    for(int i = 0; i < num_words; ++i)
    {
       message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */
       message = (char*) realloc(message, message_len);
       strncat(strncat(message, ";", message_len), words[i], message_len);
    }

    puts(message);

    free(message);
}

Get MD5 hash of big files in Python

I think the following code is more pythonic:

from hashlib import md5

def get_md5(fname):
    m = md5()
    with open(fname, 'rb') as fp:
        for chunk in fp:
            m.update(chunk)
    return m.hexdigest()

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

You could always roll your own. I'm getting rid of Crystal Reports in our project because currently, we can't update our old reports without upgrading everyone to XP, because we develop in VS 2008, and the new CR doesn't support Win2K. Also, CR takes about 30 seconds to build and load the report, mine is instantaneous.

I wrote my own XML serializer, and I build custom objects that are populated from List<T>s, DataTables, etc..., serialize the object, load it into an XmlDocument, append an XSLT stylesheet, and write it to a directory containing that XSLT file and any CSS and images. The XSLT file then transforms it to HTML/CSS when the XML file is opened in the user's browser.

I could also probably load it into a WebBrowser control and use one of the free PDF libraries to convert it to PDF and print it. See these threads for more details:

I can't access http://localhost/phpmyadmin/

Make sure you still have phpMyAdmin maybe you deleted it in your htdocs folder?

Get the latest version: http://www.phpmyadmin.net/home_page/downloads.php

Unzip then place the phpMyAdmin (rename the folder if it has version numbers) in your htdocs folder.

Make sure Skype is disabled as it will some times run on the same port as your XAMPP install... I'm not sure why but apache installed via xampp on some windows 7 machines ive seen apache not run if skype is on after 10years of IT work.

So make sure apache is running, mysql is running and hit:

localhost/phpMyAdmin

You should get some kind of install prompt. Step through this you will learn lots along the way. But basically its one config file that needs some settings.

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

Aren't promises just callbacks?

No promises are just wrapper on callbacks

example You can use javascript native promises with node js

my cloud 9 code link : https://ide.c9.io/adx2803/native-promises-in-node

/**
* Created by dixit-lab on 20/6/16.
*/

var express = require('express');
var request = require('request');   //Simplified HTTP request client.


var app = express();

function promisify(url) {
    return new Promise(function (resolve, reject) {
    request.get(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        resolve(body);
    }
    else {
        reject(error);
    }
    })
    });
}

//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
//get the post with post id 100
promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
var obj = JSON.parse(result);
return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
})
.catch(function (e) {
    console.log(e);
})
.then(function (result) {
    res.end(result);
}
)

})


var server = app.listen(8081, function () {

var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)

})


//run webservice on browser : http://localhost:8081/listAlbums

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

Real world example from SQL Server 2008.

Source data:

ID    Start
1     2010-04-30 00:00:01.000
2     2010-04-02 00:00:00.000
3     2010-05-01 00:00:00.000
4     2010-07-31 00:00:00.000

Query:

SELECT
    *
FROM
    tbl
WHERE
    Start BETWEEN '2010-04-01 00:00:00' AND '2010-05-01 00:00:00'

Results:

ID    Start
1     2010-04-30 00:00:01.000
2     2010-04-02 00:00:00.000

alt text

downloading all the files in a directory with cURL

OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.

First of all, you need to create a batch (script) file for the ftp program, containing instructions for it. Name it as you want, and put into it:

curl -u login:pass ftp.myftpsite.com/iiumlabs* -O

open ftp.myftpsite.com
login
pass
mget *
quit

The first line opens a connection to the ftp server at ftp.myftpsite.com. The two following lines specify the login, and the password which ftp will ask for (replace login and pass with just the login and password, without any keywords). Then, you use mget * to get all files. Instead of the *, you can use any wildcard. Finally, you use quit to close the ftp program without interactive prompt.

If you needed to enter some directory first, add a cd command before mget. It should be pretty straightforward.

Finally, write that file and run ftp like this:

ftp -i -s:yourscript

where -i disables interactivity (asking before downloading files), and -s specifies path to the script you created.


Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp which is practically the PuTTy counter-part of the openssh scp command.

The syntax is similar to copy command, and it supports wildcards:

pscp -batch [email protected]:iiumlabs* .

If you authenticate using a key file, you should pass it using -i path-to-key-file. If you use password, -pw pass. It can also reuse sessions saved using PuTTy, using the load -load your-session-name argument.

Can't update: no tracked branch

 git commit -m "first commit"

 git remote add origin <linkyourrepository>

 git push -u origin master

will works!

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

jquery loop on Json data using $.each

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
    alert(data[i].PageName);
});

$.each(data, function(i, item) {
    alert(item.PageName);
});

these two options work well, unless you have something like:

var data.result = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data.result, function(i, item) {
    alert(data.result[i].PageName);
});

EDIT:

try with this and describes what the result

$.get('/Cms/GetPages/123', function(data) {
  alert(data);
});

FOR EDIT 3:

this corrects the problem, but not the idea to use "eval", you should see how are the response in '/Cms/GetPages/123'.

$.get('/Cms/GetPages/123', function(data) {
  $.each(eval(data.replace(/[\r\n]/, "")), function(i, item) {
   alert(item.PageName);
  });
});

How do I style (css) radio buttons and labels?

This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm

<style type="text/css">
.input input {
  float: left;
}
.input label {
  margin: 5px;
}
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

error LNK2005, already defined?

Presence of int k; in the header file causes symbol k to be defined within each translation unit this header is included to while linker expects it to be defined only once (aka One Definition Rule Violation).

While suggestion involving extern are not wrong, extern is a C-ism and should not be used.

Pre C++17 solution that would allow variable in header file to be defined in multiple translation units without causing ODR violation would be conversion to template:

template<typename x_Dummy = void> class
t_HeaderVariableHolder
{
    public: static int s_k;
};

template<typename x_Dummy> int t_HeaderVariableHolder<x_Dummy>::s_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return t_HeaderVariableHolder<>::s_k;
}

With C++17 things become much simpler as it allows inline variables:

inline int g_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return g_k;
}

Getting a random value from a JavaScript array

I've found a way around the top answer's complications, just by concatenating the variable rand to another variable that allows that number to be displayed inside the calling of myArray[];. By deleting the new array created and toying around with it's complications, I've come up with a working solution:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

var myArray = ['January', 'February', 'March', 'April', 'May'];    

var rand = Math.floor(Math.random() * myArray.length);

var concat = myArray[rand];

function random() {
   document.getElementById("demo").innerHTML = (concat);
}
</script>

<button onClick="random();">
Working Random Array generator
</button>

</body>
</html>

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Loop Through Each HTML Table Column and Get the Data using jQuery

When you create your table, put your td with class = "suma"

$(function(){   

   //funcion suma todo

   var sum = 0;
   $('.suma').each(function(x,y){
       sum += parseInt($(this).text());                                   
   })           
   $('#lblTotal').text(sum);   

   // funcion suma por check                                           

    $( "input:checkbox").change(function(){
    if($(this).is(':checked')){     
        $(this).parent().parent().find('td:last').addClass('suma2');
   }else{       
        $(this).parent().parent().find('td:last').removeClass('suma2');
   }    
   suma2Total();                                                           
   })                                                      

   function suma2Total(){
      var sum2 = 0;
      $('.suma2').each(function(x,y){
        sum2 += parseInt($(this).text());       
      })
      $('#lblTotal2').text(sum2);                                              
   }                                                                      
});

Ejemplo completo

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

Print the stack trace of an exception

Apache commons provides utility to convert the stack trace from throwable to string.

Usage:

ExceptionUtils.getStackTrace(e)

For complete documentation refer to https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

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

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

Android - How to get application name? (Not package name)

The source comment added to NonLocalizedLabel directs us now to:

return context.getPackageManager().getApplicationLabelFormatted(context.getApplicationInfo());

Dynamic instantiation from string name of a class in dynamically imported module?

Use getattr to get an attribute from a name in a string. In other words, get the instance as

instance = getattr(modul, class_name)()

Using JQuery to check if no radio button in a group has been checked

var len = $('#your_form_id input:radio:checked').length;
      if (!len) {
        alert("None checked");
      };
      alert("checked: "+ len);

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

Synchronous request in Node.js

I like Raynos' solution as well, but I prefer a different flow control library.

https://github.com/caolan/async

Depending on whether you need the results in each subsequent function, I'd either use series, parallel, or waterfall.

Series when they have to be serially executed, but you don't necessarily need the results in each subsequent function call.

Parallel if they can be executed in parallel, you don't need the results from each during each parallel function, and you need a callback when all have completed.

Waterfall if you want to morph the results in each function and pass to the next

endpoints = 
 [{ host: 'www.example.com', path: '/api_1.php' },
  { host: 'www.example.com', path: '/api_2.php' },
  { host: 'www.example.com', path: '/api_3.php' }];

async.mapSeries(endpoints, http.get, function(results){
    // Array of results
});

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

If you are using windows8:

  1. Click start button
  2. In the search box, type command prompt
  3. From the result, right-click command prompt and click Run as administrator. Then execute the keytool command.

Using jQuery Fancybox or Lightbox to display a contact form

Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.

Kiss Jquery UI goodbye and a lightbox hello. You can get it here.

What is Activity.finish() method doing exactly?

It seems that the only correct answer here so far has been given by romnex: "onDestroy() may not be called at all". Even though in practice, in almost all cases it will, there is no guarantee: The documentation on finish() only promises that the result of the activity is propagated back to the caller, but nothing more. Moreover, the lifecycle documentation clarifies that the activity is killable by the OS as soon as onStop() finishes (or even earlier on older devices), which, even though unlikely and therefore rare to observe in a simple test, might mean that the activity might be killed while or even before onDestroy() is executed.

So if you want to make sure some work is done when you call finish(), you cannot put it in onDestroy(), but will need to do in the same place where you call finish(), right before actually calling it.

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

I had the same problem and my mistake was that I had installed the binary boost_1_55_0-msvc-11.0-32.exe to use with visual c++ 2010 which has the version v100 (project properties->ConfiguratioProperties->General->platformTooset) not v110 as visual c++ 2012. So I dowloaded boost_1_55_0-msvc-10.0-32.exe and now everything is ok so far.

Does MySQL ignore null values on unique constraints?

A simple answer would be : No, it doesn't

Explanation : According to the definition of unique constraints (SQL-92)

A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns

This statement can have two interpretations as :

  • No two rows can have same values i.e. NULL and NULL is not allowed
  • No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed

Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :

MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values

JavaScript: Parsing a string Boolean value?

stringjs has a toBoolean() method:

http://stringjs.com/#methods/toboolean-tobool

S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false

redirect while passing arguments

You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:

from flask import session, url_for

def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))

(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)

Or you could probably just use Flask Message Flashing if you just need to show simple messages.

startsWith() and endsWith() functions in PHP

Many of the previous answers will work just as well. However, this is possibly as short as you can make it and have it do what you desire. You just state that you'd like it to 'return true'. So I've included solutions that returns boolean true/false and the textual true/false.

// boolean true/false
function startsWith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0 ? 1 : 0;
}

function endsWith($haystack, $needle)
{
    return stripos($haystack, $needle) === 0 ? 1 : 0;
}


// textual true/false
function startsWith($haystack, $needle)
{
    return strpos($haystack, $needle) === 0 ? 'true' : 'false';
}

function endsWith($haystack, $needle)
{
    return stripos($haystack, $needle) === 0 ? 'true' : 'false';
}

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

CodeIgniter: Load controller within controller

If you're interested, there's a well-established package out there that you can add to your Codeigniter project that will handle this:

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/

Modular Extensions makes the CodeIgniter PHP framework modular. Modules are groups of independent components, typically model, controller and view, arranged in an application modules sub-directory, that can be dropped into other CodeIgniter applications.

OK, so the big change is that now you'd be using a modular structure - but to me this is desirable. I have used CI for about 3 years now, and can't imagine life without Modular Extensions.

Now, here's the part that deals with directly calling controllers for rendering view partials:

// Using a Module as a view partial from within a view is as easy as writing:
<?php echo modules::run('module/controller/method', $param1, $params2); ?>

That's all there is to it. I typically use this for loading little "widgets" like:

  • Event calendars
  • List of latest news articles
  • Newsletter signup forms
  • Polls

Typically I build a "widget" controller for each module and use it only for this purpose.

Your question was also one of my first questions when I started with Codeigniter. I hope this helps you out, even though it may be a bit more than you were looking for. I've been using MX ever since and haven't looked back.

Make sure to read the docs and check out the multitude of information regarding this package on the Codeigniter forums. Enjoy!

Setting the Vim background colors

In a terminal emulator like konsole or gnome-terminal, you should to set a 256 color setting for vim.

:set  t_Co=256

After that you can to change your background.

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

I was looking for a way to prevent all body scrolling when there's a popup with a scrollable area (a "shopping cart" popdown that has a scrollable view of your cart).

I wrote a far more elegant solution using minimal javascript to just toggle the class "noscroll" on your body when you have a popup or div that you'd like to scroll (and not "overscroll" the whole page body).

while desktop browsers observe overflow:hidden -- iOS seems to ignore that unless you set the position to fixed... which causes the whole page to be a strange width, so you have to set the position and width manually as well. use this css:

.noscroll {
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}

and this jquery:

/* fade in/out cart popup, add/remove .noscroll from body */
$('a.cart').click(function() {
    $('nav > ul.cart').fadeToggle(100, 'linear');
    if ($('nav > ul.cart').is(":visible")) {
        $('body').toggleClass('noscroll');
    } else {
        $('body').removeClass('noscroll');
    }
});

/* close all popup menus when you click the page... */
$('body').click(function () {
    $('nav > ul').fadeOut(100, 'linear');
    $('body').removeClass('noscroll');
});

/* ... but prevent clicks in the popup from closing the popup */
$('nav > ul').click(function(event){
    event.stopPropagation();
});

how to set value of a input hidden field through javascript?

The first thing I will try - determine if your code with alerts is actually rendered. I see some server "if" code in what you posted, so may be condition to render javascript is not satisfied. So, on the page you working on, right-click -> view source. Try to find the js code there. Please tell us if you found the code on the page.

Difference between "as $key => $value" and "as $value" in PHP foreach

Sample Array: Left ones are the keys, right one are my values

$array = array(
        'key-1' => 'value-1', 
        'key-2' => 'value-2',
        'key-3' => 'value-3',
        );

Example A: I want only the values of $array

foreach($array as $value) {    
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'     
}

Example B: I want each value AND key of $array

foreach($array as $key => $value) {                 
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'  

    echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'    

    echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
    $array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1            
}

What’s the best way to check if a file exists in C++? (cross platform)

How about access?

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}

python: [Errno 10054] An existing connection was forcibly closed by the remote host

there are many causes such as

  • The network link between server and client may be temporarily going down.
  • running out of system resources.
  • sending malformed data.

To examine the problem in detail, you can use Wireshark.

or you can just re-request or re-connect again.

In Mongoose, how do I sort by date? (node.js)

ES6 solution with Koa.

  async recent() {
    data = await ReadSchema.find({}, { sort: 'created_at' });
    ctx.body = data;
  }

HTTP test server accepting GET/POST requests

nc one-liner local test server

Setup a local test server in one line under Linux:

nc -kdl localhost 8000

Sample request maker on another shell:

wget http://localhost:8000

then on the first shell you see the request that was made appear:

GET / HTTP/1.1
User-Agent: Wget/1.19.4 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: localhost:8000
Connection: Keep-Alive

nc from the netcat-openbsd package is widely available and pre-installed on Ubuntu.

Tested on Ubuntu 18.04.

How to set recurring schedule for xlsm file using Windows Task Scheduler

Better to use a as you indicated

  1. Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
  2. Use the Task Scheduler to run the vbs
  3. Use the vbs to open the workbook at the scheduled time and then either:
    • use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
    • more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro

See this example of the later approach at Running Excel on Windows Task Scheduler

sample vbs

Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run

ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing

How to install OpenSSL in windows 10?

In case you have Git installed,

you can open the Git Bash (shift pressed + right click in the folder -> Git Bash Here) and use openssl command right in the Bash

How to define a Sql Server connection string to use in VB.NET?

Standard Security:

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

Trusted Connection:

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

will be glad if it helps.

Regards.

How to include CSS file in Symfony 2 and Twig?

In case you are using Silex add the Symfony Asset as a dependency:

composer require symfony/asset

Then you may register Asset Service Provider:

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.version_format' => '%s?version=%s',
    'assets.named_packages' => array(
        'css' => array(
            'version' => 'css2',
            'base_path' => __DIR__.'/../public_html/resources/css'
        ),
        'images' => array(
            'base_urls' => array(
                'https://img.example.com'
            )
        ),
    ),
));

Then in your Twig template file in head section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% block head %}
    <link rel="stylesheet" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>

</body>
</html>

Apply CSS style attribute dynamically in Angular JS

Directly from ngStyle docs:

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.

<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>

So you could do this:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Hope this helps!

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

Comparing Arrays of Objects in JavaScript

EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.

To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.

Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.


EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).

Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:

function objectsAreSame(x, y) {
   var objectsAreSame = true;
   for(var propertyName in x) {
      if(x[propertyName] !== y[propertyName]) {
         objectsAreSame = false;
         break;
      }
   }
   return objectsAreSame;
}

The assumption is that both objects have the same exact list of properties.

Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Running these commands solved my problem (credit to this answer):

import django
django.setup()

However I'm not sure why I need this. Comments would be appreciated.

How can I clear or empty a StringBuilder?

There are basically two alternatives, using setLength(0) to reset the StringBuilder or creating a new one in each iteration. Both can have pros and cons depending on the usage.

If you know the expected capacity of the StringBuilder beforehand, creating a new one each time should be just as fast as setting a new length. It will also help the garbage collector, since each StringBuilder will be relatively short-lived and the gc is optimized for that.

When you don't know the capacity, reusing the same StringBuilder might be faster. Each time you exceed the capacity when appending, a new backing array has to be allocated and the previous content has to be copied. By reusing the same StringBuilder, it will reach the needed capacity after some iterations and there won't be any copying thereafter.

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

Nginx -- static file serving confusion with root & alias

Just a quick addendum to @good_computer's very helpful answer, I wanted to replace to root of the URL with a folder, but only if it matched a subfolder containing static files (which I wanted to retain as part of the path).

For example if file requested is in /app/js or /app/css, look in /app/location/public/[that folder].

I got this to work using a regex.

 location ~ ^/app/((images/|stylesheets/|javascripts/).*)$ {
     alias /home/user/sites/app/public/$1;
     access_log off;
     expires max;
 }

Print Html template in Angular 2 (ng-print in Angular 2)

That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:

<div id="print-section">
  // your html stuff that you want to print
</div>
<button (click)="print()">print</button>

and in your TS file :

print(): void {
    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
          <style>
          //........Customized style.......
          </style>
        </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
}

UPDATE:

You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.

Android Studio - mergeDebugResources exception

I just upgraded to the latest gradle build tool version and it works.

 classpath 'com.android.tools.build:gradle:3.0.1

How can I restart a Java application?

If you realy need to restart your app, you could write a separate app the start it...

This page provides many different examples for different scenarios:

http://www.rgagnon.com/javadetails/java-0014.html

Angular.js programmatically setting a form field to dirty

A helper function to do the job:

function setDirtyForm(form) {
    angular.forEach(form.$error, function(type) {
        angular.forEach(type, function(field) {
            field.$setDirty();
        });
    });
    return form;
}

How can I set the focus (and display the keyboard) on my EditText programmatically

Here is KeyboardHelper Class for hiding and showing keyboard

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by khanhamza on 06-Mar-17.
 */

public class KeyboardHelper {
public static void hideSoftKeyboard(final Context context, final View view) {
    if (context == null) {
        return;
    }
    view.requestFocus();
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}

public static void hideSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}


public static void openSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}

How to install Flask on Windows?

Install pip as described here: How do I install pip on Windows?

Then do

pip install flask

That installation tutorial is a bit misleading, it refers to actually running it in a production environment.

Recursive directory listing in DOS

You can use various options with FINDSTR to remove the lines do not want, like so:

DIR /S | FINDSTR "\-" | FINDSTR /VI DIR

Normal output contains entries like these:

28-Aug-14  05:14 PM    <DIR>          .
28-Aug-14  05:14 PM    <DIR>          ..

You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.

Add Text on Image using PIL

I think ImageFont module available in PIL should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.

# font = ImageFont.truetype(<font-file>, <font-size>)
# font-file should be present in provided path.
font = ImageFont.truetype("sans-serif.ttf", 16)

So your code will look something similar to:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

img = Image.open("sample_in.jpg")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('sample-out.jpg')

You might need to put some extra effort to calculate font size. In case you want to change it based on amount of text user has provided in TextArea.

To add text wrapping (Multiline thing) just take a rough idea of how many characters can come in one line, Then you can probably write a pre-pprocessing function for your Text, Which basically finds the character which will be last in each line and converts white space before this character to new-line.

'uint32_t' identifier not found error

This type is defined in the C header <stdint.h> which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.

In the meantime, you could probably fake up your own version of the header by adding typedefs that map Microsoft's custom integer types to the types expected by C. For example:

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */

Hope this helps!

Using Git with Visual Studio

The Git support done by Microsoft in Visual Studio is just good enough for basic work (commit/fetch/merge and push). My advice is just to avoid it...

I highly prefer GitExtensions (or in less proportion SourceTree). Because seeing the DAG is for me really important to understand how Git works. And you are a lot more aware of what the other contributors to your project have done!

In Visual Studio, you can't quickly see the diff between files or commit, nor (add to the index) and commit only part of modifications. Browse your history is not good either... All that ending in a painful experience!

And, for example, GitExtensions is bundled with interesting plugins: background fetch, GitFlow,... and now, continuous integration!

For the users of Visual Studio 2015, Git is taking shape if you install the GitHub extension. But an external tool is still better ;-)

Pass all variables from one shell script to another?

You have basically two options:

  1. Make the variable an environment variable (export TESTVARIABLE) before executing the 2nd script.
  2. Source the 2nd script, i.e. . test2.sh and it will run in the same shell. This would let you share more complex variables like arrays easily, but also means that the other script could modify variables in the source shell.

UPDATE:

To use export to set an environment variable, you can either use an existing variable:

A=10
# ...
export A

This ought to work in both bash and sh. bash also allows it to be combined like so:

export A=10

This also works in my sh (which happens to be bash, you can use echo $SHELL to check). But I don't believe that that's guaranteed to work in all sh, so best to play it safe and separate them.

Any variable you export in this way will be visible in scripts you execute, for example:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

The fact that these are both shell scripts is also just incidental. Environment variables can be passed to any process you execute, for example if we used python instead it might look like:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.py

b.py:

#!/usr/bin/python

import os

print 'The message is:', os.environ['MESSAGE']

Sourcing:

Instead we could source like this:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

This more or less "imports" the contents of b.sh directly and executes it in the same shell. Notice that we didn't have to export the variable to access it. This implicitly shares all the variables you have, as well as allows the other script to add/delete/modify variables in the shell. Of course, in this model both your scripts should be the same language (sh or bash). To give an example how we could pass messages back and forth:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

echo "[A] The message is: $MESSAGE"

b.sh:

#!/bin/sh

echo "[B] The message is: $MESSAGE"

MESSAGE="goodbye"

Then:

$ ./a.sh
[B] The message is: hello
[A] The message is: goodbye

This works equally well in bash. It also makes it easy to share more complex data which you could not express as an environment variable (at least without some heavy lifting on your part), like arrays or associative arrays.

Difference between binary semaphore and mutex

Mutex work on blocking critical region, But Semaphore work on count.

How to get the onclick calling object?

pass in this in the inline click handler

<a href="123.com" onclick="click123(this);">link</a>

or use event.target in the function (according to the W3C DOM Level 2 Event model)

function click123(event)
{
    var a = event.target;
}

But of course, IE is different, so the vanilla JavaScript way of handling this is

function doSomething(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
}

or less verbose

function doSomething(e) {

    e = e || window.event;
    var targ = e.target || e.srcElement || e;
    if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}

where e is the event object that is passed to the function in browsers other than IE.

If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.

How to style input and submit button with CSS?

HTML

<input type="submit" name="submit" value="Send" id="submit" />

CSS

#submit {
 color: #fff;
 font-size: 0;
 width: 135px;
 height: 60px;
 border: none;
 margin: 0;
 padding: 0;
 background: #0c0 url(image) 0 0 no-repeat; 
}

How to convert XML to JSON in Python?

One possibility would be to use Objectify or ElementTree from the lxml module. An older version ElementTree is also available in the python xml.etree module as well. Either of these will get your xml converted to Python objects which you can then use simplejson to serialize the object to JSON.

While this may seem like a painful intermediate step, it starts making more sense when you're dealing with both XML and normal Python objects.

How to print Two-Dimensional Array like table

Just for the records, Java 8 provides a better alternative.

int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};

System.out.println(Stream.of(table)
    .map(rowParts -> Stream.of(rowParts
    .map(element -> ((Integer)element).toString())
        .collect(Collectors.joining("\t")))
    .collect(Collectors.joining("\n")));

How can I install an older version of a package via NuGet?

Try the following:

Uninstall-Package Newtonsoft.Json -Force

Followed by:

Install-Package Newtonsoft.Json -Version <press tab key for autocomplete>

"Error 404 Not Found" in Magento Admin Login Page

Finally, I found the solution to my problem.

I looked into the Magento system log file (var/log/system.log). There I saw the exact error.

The error is as below:-

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227

Actually, I had this error before. But, error display message like Error: 404 Not Found was new to me.

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.

Open PhpMyAdmin and run the following query in your database:-

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

I have written about this problem and solution over here:-

Magento: Solution to "Error: 404 Not Found" in Admin Login Page

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

Get month and year from date cells Excel

Try this formula (it will return value from A1 as is if it's not a date):

=TEXT(A1,"mm-yyyy")

Or this formula (it's more strict, it will return #VALUE error if A1 is not date):

=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)

How to print without newline or space?

You can try:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

How to import js-modules into TypeScript file?

I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions

{
  "compilerOptions": {
      ...
      "allowJs": true
      ...
  }
}

Running a cron every 30 seconds

write one shell script create .sh file

nano every30second.sh

and write script

#!/bin/bash
For  (( i=1; i <= 2; i++ ))
do
    write Command here
    sleep 30
done

then set cron for this script crontab -e

(* * * * * /home/username/every30second.sh)

this cron call .sh file in every 1 min & in the .sh file command is run 2 times in 1 min

if you want run script for 5 seconds then replace 30 by 5 and change for loop like this: For (( i=1; i <= 12; i++ ))

when you select for any second then calculate 60/your second and write in For loop

How to set the From email address for mailx command?

On debian where bsd-mailx is installed by default, the -r option does not work. However you can use mailx -s subject [email protected] -- -f [email protected] instead. According to man page, you can specify sendmail options after --.

"python" not recognized as a command

in PowerShell enter this:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")

Close PowerShell and then start it again to make sure Python now runs. If it doesn’t, restart may be required.

enter image description here

How to get the row number from a datatable?

ArrayList check = new ArrayList();            

for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
    int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
    check.Add(iValue);

}

Combine two (or more) PDF's

I combined the two above, because I needed to merge 3 pdfbytes and return a byte

internal static byte[] mergePdfs(byte[] pdf1, byte[] pdf2,byte[] pdf3)
        {
            MemoryStream outStream = new MemoryStream();
            using (Document document = new Document())
            using (PdfCopy copy = new PdfCopy(document, outStream))
            {
                document.Open();
                copy.AddDocument(new PdfReader(pdf1));
                copy.AddDocument(new PdfReader(pdf2));
                copy.AddDocument(new PdfReader(pdf3));
            }
            return outStream.ToArray();
        } 

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

How to convert jsonString to JSONObject in Java

you must import org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }

How to move/rename a file using an Ansible task on a remote system

On Windows: - name: Move old folder to backup win_command: "cmd.exe /c move /Y {{ sourcePath }} {{ destinationFolderPath }}"

To rename use rename or ren command instead