Programs & Examples On #Freemind

How to format DateTime in Flutter , How to get current time in flutter?

You can use DateFormat from intl package.

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

How to take MySQL database backup using MySQL Workbench?

Sever > Data Export

enter image description here

Select database, and start export

enter image description here

How to generate a core dump in Linux on a segmentation fault?

To check where the core dumps are generated, run:

sysctl kernel.core_pattern

or:

cat /proc/sys/kernel/core_pattern

where %e is the process name and %t the system time. You can change it in /etc/sysctl.conf and reloading by sysctl -p.

If the core files are not generated (test it by: sleep 10 & and killall -SIGSEGV sleep), check the limits by: ulimit -a.

If your core file size is limited, run:

ulimit -c unlimited

to make it unlimited.

Then test again, if the core dumping is successful, you will see “(core dumped)” after the segmentation fault indication as below:

Segmentation fault: 11 (core dumped)

See also: core dumped - but core file is not in current directory?


Ubuntu

In Ubuntu the core dumps are handled by Apport and can be located in /var/crash/. However, it is disabled by default in stable releases.

For more details, please check: Where do I find the core dump in Ubuntu?.

macOS

For macOS, see: How to generate core dumps in Mac OS X?

Log4j: How to configure simplest possible file logging?

I have one generic log4j.xml file for you:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="default.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/mylogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="another.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/anotherlogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <logger name="com.yourcompany.SomeClass" additivity="false">
        <level value="debug" />
        <appender-ref ref="another.file" />
    </logger>

    <root>
        <priority value="info" />
        <appender-ref ref="default.console" />
        <appender-ref ref="default.file" />
    </root>
</log4j:configuration>

with one console, two file appender and one logger poiting to the second file appender instead of the first.

EDIT

In one of the older projects I have found a simple log4j.properties file:

# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.

# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with 
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless 
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

For the description of all the layout arguments look here: log4j PatternLayout arguments

Upload Image using POST form data in Python-requests

In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

Last Run Date on a Stored Procedure in SQL Server

Oh, be careful now! All that glitters is NOT gold! All of the “stats” dm views and functions have a problem for this type of thing. They only work against what is in cache and the lifetime of what is in cache can be measure in minutes. If you were to use such a thing to determine which SPs are candidates for being dropped, you could be in for a world of hurt when you delete SPs that were used just minutes ago.

The following excerpts are from Books Online for the given dm views…

sys.dm_exec_procedure_stats Returns aggregate performance statistics for cached stored procedures. The view contains one row per stored procedure, and the lifetime of the row is as long as the stored procedure remains cached. When a stored procedure is removed from the cache, the corresponding row is eliminated from this view.

sys.dm_exec_query_stats The view contains one row per query statement within the cached plan, and the lifetime of the rows are tied to the plan itself. When a plan is removed from the cache, the corresponding rows are eliminated from this view.

Copy multiple files with Ansible

If you need more than one location, you need more than one task. One copy task can copy only from one location (including multiple files) to another one on the node.

- copy: src=/file1 dest=/destination/file1
- copy: src=/file2 dest=/destination/file2

# copy each file over that matches the given pattern
- copy: src={{ item }} dest=/destination/
  with_fileglob:
    - /files/*

Error:(1, 0) Plugin with id 'com.android.application' not found

This issue happened when I accidently renamed the line

apply plugin: 'com.android.application'

on file app/build.gradle to some other name. So, I fixed it by changing it to what it was.

React Router Pass Param to Component

Here's typescript version. works on "react-router-dom": "^4.3.1"

export const AppRouter: React.StatelessComponent = () => {
    return (
        <BrowserRouter>
            <Switch>
                <Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
                <Route path="/" exact component={App} />
            </Switch>
        </BrowserRouter>
    );
};

and component

export class ProblemPage extends React.Component<ProblemRouteTokens> {

    public render(): JSX.Element {
        return <div>{this.props.problemId}</div>;
    }
}

where ProblemRouteTokens

export interface ProblemRouteTokens { problemId: string; }

HTTP vs HTTPS performance

There is a way to measure this. The tool from apache called jmeter will measure throughput. If you set up a large sampling of your service with jmeter, in a controlled environment, with and without SSL, you should get an accurate comparison of the relative cost. I would be interested in your results.

Catch multiple exceptions at once?

This is a variant of Matt's answer (I feel that this is a bit cleaner)...use a method:

public void TryCatch(...)
{
    try
    {
       // something
       return;
    }
    catch (FormatException) {}
    catch (OverflowException) {}

    WebId = Guid.Empty;
}

Any other exceptions will be thrown and the code WebId = Guid.Empty; won't be hit. If you don't want other exceptions to crash your program, just add this AFTER the other two catches:

...
catch (Exception)
{
     // something, if anything
     return; // only need this if you follow the example I gave and put it all in a method
}

Is there a C# String.Format() equivalent in JavaScript?

Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:

String.prototype.format = function(placeholders) {
    var s = this;
    for(var propertyName in placeholders) {
        var re = new RegExp('{' + propertyName + '}', 'gm');
        s = s.replace(re, placeholders[propertyName]);
    }    
    return s;
};

usage:

"{greeting} {who}!".format({greeting: "Hello", who: "world"})

_x000D_
_x000D_
String.prototype.format = function(placeholders) {_x000D_
    var s = this;_x000D_
    for(var propertyName in placeholders) {_x000D_
        var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
        s = s.replace(re, placeholders[propertyName]);_x000D_
    }    _x000D_
    return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to prevent column break within an element?

This works for me in 2015 :

_x000D_
_x000D_
li {_x000D_
  -webkit-column-break-inside: avoid;_x000D_
  /* Chrome, Safari, Opera */_x000D_
  page-break-inside: avoid;_x000D_
  /* Firefox */_x000D_
  break-inside: avoid;_x000D_
  /* IE 10+ */_x000D_
}_x000D_
.x {_x000D_
  -moz-column-count: 3;_x000D_
  column-count: 3;_x000D_
  width: 30em;_x000D_
}
_x000D_
<div class='x'>_x000D_
  <ul>_x000D_
    <li>Number one</li>_x000D_
    <li>Number two</li>_x000D_
    <li>Number three</li>_x000D_
    <li>Number four is a bit longer</li>_x000D_
    <li>Number five</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS: borders between table columns only

I used this in a style sheet for three columns separated by vertical borders and it worked fine:

#column-left {
     border-left: 1px solid #dddddd;
}
#column-center {
     /*no border needed/*
}
#column-right {
     border-right: 1px solid #dddddd;
}

The column on the left gets a border on the right, the column on the right gets a border on the left and the the middle column is already taken care of by the left and right.

If your columns are inside a div/wrapper/table/etc... don't forget to add extra space to accomodate the width of the borders.

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Getting index value on razor foreach

Very Simple:

     @{
         int i = 0;
         foreach (var item in Model)
         {
          <tr>
          <td>@(i = i + 1)</td>`
          </tr>
         }
      }`

How to connect to a MS Access file (mdb) using C#?

Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

How to get an absolute file path in Python

Today you can also use the unipath package which was based on path.py: http://sluggo.scrapping.cc/python/unipath/

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

I would recommend using this package as it offers a clean interface to common os.path utilities.

Split string in Lua?

If you are splitting a string in Lua, you should try the string.gmatch() or string.sub() methods. Use the string.sub() method if you know the index you wish to split the string at, or use the string.gmatch() if you will parse the string to find the location to split the string at.

Example using string.gmatch() from Lua 5.1 Reference Manual:

 t = {}
 s = "from=world, to=Lua"
 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
   t[k] = v
 end

How can I calculate an md5 checksum of a directory?

Create a tar archive file on the fly and pipe that to md5sum:

tar c dir | md5sum

This produces a single md5sum that should be unique to your file and sub-directory setup. No files are created on disk.

CSS scale down image to fit in containing div, without specifing original size

if you want both width and the height you can try

 background-size: cover !important;

but this wont distort the image but fill the div.

preferredStatusBarStyle isn't called

So I actually added a category to UINavigationController but used the methods:

-(UIViewController *)childViewControllerForStatusBarStyle;
-(UIViewController *)childViewControllerForStatusBarHidden;

and had those return the current visible UIViewController. That lets the current visible view controller set its own preferred style/visibility.

Here's a complete code snippet for it:

In Swift:

extension UINavigationController {

    public override func childViewControllerForStatusBarHidden() -> UIViewController? {
        return self.topViewController
    }

    public override func childViewControllerForStatusBarStyle() -> UIViewController? {
        return self.topViewController
    }
}

In Objective-C:

@interface UINavigationController (StatusBarStyle)

@end

@implementation UINavigationController (StatusBarStyle)

-(UIViewController *)childViewControllerForStatusBarStyle {
    return self.topViewController;
}

-(UIViewController *)childViewControllerForStatusBarHidden {
    return self.topViewController;
}

@end

And for good measure, here's how it's implemented then in a UIViewController:

In Swift

override public func preferredStatusBarStyle() -> UIStatusBarStyle {
    return .LightContent
}

override func prefersStatusBarHidden() -> Bool {
    return false
}

In Objective-C

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; // your own style
}

- (BOOL)prefersStatusBarHidden {
    return NO; // your own visibility code
}

Finally, make sure your app plist does NOT have the "View controller-based status bar appearance" set to NO. Either delete that line or set it to YES (which I believe is the default now for iOS 7?)

Convert Datetime column from UTC to local time in select statement

This function will convert a UTC time to EST time with DST adjustment. You can change your designed time zone name in this function, or get it from registry:

Create Function fnConvertUTCTimetoESTTime(
    @UTCTime as datetime
)
returns datetime
as
begin
    return convert(datetime, convert(varchar(23), @UTCTime AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time', 121), 121)
end
go

select dbo.fnConvertUTCTimetoESTTime ('2020-3-8 5:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-3-8 6:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-3-8 7:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-3-8 8:00:00.000')

--returns 0:00am, 1:00am, 3:00am, 4:00am

select dbo.fnConvertUTCTimetoESTTime ('2020-11-1 4:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-11-1 5:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-11-1 6:00:00.000')
    , dbo.fnConvertUTCTimetoESTTime ('2020-11-1 7:00:00.000')

--returns 0:00am, 1:00am, 1:00am, 2:00am

Note you can not just return "@UTCTime AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time'" as the result because this result is actually a UTC time in EST format (when you compare this "fake" EST time or include it in an order clause it will be converted back to a UTC time).

Find empty or NaN entry in Pandas Dataframe

Another opltion covering cases where there might be severar spaces is by using the isspace() python function.

df[df.col_name.apply(lambda x:x.isspace() == False)] # will only return cases without empty spaces

adding NaN values:

df[(df.col_name.apply(lambda x:x.isspace() == False) & (~df.col_name.isna())] 

Windows Explorer "Command Prompt Here"

Right-click the title-bar icon of the Explorer window. You'll get the current folder's context menu, where you'll find the "command window here" item.

(Note that to see that menu item, you need to have the corresponding "power toy" installed, or you can create the right registry keys yourself to add that item to folders' context menus.)

Jquery $(this) Child Selector

This is a lot simpler with .slideToggle():

jQuery('.class1 a').click( function() {
  $(this).next('.class2').slideToggle();
});

EDIT: made it .next instead of .siblings

http://www.mredesign.com/demos/jquery-effects-1/

You can also add cookie's to remember where you're at...

http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

How to enable CORS in apache tomcat

CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.

Clearing input in vuejs form

I use this

this.$refs['refFormName'].resetFields();

this work fine for me.

How do I get the last four characters from a string in C#?

string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)

what is right way to do API call in react js?

This discussion has been for a while and @Alexander T.'s answer provided a good guide to follow for newer of React like me. And I'm gonna share some additional know-hows about calling the same API multiple times to refresh the component, I think it's probably a common problem that newbie may face at the beginning.

componentWillReceiveProps(nextProps), from official documentation :

If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

We could conclude that here is the place we handle props from the parent component, have API calls, and update state.

Base on @Alexander T.'s example:

export default class UserList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {person: []};
  }

  componentDidMount() {
   //For our first load. 
   this.UserList(this.props.group); //maybe something like "groupOne"
  }

  componentWillReceiveProps(nextProps) {
    // Assuming parameter comes from url.
    // let group = window.location.toString().split("/")[*indexParameterLocated*];
    // this.UserList(group);

    // Assuming parameter comes from props that from parent component.
    let group = nextProps.group; // Maybe something like "groupTwo" 
    this.UserList(group);
  }

  UserList(group) {
    $.getJSON('https://randomuser.me/api/' + group)
      .then(({ results }) => this.setState({ person: results }));
  }

  render() {
    return (...)
  }
}

Update

componentWillReceiveProps() would be deprecated.

Here are only some methods (all of them in Doc) in the life cycle which I think would be related to deploying API in general case: enter image description here

By referring the diagram above:

  • Deploy API in componentDidMount()

    The proper scenario to have API call here is that the content (from the response of API) of this component will be static, componentDidMount() only fire once while the component is mounting, even new props are passed from parent component or have actions to lead re-rendering.
    The component do check difference to re-render but not re-mount.
    Quote from doc:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.


  • Deploy API in static getDerivedStateFromProps(nextProps, prevState)

We should notice that there are two kinds of component updating, setState() in current component would not lead this method to trigger, but re-rendering or new props from parent component do. We could found out that this method also fires while mounting.

This is a proper place to deploy API if we want to use the current component like a template, and the new parameters for API are props coming from parent component.
We receive a different response from API and return a new state here to change the content of this component.

For example:
We have a dropdown list for different Cars in the parent component, this component needs to show the details of the selected one.


  • Deploy API in componentDidUpdate(prevProps, prevState)

Differ from static getDerivedStateFromProps(), this method is invoked immediately after every rendering except the initial rendering. We could have API calling and render difference in one component.

Extend the previous example:
The component to show Car's details may contain a list of series of this car, if we want to check the 2013 production one, we may click or select or ... the list item to lead a first setState() to reflect this behavior (such as highlighting the list item) in this component, and in the following componentDidUpdate() we send our request with new parameters (state). After getting the response, we setState() again for rendering the different content of the Car details. To prevent the following componentDidUpdate() from causing the infinity loop, we need to compare the state by utilizing prevState at the beginning of this method to decide if we send the API and render the new content.

This method really could be utilized just like static getDerivedStateFromProps() with props, but need to handle the changes of props by utilizing prevProps. And we need to cooperate with componentDidMount() to handle the initial API call.

Quote from doc:

... This is also a good place to do network requests as long as you compare the current props to previous props ...

How to change Navigation Bar color in iOS 7?

In iOS 7 you must use the -barTintColor property:

navController.navigationBar.barTintColor = [UIColor barColor];

How do I create a comma-separated list using a SQL query?

From next version of SQL Server you will be able to do

SELECT r.name,
       STRING_AGG(a.name, ',')
FROM   RESOURCES r
       JOIN APPLICATIONSRESOURCES ar
         ON ar.resource_id = r.id
       JOIN APPLICATIONS a
         ON a.id = ar.app_id
GROUP  BY r.name 

For previous versions of the product there are quite a wide variety of different approaches to this problem. An excellent review of them is in the article: Concatenating Row Values in Transact-SQL.

  • Concatenating values when the number of items are not known

    • Recursive CTE method
    • The blackbox XML methods
    • Using Common Language Runtime
    • Scalar UDF with recursion
    • Table valued UDF with a WHILE loop
    • Dynamic SQL
    • The Cursor approach
      .
  • Non-reliable approaches

    • Scalar UDF with t-SQL update extension
    • Scalar UDF with variable concatenation in SELECT

Setting unique Constraint with fluent API?

@coni2k 's answer is correct however you must add [StringLength] attribute for it to work otherwise you will get an invalid key exception (Example bellow).

[StringLength(65)]
[Index("IX_FirstNameLastName", 1, IsUnique = true)]
public string FirstName { get; set; }

[StringLength(65)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string LastName { get; set; }

How to write a basic swap function in Java

There are no pointers in Java. However, every variable that "contains" an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.

So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).

An alternative is to let the method return an array or pair of ints.

WMI "installed" query different from add/remove programs list?

Not the best, but whether it is practical method:

Use HijackThis.

Run hijack this, click the "Open the Misc Tools section" button

HijackThis Main Menu

click "Open Uninstall Manager"

HijackThis Configuration

click save list (*.txt), yes to the prompts, notepad will open with your add/remove programs list.

HijackThis Add/Remove Programs Manager


Source

How to redirect output of an entire shell script within the script itself?

Addressing the question as updated.

#...part of script without redirection...

{
    #...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...

#...residue of script without redirection...

The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)

You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.

The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.

Force update of an Android app when a new version is available

var activeVersion = "3.9.2";

var currentVersion = "3.9.1";

var activeVersionArr = activeVersion.split("."); var currentVersionArr = currentVersion.split(".");

var compareArray =JSON.stringify(activeVersionArr)==JSON.stringify(currentVersionArr);

if(compareArray){ return false; }

if(!compareArray){ for(var i=0;i<activeVersionArr.length;i++){
if(activeVersionArr[i]!==currentVersionArr[i]){
if(activeVersionArr[i] > currentVersionArr[i]){ return true; }else{ return false; }
} } }

Defined Edges With CSS3 Filter Blur

Here is a solution I came up with keeps 100% of the image and no crop is needed:

Basically I mirror tile the image in 3x3 grid then blur everything and then zoom in at the center image effectively creating like a repeat edges when blurring in after effects, it a bit strange that css3 don't have like a repeat edges built in.

Link to the method / code: How to blur an image using CSS3 without cropping or fading the edges?

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

Can I fade in a background image (CSS: background-image) with jQuery?

i have been searching for ages and finally i put everything together to find my solution. Folks say, you cannot fade-in/-out the background-image- id of the html-background. Thats definitely wrong as you can figure out by implementing the below mentioned demo

CSS:

html, body

height: 100%;   /* ges Hoehe der Seite -> weitere Hoehenangaben werden relativ hierzu ausgewertet */
overflow: hidden;   /*  hide scrollbars */
opacity: 1.0;
-webkit-transition: background 1.5s linear;
-moz-transition: background 1.5s linear;
-o-transition: background 1.5s linear;
-ms-transition: background 1.5s linear;
transition: background 1.5s linear;

Changing body's background-image can now easily be done using JavaScript:

switch (dummy)

case 1:

$(document.body).css({"background-image": "url("+URL_of_pic_One+")"});
waitAWhile();

case 2:
$(document.body).css({"background-image": "url("+URL_of_pic_Two+")"});
waitAWhile();

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Insert value into a string at a certain position?

If you just want to insert a value at a certain position in a string, you can use the String.Insert method:

public string Insert(int startIndex, string value)

Example:

"abc".Insert(2, "XYZ") == "abXYZc"

How do I define global variables in CoffeeScript?

Since coffee script has no var statement it automatically inserts it for all variables in the coffee-script, that way it prevents the compiled JavaScript version from leaking everything into the global namespace.

So since there's no way to make something "leak" into the global namespace from the coffee-script side of things on purpose, you need to define your global variables as properties of the global object.

attach them as properties on window

This means you need to do something like window.foo = 'baz';, which handles the browser case, since there the global object is the window.

Node.js

In Node.js there's no window object, instead there's the exports object that gets passed into the wrapper that wraps the Node.js module (See: https://github.com/ry/node/blob/master/src/node.js#L321 ), so in Node.js what you would need to do is exports.foo = 'baz';.

Now let us take a look at what it states in your quote from the docs:

...targeting both CommonJS and the browser: root = exports ? this

This is obviously coffee-script, so let's take a look into what this actually compiles to:

var root;
root = (typeof exports !== "undefined" && exports !== null) ? exports : this;

First it will check whether exports is defined, since trying to reference a non existent variable in JavaScript would otherwise yield an SyntaxError (except when it's used with typeof)

So if exports exists, which is the case in Node.js (or in a badly written WebSite...) root will point to exports, otherwise to this. So what's this?

(function() {...}).call(this);

Using .call on a function will bind the this inside the function to the first parameter passed, in case of the browser this would now be the window object, in case of Node.js it would be the global context which is also available as the global object.

But since you have the require function in Node.js, there's no need to assign something to the global object in Node.js, instead you assign to the exports object which then gets returned by the require function.

Coffee-Script

After all that explanation, here's what you need to do:

root = exports ? this
root.foo = -> 'Hello World'

This will declare our function foo in the global namespace (whatever that happens to be).
That's all :)

How do I exit a while loop in Java?

You can do multiple condition logical tests within the while() check using the same rules as within any logical check.

while ( obj != null ) {  
    // do stuff  
}

works, as does

while ( value > 5 && value < 10 ) {  
    // do stuff  
}  

are valid. The conditionals are checked on each iteration through the loop. As soon as one doesn't match, the while() loop is exited. You can also use break;

while ( value > 5 ) {  
    if ( value > 10 ) { break; }  
    ...  
}  

How do I change the background color with JavaScript?

_x000D_
_x000D_
function pink(){ document.body.style.background = "pink"; }
function sky(){ document.body.style.background = "skyblue"; }
_x000D_
<p onclick="pink()" style="padding:10px;background:pink">Pink</p>
<p onclick="sky()" style="padding:10px;background:skyblue">Sky</p>
_x000D_
_x000D_
_x000D_

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');

depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.

Array slices in C#

For byte arrays System.Buffer.BlockCopy will give you the very best performance.

How to calculate sum of a formula field in crystal Reports?

You can try like this:

Sum({Tablename.Columnname})

It will work without creating a summarize field in formulae.

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

PDF Blob - Pop up window not showing content

If you set { responseType: 'blob' }, no need to create Blob on your own. You can simply create url based with response content:

$http({
    url: "...",
    method: "POST",
    responseType: "blob"
}).then(function(response) {
    var fileURL = URL.createObjectURL(response.data);
    window.open(fileURL);
});

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Get The Current Domain Name With Javascript (Not the path, etc.)

Since this question asks for domain name, not host name, a correct answer should be

window.location.hostname.split('.').slice(-2).join('.')

This works for host names like www.example.com too.

What's the fastest way to loop through an array in JavaScript?

var arr = []; // The array
var i = 0;
while (i < arr.length) {
    // Do something with arr[i]
    i++;
}

i++ is faster than ++i, --i and i--

Also, you can save the last line doing arr[i++] the last time you need to access i (but this can be hard to debug).

You can test it here (with other loop tests): http://jsperf.com/for-vs-whilepop/5

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Is there a math nCr function in python?

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)
120

How to write a Unit Test?

Other answers have shown you how to use JUnit to set up test classes. JUnit is not the only Java test framework. Concentrating on the technical details of using a framework however detracts from the most important concepts that should be guiding your actions, so I will talk about those.

  • Testing (of all kinds of all kinds of things) compares the actual behaviour of something (The System Under Test, SUT) with its expected behaviour.

  • Automated testing can be done using a computer program. Because that comparison is being done by an inflexible and unintelligent computer program, the expected behaviour must be precisely and unambiguously known.

  • What a program or part of a program (a class or method) is expected to do is its specification. Testing software therefore requires that you have a specification for the SUT. This might be an explicit description, or an implicit specification in your head of what is expected.

  • Automated unit testing therefore requires a precise and unambiguous specification of the class or method you are testing.

  • But you needed that specification when you set out to write that code. So part of what testing is about actually begins before you write even one line of the SUT. The testing technique of Test Driven Development (TDD) takes that idea to an extreme, and has you create the unit testing code before you write the code to be tested.

  • Unit testing frameworks test your SUT using assertions. An assertion is a logical expression (an expression with a boolean result type; a predicate) that must be true if the SUT is behaving correctly. The specification must therefore be expressed (or re-expressed) as assertions.

  • A useful technique for expressing a specification as assertions is programming by contract. These specifications are in terms of postconditions. A postcondition is an assertion about the publicly visible state of the SUT after return from a method or a constructor. Some methods have postconditions that are invariants, which are predicates that are true before and after execution of the method. A class can also be said to have invariants, which are postconditions of every constructor and method of the class, and hence should always be true. Postconditions (And invariants) are expressed only in terms of publicity visible state: public and protected fields, the values returned by returned by public and protected methods (such as getters), and the publicly visible state of objects passed (by reference) to methods.


Many beginners post questions here asking how they can test some code, presenting the code but without stating the specification for that code. As this discussion shows, it is impossible for anyone to give a good answer to such a question, because at best potential answereres must guess the specification, and might do so incorrectly. The asker of the question evidently does not understand the importance of a specification, and is thus a novice who needs to understand the fundamentals I've described here before trying to write some test code.

text-align: right; not working for <label>

You can make a text align to the right inside of any element, including labels.

Html:

<label>Text</label>

Css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

ProgressDialog spinning circle

I was using View.INVISIBLE and View.VISIBLE and the ProgressBar would slowly flash instead of constantly being visible, switched to View.GONE and View.VISIBLE and it works perfectly

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Using putty to scp from windows to Linux

You can use PSCP to copy files from Windows to Linux.

  1. Download PSCP from putty.org
  2. Open cmd in the directory with pscp.exe file
  3. Type command pscp source_file user@host:destination_file

Reference

How to create a .NET DateTime from ISO 8601 format

using System.Globalization;

DateTime d;
DateTime.TryParseExact(
    "2010-08-20T15:00:00",
    "s",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal, out d);

Backup/Restore a dockerized PostgreSQL database

Another approach (based on docker-postgresql-workflow)

Local running database (not in docker, but same approach would work) to export:

pg_dump -F c -h localhost mydb -U postgres export.dmp

Container database to import:

docker run -d -v /local/path/to/postgres:/var/lib/postgresql/data postgres #ex runs container as `CONTAINERNAME` #find via `docker ps`
docker run -it --link CONTAINERNAME:postgres  --volume $PWD/:/tmp/  postgres  bash -c 'exec pg_restore -h postgres -U postgres -d mydb -F c /tmp/sonar.dmp'

Convert ASCII number to ASCII Character in C

If i is the int, then

char c = i;

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

What's the Android ADB shell "dumpsys" tool and what are its benefits?

According to official Android information about dumpsys:

The dumpsys tool runs on the device and provides information about the status of system services.

To get a list of available services use

adb shell dumpsys -l

How to check whether java is installed on the computer

You can do it programmatically by reading the java system properties

@Test
public void javaVersion() {
    System.out.println(System.getProperty("java.version"));
    System.out.println(System.getProperty("java.runtime.version"));
    System.out.println(System.getProperty("java.home"));
    System.out.println(System.getProperty("java.vendor"));
    System.out.println(System.getProperty("java.vendor.url"));
    System.out.println(System.getProperty("java.class.path"));
}

This will output somthing like

1.7.0_17
1.7.0_17-b02
C:\workspaces\Oracle\jdk1.7\jre
Oracle Corporation
http://java.oracle.com/
C:\workspaces\Misc\Miscellaneous\bin; ...

The first line shows the version number. You can parse it an see whether it fits your minimun required java version or not. You can find a description for the naming convention here and more infos here.

How to open local files in Swagger-UI

Yet another option is to run swagger using docker, you can use this docker image:

https://hub.docker.com/r/madscientist/swagger-ui/

I made this ghetto little BASH script to kill running containers and rebuild, so basically each time you make a change to your spec and want to see it, just run the script. Make sure to put the name of your application in the APP_NAME variable

#!/bin/bash

# Replace my_app with your application name
APP_NAME="my_app"

# Clean up old containers and images
old_containers=$(docker ps -a | grep $APP_NAME | awk '{ print $1 }')
old_images=$(docker images | grep $APP_NAME | awk '{ print $3 }')

if [[ $old_containers ]];
    then
        echo "Stopping old containers: $old_containers"
        docker stop $old_containers
        echo "Removing old containers: $old_containers"
        docker rm $old_containers
fi

if [[ $old_images ]];
    then
        echo "Removing stale images"
        docker rmi $old_images
fi

# Create new image
echo "Creating new image for $APP_NAME"
docker build . -t $APP_NAME

# Run container
echo "Running container with image $APP_NAME"
docker run -d --name $APP_NAME -p 8888:8888 $APP_NAME
echo "Check out your swaggery goodness here:

http://localhost:8888/swagger-ui/?url=http://localhost:8888/swagger-ui/swagger.yaml"

How to play video with AVPlayerViewController (AVKit) in Swift

a bug(?!) in iOS10/Swift3/Xcode 8?

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
    let playerItem = AVPlayerItem(url: url)
    let player = AVPlayer(playerItem: playerItem)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame=CGRect(x: 10, y: 10, width: 300, height: 300)
    self.view.layer.addSublayer(playerLayer)
}

does not work (empty rect...)

this works:

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){

            let player = AVPlayer(url: url)
            let controller=AVPlayerViewController()
            controller.player=player
            controller.view.frame = self.view.frame
            self.view.addSubview(controller.view)
            self.addChildViewController(controller)
            player.play()
        }

Same URL...

XPath to select multiple tags

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e

Pandas: rolling mean by time interval

What about something like this:

First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the fill_method option to fill in missing date values. Next, pass the resampled frame into pd.rolling_mean with a window of 3 and min_periods=1 :

pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)

            favorable  unfavorable     other
enddate
2012-10-25   0.495000     0.485000  0.025000
2012-10-26   0.527500     0.442500  0.032500
2012-10-27   0.521667     0.451667  0.028333
2012-10-28   0.515833     0.450000  0.035833
2012-10-29   0.488333     0.476667  0.038333
2012-10-30   0.495000     0.470000  0.038333
2012-10-31   0.512500     0.460000  0.029167
2012-11-01   0.516667     0.456667  0.026667
2012-11-02   0.503333     0.463333  0.033333
2012-11-03   0.490000     0.463333  0.046667
2012-11-04   0.494000     0.456000  0.043333
2012-11-05   0.500667     0.452667  0.036667
2012-11-06   0.507333     0.456000  0.023333
2012-11-07   0.510000     0.443333  0.013333

UPDATE: As Ben points out in the comments, with pandas 0.18.0 the syntax has changed. With the new syntax this would be:

df.resample("1d").sum().fillna(0).rolling(window=3, min_periods=1).mean()

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

javascript regex for special characters

function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text 
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}

This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.

Using wire or reg with input or output in Verilog

seeing it in digital circuit domain

  1. A Wire will create a wire output which can only be assigned any input by using assign statement as assign statement creates a port/pin connection and wire can be joined to the port/pin
  2. A reg will create a register(D FLIP FLOP ) which gets or recieve inputs on basis of sensitivity list either it can be clock (rising or falling ) or combinational edge .

so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment

VBA: Selecting range by variables

If you just want to select the used range, use

ActiveSheet.UsedRange.Select

If you want to select from A1 to the end of the used range, you can use the SpecialCells method like this

With ActiveSheet
    .Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select
End With

Sometimes Excel gets confused on what is the last cell. It's never a smaller range than the actual used range, but it can be bigger if some cells were deleted. To avoid that, you can use Find and the asterisk wildcard to find the real last cell.

Dim rLastCell As Range

With Sheet1
    Set rLastCell = .Cells.Find("*", .Cells(1, 1), xlValues, xlPart, , xlPrevious)

    .Range(.Cells(1, 1), rLastCell).Select
End With

Finally, make sure you're only selecting if you really need to. Most of what you need to do in Excel VBA you can do directly to the Range rather than selecting it first. Instead of

.Range(.Cells(1, 1), rLastCell).Select
Selection.Font.Bold = True

You can

.Range(.Cells(1,1), rLastCells).Font.Bold = True

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

I just run into problem downloading google-services.json from Firebase console. Turns out I had to log out from all other google accounts than the one I was using for Firebase.

How to check a Long for null in java

You can check Long object for null value with longValue == null , you can use longValue == 0L for long (primitive), because default value of long is 0L, but it's result will be true if longValue is zero too

Log4j output not displayed in Eclipse console

I had the same error.

I am using Jboss 7.1 AS. In the configuration file - standalone.xml edit the following tag. (stop your server and edit)

     <root-logger>
            <level name="ALL"/>
            <handlers>
                <handler name="CONSOLE"/>
                <handler name="FILE"/>
            </handlers>
    </root-logger>

The ALL has the lowest possible rank and is intended to turn on all logging.

How to call a parent class function from derived class function?

struct a{
 int x;

 struct son{
  a* _parent;
  void test(){
   _parent->x=1; //success
  }
 }_son;

 }_a;

int main(){
 _a._son._parent=&_a;
 _a._son.test();
}

Reference example.

bootstrap popover not showing on top of all elements

In my case I had to use the popover template option and add my own css class to the template html:

        $("[data-toggle='popover']").popover(
          {
            container: 'body',
            template: '<div class="popover top-modal" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
       });

Css:

.top-modal {
  z-index: 99999;
}

Joining pairs of elements of a list

Well I would do it this way as I am no good with Regs..

CODE

t = '1. eat, food\n\
7am\n\
2. brush, teeth\n\
8am\n\
3. crack, eggs\n\
1pm'.splitlines()

print [i+j for i,j in zip(t[::2],t[1::2])]

output:

['1. eat, food   7am', '2. brush, teeth   8am', '3. crack, eggs   1pm']  

Hope this helps :)

How do I get elapsed time in milliseconds in Ruby?

ezpz's answer is almost perfect, but I hope I can add a little more.

Geo asked about time in milliseconds; this sounds like an integer quantity, and I wouldn't take the detour through floating-point land. Thus my approach would be:

irb(main):038:0> t8 = Time.now
=> Sun Nov 01 15:18:04 +0100 2009
irb(main):039:0> t9 = Time.now
=> Sun Nov 01 15:18:18 +0100 2009
irb(main):040:0> dif = t9 - t8
=> 13.940166
irb(main):041:0> (1000 * dif).to_i
=> 13940

Multiplying by an integer 1000 preserves the fractional number perfectly and may be a little faster too.

If you're dealing with dates and times, you may need to use the DateTime class. This works similarly but the conversion factor is 24 * 3600 * 1000 = 86400000 .

I've found DateTime's strptime and strftime functions invaluable in parsing and formatting date/time strings (e.g. to/from logs). What comes in handy to know is:

  • The formatting characters for these functions (%H, %M, %S, ...) are almost the same as for the C functions found on any Unix/Linux system; and

  • There are a few more: In particular, %L does milliseconds!

How to get string objects instead of Unicode from JSON?

I've adapted the code from the answer of Mark Amery, particularly in order to get rid of isinstance for the pros of duck-typing.

The encoding is done manually and ensure_ascii is disabled. The python docs for json.dump says that

If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences

Disclaimer: in the doctest I used the Hungarian language. Some notable Hungarian-related character encodings are: cp852 the IBM/OEM encoding used eg. in DOS (sometimes referred as ascii, incorrectly I think, it is dependent on the codepage setting), cp1250 used eg. in Windows (sometimes referred as ansi, dependent on the locale settings), and iso-8859-2, sometimes used on http servers. The test text Tüskéshátú kígyóbuvölo is attributed to Koltai László (native personal name form) and is from wikipedia.

# coding: utf-8
"""
This file should be encoded correctly with utf-8.
"""
import json

def encode_items(input, encoding='utf-8'):
    u"""original from: https://stackoverflow.com/a/13101776/611007
    adapted by SO/u/611007 (20150623)
    >>> 
    >>> ## run this with `python -m doctest <this file>.py` from command line
    >>> 
    >>> txt = u"Tüskéshátú kígyóbuvölo"
    >>> txt2 = u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"
    >>> txt3 = u"uúuutifu"
    >>> txt4 = b'u\\xfauutifu'
    >>> # txt4 shouldn't be 'u\\xc3\\xbauutifu', string content needs double backslash for doctest:
    >>> assert u'\\u0102' not in b'u\\xfauutifu'.decode('cp1250')
    >>> txt4u = txt4.decode('cp1250')
    >>> assert txt4u == u'u\\xfauutifu', repr(txt4u)
    >>> txt5 = b"u\\xc3\\xbauutifu"
    >>> txt5u = txt5.decode('utf-8')
    >>> txt6 = u"u\\u251c\\u2551uutifu"
    >>> there_and_back_again = lambda t: encode_items(t, encoding='utf-8').decode('utf-8')
    >>> assert txt == there_and_back_again(txt)
    >>> assert txt == there_and_back_again(txt2)
    >>> assert txt3 == there_and_back_again(txt3)
    >>> assert txt3.encode('cp852') == there_and_back_again(txt4u).encode('cp852')
    >>> assert txt3 == txt4u,(txt3,txt4u)
    >>> assert txt3 == there_and_back_again(txt5)
    >>> assert txt3 == there_and_back_again(txt5u)
    >>> assert txt3 == there_and_back_again(txt4u)
    >>> assert txt3.encode('cp1250') == encode_items(txt4, encoding='utf-8')
    >>> assert txt3.encode('utf-8') == encode_items(txt5, encoding='utf-8')
    >>> assert txt2.encode('utf-8') == encode_items(txt, encoding='utf-8')
    >>> assert {'a':txt2.encode('utf-8')} == encode_items({'a':txt}, encoding='utf-8')
    >>> assert [txt2.encode('utf-8')] == encode_items([txt], encoding='utf-8')
    >>> assert [[txt2.encode('utf-8')]] == encode_items([[txt]], encoding='utf-8')
    >>> assert [{'a':txt2.encode('utf-8')}] == encode_items([{'a':txt}], encoding='utf-8')
    >>> assert {'b':{'a':txt2.encode('utf-8')}} == encode_items({'b':{'a':txt}}, encoding='utf-8')
    """
    try:
        input.iteritems
        return {encode_items(k): encode_items(v) for (k,v) in input.iteritems()}
    except AttributeError:
        if isinstance(input, unicode):
            return input.encode(encoding)
        elif isinstance(input, str):
            return input
        try:
            iter(input)
            return [encode_items(e) for e in input]
        except TypeError:
            return input

def alt_dumps(obj, **kwargs):
    """
    >>> alt_dumps({'a': u"T\\u00fcsk\\u00e9sh\\u00e1t\\u00fa k\\u00edgy\\u00f3b\\u0171v\\u00f6l\\u0151"})
    '{"a": "T\\xc3\\xbcsk\\xc3\\xa9sh\\xc3\\xa1t\\xc3\\xba k\\xc3\\xadgy\\xc3\\xb3b\\xc5\\xb1v\\xc3\\xb6l\\xc5\\x91"}'
    """
    if 'ensure_ascii' in kwargs:
        del kwargs['ensure_ascii']
    return json.dumps(encode_items(obj), ensure_ascii=False, **kwargs)

I'd also like to highlight the answer of Jarret Hardie which references the JSON spec, quoting:

A string is a collection of zero or more Unicode characters

In my use-case I had files with json. They are utf-8 encoded files. ensure_ascii results in properly escaped but not very readable json files, that is why I've adapted Mark Amery's answer to fit my needs.

The doctest is not particularly thoughtful but I share the code in the hope that it will useful for someone.

"Expected an indented block" error?

You have to indent the docstring after the function definition there (line 3, 4):

def print_lol(the_list):
"""this doesn't works"""
    print 'Ain't happening'

Indented:

def print_lol(the_list):
    """this works!"""
    print 'Aaaand it's happening'

Or you can use # to comment instead:

def print_lol(the_list):
#this works, too!
    print 'Hohoho'

Also, you can see PEP 257 about docstrings.

Hope this helps!

YouTube: How to present embed video with sound muted

This is easy. Just add mute=1 to the src parameter of iframe.

Example:

<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?controls=0&mute=1&showinfo=0&rel=0&autoplay=1&loop=1&playlist=uNRGWVJ10gQ" frameborder="0" allowfullscreen></iframe>

What does ENABLE_BITCODE do in xcode 7?

Update

Apple has clarified that slicing occurs independent of enabling bitcode. I've observed this in practice as well where a non-bitcode enabled app will only be downloaded as the architecture appropriate for the target device.

Original

More specifically:

Bitcode. Archive your app for submission to the App Store in an intermediate representation, which is compiled into 64- or 32-bit executables for the target devices when delivered.

Slicing. Artwork incorporated into the Asset Catalog and tagged for a platform allows the App Store to deliver only what is needed for installation.

The way I read this, if you support bitcode, downloaders of your app will only get the compiled architecture needed for their own device.

How to force ViewPager to re-instantiate its items

public class DayFlipper extends ViewPager {

private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return DayFlipper.DAY_HISTORY;
    }

    @Override
    public void startUpdate(View container) {
    }

    @Override
    public Object instantiateItem(View container, int position) {
        Log.d(TAG, "instantiateItem(): " + position);

        Date d = DateHelper.getBot();
        for (int i = 0; i < position; i++) {
            d = DateHelper.getTomorrow(d);
        }

        d = DateHelper.normalize(d);

        CubbiesView cv = new CubbiesView(mContext);
        cv.setLifeDate(d);
        ((ViewPager) container).addView(cv, 0);
        // add map
        cv.setCubbieMap(mMap);
        cv.initEntries(d);
adpter = FlipperAdapter.this;
        return cv;
    }

    @Override
    public void destroyItem(View container, int position, Object object) {
        ((ViewPager) container).removeView((CubbiesView) object);
    }

    @Override
    public void finishUpdate(View container) {

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((CubbiesView) object);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }

}

    ...

    public void refresh() {
    adapter().notifyDataSetChanged();
}
}

try this.

Run Stored Procedure in SQL Developer?

With simple parameter types (i.e. not refcursors etc.) you can do something like this:

SET serveroutput on;
DECLARE
    InParam1 number;
    InParam2 number;
    OutParam1 varchar2(100);
    OutParam2 varchar2(100);
    OutParam3 varchar2(100);
    OutParam4 number;
BEGIN
    /* Assign values to IN parameters */
    InParam1 := 33;
    InParam2 := 89;

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(InParam1, InParam2,
        OutParam1, OutParam2, OutParam3, OutParam4);

    /* Display OUT parameters */
    dbms_output.put_line('OutParam1: ' || OutParam1);
    dbms_output.put_line('OutParam2: ' || OutParam2);
    dbms_output.put_line('OutParam3: ' || OutParam3);
    dbms_output.put_line('OutParam4: ' || OutParam4);
END;
/


Edited to use the OP's spec, and with an alternative approach to utilise :var bind variables:

var InParam1 number;
var InParam2 number;
var OutParam1 varchar2(100);
var OutParam2 varchar2(100);
var OutParam3 varchar2(100);
var OutParam4 number;

BEGIN
    /* Assign values to IN parameters */
    :InParam1 := 33;
    :InParam2 := 89;

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(:InParam1, :InParam2,
        :OutParam1, :OutParam2, :OutParam3, :OutParam4);
END;
/

-- Display OUT parameters
print :OutParam1;
print :OutParam2;
print :OutParam3;
print :OutParam4;

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

How to update/refresh specific item in RecyclerView

The problem is RecyclerView.Adatper does not provide any methods that return the index of element

public abstract static class Adapter<VH extends ViewHolder> {
  /**
   * returns index of the given element in adapter, return -1 if not exist
   */
  public int indexOf(Object elem);
}

My workaround is to create a map instance for (element, position)s

public class FriendAdapter extends RecyclerView.Adapter<MyViewHolder> {
  private Map<Friend, Integer> posMap ;
  private List<Friend> friends;

  public FriendAdapter(List<Friend> friends ) {
    this.friends = new ArrayList<>(friends);
    this.posMap = new HashMap<>();
    for(int i = 0; i < this.friends.size(); i++) {
      posMap.put(this.friends.get(i), i);
    }
  }

  public int indexOf(Friend friend) {
    Integer position = this.posMap.get(elem);
    return position == null ? -1 : position;
  }
  // skip other methods in class Adapter
}
  • the element type(here class Friend) should implements hashCode() and equals() because it is key in hashmap.

when an element changed,

  void someMethod() {
    Friend friend = ...;
    friend.setPhoneNumber('xxxxx');

    int position = friendAdapter.indexOf(friend);
    friendAdapter.notifyItemChanged(position);

  }

It is good to define an helper method

public class FriendAdapter extends extends RecyclerView.Adapter<MyViewHolder> {

  public void friendUpdated(Friend friend) {
    int position = this.indexOf(friend);
    this.notifyItemChanged(position);
  }
}

Map instance(Map<Friend, Integer> posMap) is not necessarily required. If map is not used, looping throughout list can find the position of an element.

How to delete all files older than 3 days when "Argument list too long"?

Can also use:

find . -mindepth 1 -mtime +3 -delete

To not delete target directory

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

I want to vertical-align text in select box

So far this is working fine for me:

line-height: 100%;

How to change the current URL in javascript?

What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.

Why not do something like this:

var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';

nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

Pass Array Parameter in SqlCommand

try it like this

StringBuilder sb = new StringBuilder(); 
foreach (ListItem item in ddlAge.Items) 
{ 
     if (item.Selected) 
     { 
          string sqlCommand = "SELECT * from TableA WHERE Age IN (@Age)"; 
          SqlConnection sqlCon = new SqlConnection(connectString); 
          SqlCommand sqlComm = new SqlCommand(); 
          sqlComm.Connection = sqlCon; 
          sqlComm.CommandType = System.Data.CommandType.Text; 
          sqlComm.CommandText = sqlCommand; 
          sqlComm.CommandTimeout = 300; 
          sqlComm.Parameters.Add("@Age", SqlDbType.NVarChar);
          sb.Append(item.Text + ","); 
          sqlComm.Parameters["@Age"].Value = sb.ToString().TrimEnd(',');
     } 
} 

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

Convert SVG to PNG in Python

Here is what I did using cairosvg:

from cairosvg import svg2png

svg_code = """
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12" y2="16"/>
    </svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

And it works like a charm!

See more: cairosvg document

TypeError: $(...).on is not a function

The usual cause of this is that you're also using Prototype, MooTools, or some other library that makes use of the $ symbol, and you're including that library after jQuery, and so that library is "winning" (taking $ for itself). So the return value of $ isn't a jQuery instance, and so it doesn't have jQuery methods on it (like on).

You can use jQuery with those other libraries, but if you do, you have to use the jQuery symbol rather than its alias $, e.g.:

jQuery('body').on(...);

And it's usually best if you add this immediately after your script tag including jQuery, before the one including the other library:

<script>jQuery.noConflict();</script>

...although it's not required if you load the other library after jQuery (it is if you load the other library first).

Using multiple full-function DOM manipulation libraries on the same page isn't ideal, though, just in terms of page weight. So if you can stick with just Prototype/MooTools/whatever or just jQuery, that's usually better.

How to style HTML5 range input to have different color before and after slider?

Yes, it is possible. Though I wouldn't recommend it because input range is not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.

Also, you'll need a bit of JavaScript too. I took the liberty of using jQuery library for this, for simplicity purposes.

Here you go: http://jsfiddle.net/JnrvG/1/.

What is Mocking?

There are plenty of answers on SO and good posts on the web about mocking. One place that you might want to start looking is the post by Martin Fowler Mocks Aren't Stubs where he discusses a lot of the ideas of mocking.

In one paragraph - Mocking is one particlar technique to allow testing of a unit of code with out being reliant upon dependencies. In general, what differentiates mocking from other methods is that mock objects used to replace code dependencies will allow expectations to be set - a mock object will know how it is meant to be called by your code and how to respond.


Your original question mentioned TypeMock, so I've left my answer to that below:

TypeMock is the name of a commercial mocking framework.

It offers all the features of the free mocking frameworks like RhinoMocks and Moq, plus some more powerful options.

Whether or not you need TypeMock is highly debatable - you can do most mocking you would ever want with free mocking libraries, and many argue that the abilities offered by TypeMock will often lead you away from well encapsulated design.

As another answer stated 'TypeMocking' is not actually a defined concept, but could be taken to mean the type of mocking that TypeMock offers, using the CLR profiler to intercept .Net calls at runtime, giving much greater ability to fake objects (not requirements such as needing interfaces or virtual methods).

Dump Mongo Collection into JSON format

Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

mongoexport -d <database> -c <collection_name>

Also helpful:

-o: write the output to file, otherwise standard output is used (docs)

--jsonArray: generates a valid json document, instead of one json object per line (docs)

--pretty: outputs formatted json (docs)

npm install doesn't create node_modules directory

npm init

It is all you need. It will create the package.json file on the fly for you.

How to git-svn clone the last n revisions from a Subversion repository?

I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).

# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase

And a good way to find out where a branch started is to do a svn log it and find the first one on the branch (the last one listed when doing):

svn log --stop-on-copy svn://some/repo/branch/some-branch

So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.

How to handle windows file upload using Selenium WebDriver?

Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.

Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");

Please use below link for further assistance: http://www.guru99.com/use-autoit-selenium.html

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Spring Boot - Loading Initial Data

you can register and event listener to achieve that like below:

@EventListener
public void seed(ContextRefreshedEvent event) {
    userRepository.save(new User("lala", "lala", "lala"));
}

When the ContextRefreshEvent is fired, we get access to all autowired beans in the application — including models and repositories.

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

Use jquery click to handle anchor onClick()

You can't have multiple time the same ID for elements. It is meant to be unique.

Use a class and make your IDs unique:

<div class="solTitle" id="solTitle1"> <a href = "#"  id = "solution0" onClick = "openSolution();">Solution0 </a></div>

And use the class selector:

$('.solTitle a').click(function(evt) {

    evt.preventDefault();
    alert('here in');
    var divId = 'summary' + this.id.substring(0, this.id.length-1);

    document.getElementById(divId).className = ''; 

});

Convert MySql DateTime stamp into JavaScript's Date format

var a=dateString.split(" ");
var b=a[0].split("-");
var c=a[1].split(":");
var date = new Date(b[0],(b[1]-1),b[2],b[0],c[1],c[2]);

Is it possible to disable scrolling on a ViewPager

Here is my light weight variant of slayton's answer:

public class DeactivatableViewPager extends ViewPager {
    public DeactivatableViewPager(Context context) {
        super(context);
    }

    public DeactivatableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return !isEnabled() || super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return isEnabled() && super.onInterceptTouchEvent(event);
    }
}

With my code you can disable the paging with setEnable().

MySQL - Using COUNT(*) in the WHERE clause

try

SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC

How to dynamically insert a <script> tag via jQuery after page load?

There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

Say your AJAX response is something like

<b>some html</b>
<script>alert("and some javscript")

Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

In times like these, I feel like I've successfully divided by zero.

Error - Unable to access the IIS metabase

Run command:

c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ga %username%
c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

How do I reverse a commit in git?

This article has an excellent explanation as to how to go about various scenarios (where a commit has been done as well as the push OR just a commit, before the push):

http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html

From the article, the easiest command I saw to revert a previous commit by its commit id, was:

git revert dd61ab32

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

How do I format date in jQuery datetimepicker?

You can use the format option, as described in the documentation

$("#timePicker").datetimepicker({
  format: 'Y-m-d H:i'
});

How to add line breaks to an HTML textarea?

You need to use \n for linebreaks inside textarea

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

How to store printStackTrace into a string

call:  getStackTraceAsString(sqlEx)

public String getStackTraceAsString(Exception exc)  
{  
String stackTrace = "*** Error in getStackTraceAsString()";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
    stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
    } 
catch( UnsupportedEncodingException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
ps.close();
try {
    baos.close();
    } 
catch( IOException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
return stackTrace;
}

SQL server stored procedure return a table

I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.

/****** Check if my table type and/or proc exists and drop them ******/
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
DROP PROCEDURE returnTableTypeData
GO
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
DROP TYPE myTableType
GO

/****** Create the type that I'll pass into the proc and return from it ******/
CREATE TYPE [dbo].[myTableType] AS TABLE(
    [someInt] [int] NULL,
    [somenVarChar] [nvarchar](100) NULL
)
GO

CREATE PROC returnTableTypeData
    @someInputInt INT,
    @myInputTable myTableType READONLY --Must be readonly because
AS
BEGIN

    --Return the subset of data consistent with the type
    SELECT
        *
    FROM
        @myInputTable
    WHERE
        someInt < @someInputInt

END
GO


DECLARE @myInputTableOrig myTableType
DECLARE @myUpdatedTable myTableType

INSERT INTO @myInputTableOrig ( someInt,somenVarChar )
VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )

INSERT INTO @myUpdatedTable EXEC returnTableTypeData @someInputInt=1, @myInputTable=@myInputTableOrig

SELECT * FROM @myUpdatedTable


DROP PROCEDURE returnTableTypeData
GO
DROP TYPE myTableType
GO

How do I increment a DOS variable in a FOR /F loop?

What about this simple code, works for me and on Windows 7

set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin

:end

How to add leading zeros?

data$anim <- sapply(0, paste0,data$anim)

How to output (to a log) a multi-level array in a format that is human-readable?

I just wonder why nobody uses or recommends the way I prefer to debug an array:

error_log(json_encode($array));

Next to my browser I tail my server log in the console eg.

tail -f /var/log/apache2/error.log

How do I format a string using a dictionary in python-3.x?

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

How to run a shell script in OS X by double-clicking?

No need to use third-party apps such as Platypus.

Just create an Apple Script with Script Editor and use the command do shell script "shell commands" for direct command calls or executable shell script files, keep the editable script file safe somewhere then export it to create an Application script. the app script is launch-able by double click or selection in bar folder.

Declare multiple module.exports in Node.js

Adding here for someone to help:

this code block will help adding multiple plugins into cypress index.js Plugins -> cypress-ntlm-auth and cypress env file selection

const ntlmAuth = require('cypress-ntlm-auth/dist/plugin');
const fs = require('fs-extra');
const path = require('path');

const getConfigurationByFile = async (config) => {
  const file = config.env.configFile || 'dev';
  const pathToConfigFile = path.resolve(
    '../Cypress/cypress/',
    'config',
    `${file}.json`
  );
  console.log('pathToConfigFile' + pathToConfigFile);
  return fs.readJson(pathToConfigFile);
};

module.exports = async (on, config) => {
  config = await getConfigurationByFile(config);
  await ntlmAuth.initNtlmAuth(config);
  return config;
};

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

How to set an image as a background for Frame in Swing GUI of java?

if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator

Set height 100% on absolute div

Complete stretching (horizontal/vertical)

The accepted answer is great. Just want to point out some things for others coming here. Margins are not necessary in these cases. If you want a centered layout with a specific "Margin", you can add them to the right and left, like so:

.stretched {
  position: absolute;
  right: 50px;  top: 0;  bottom: 0; left: 50px;
  margin: auto;
}

This is extremely useful.

Centering div (vertical/horizontally)

As a bonus, absolute centering which can be used to get extremely simple centering:

.centered {
  height: 100px;  width: 100px;  
  right: 0;  top: 0;  bottom: 0; left: 0;
  margin: auto;
  position: absolute;
}

Difference between Subquery and Correlated Subquery

I think below explanation will help to you.. differentiation between those: Correlated subquery is an inner query referenced by main query (outer query) such that inner query considered as being excuted repeatedly.

non-correlated subquery is a sub query that is an independent of the outer query and it can executed on it's own without relying on main outer query.

plain subquery is not dependent on the outer query,

Convert a positive number to negative in C#

Just something that I want to share.

public decimal NumberReevaluate(decimal number, bool isPositive)
{
    var tempNumber = System.Math.Abs(number);
    return isPositive ? tempNumber : -tempNumber;
}

Bootstrap: Collapse other sections when one is expanded

If you stick to HTML structure and proper selectors according to the Bootstrap convention, you should be alright.

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
        </h4>
      </div>
      <div id="collapse1" class="panel-collapse collapse in">
        <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
        </h4>
      </div>
      <div id="collapse2" class="panel-collapse collapse">
        <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
        </h4>
      </div>
      <div id="collapse3" class="panel-collapse collapse">
        <div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
      </div>
    </div>
</div> 

DEMO

What is the difference between #import and #include in Objective-C?

I agree with Jason.

I got caught out doing this:

#import <sys/time.h>  // to use gettimeofday() function
#import <time.h>      // to use time() function

For GNU gcc, it kept complaining that time() function was not defined.

So then I changed #import to #include and all went ok.

Reason:

You #import <sys/time.h>:
    <sys/time.h> includes only a part of <time.h> by using #defines

You #import <time.h>:
    No go. Even though only part of <time.h> was already included, as
    far as #import is concerned, that file is now already completely included.

Bottom line:

C/C++ headers traditionally includes parts of other include files.
So for C/C++ headers, use #include.
For objc/objc++ headers, use #import.

Using Java to find substring of a bigger string using Regular Expression

You should be able to use non-greedy quantifiers, specifically *?. You're going to probably want the following:

Pattern MY_PATTERN = Pattern.compile("\\[(.*?)\\]");

This will give you a pattern that will match your string and put the text within the square brackets in the first group. Have a look at the Pattern API Documentation for more information.

To extract the string, you could use something like the following:

Matcher m = MY_PATTERN.matcher("FOO[BAR]");
while (m.find()) {
    String s = m.group(1);
    // s now contains "BAR"
}

What is the difference between Cygwin and MinGW?

Cygwin is an attempt to create a complete UNIX/POSIX environment on Windows. To do this it uses various DLLs. While these DLLs are covered by GPLv3+, their license contains an exception that does not force a derived work to be covered by the GPLv3+. MinGW is a C/C++ compiler suite which allows you to create Windows executables without dependency on such DLLs - you only need the normal MSVC runtimes, which are part of any normal Microsoft Windows installation.

You can also get a small UNIX/POSIX like environment, compiled with MinGW called MSYS. It doesn't have anywhere near all the features of Cygwin, but is ideal for programmers wanting to use MinGW.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

Xcode 10 Error: Multiple commands produce

Select your scheme (top left corner) -> Edit Scheme... -> Build (left tab) -> uncheck "Find Implicit Dependencies"

enter image description here

And after that you may need to fix any dependencies that were not imported explicitly by your targets.

How to get city name from latitude and longitude coordinates in Google Maps?

I got new way to resolve this issue. Here I have used google http service to get total information of location based on longitude and latitude. You just need to pass latitude and longitude in url and your api key (ex : latlng=21.1497409, 79.08747970000002 & key=YOUR API KEY). Here is my get service in ExampleServiceClass

 getService(url) {

    return this.http.get(url).map((data: any) => data.json())

}

this you can put anywhere you want and just call below service from component where you need location data

this._exampleService.getService("https://maps.googleapis.com/maps/api/geocode/json?latlng=21.1497409, 79.08747970000002&key=YOUR API KEY").subscribe(getplaceData => {
            var placeDataDest: any;
            placeDataDest = getplaceData;
            console.log("i got place id yeee " + placeDataDest['results'][0]['place_id']);
            console.log("i got place details yeee " + placeDataDest['results']);
        });

similarly find city name....hope you will find this useful

sequelize findAll sort order in nodejs

I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)

So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2) but is just an arbitrary sequence (2,4,11,2,9,0).

When I hit this issue with findAll, here was my solution (sub in your returned results for numbers):

var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});

Which returns [2, 23, 20, 53, 9]. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne, but then you're doing n queries when 1 will do.

button image as form input submit button?

This might be helpful

<form action="myform.cgi"> 
 <input type="file" name="fileupload" value="fileupload" id="fileupload">
 <label for="fileupload"> Select a file to upload</label> 
 <br>
 <input type="image" src="/wp-content/uploads/sendform.png" alt="Submit" width="100"> </form>

Read more: https://html.com/input-type-image/#ixzz5KD3sJxSp

How to execute a Windows command on a remote PC?

If you are in a domain environment, you can also use:

winrs -r:PCNAME cmd

This will open a remote command shell.

Using success/error/finally/catch with Promises in AngularJS

In Angular $http case, the success() and error() function will have response object been unwrapped, so the callback signature would be like $http(...).success(function(data, status, headers, config))

for then(), you probably will deal with the raw response object. such as posted in AngularJS $http API document

$http({
        url: $scope.url,
        method: $scope.method,
        cache: $templateCache
    })
    .success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    })
    .error(function(data, status) {
        $scope.data = data || 'Request failed';
        $scope.status = status;
    });

The last .catch(...) will not need unless there is new error throw out in previous promise chain.

Set up Python 3 build system with Sublime Text 3

If you are using PyQt, then for normal work, you should add "shell":"true" value, this looks like:

{
  "cmd": ["c:/Python32/python.exe", "-u", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.python",
  "shell":"true"
}

Difference between "module.exports" and "exports" in the CommonJs Module System

Also, one things that may help to understand:

math.js

this.add = function (a, b) {
    return a + b;
};

client.js

var math = require('./math');
console.log(math.add(2,2); // 4;

Great, in this case:

console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true

Thus, by default, "this" is actually equals to module.exports.

However, if you change your implementation to:

math.js

var add = function (a, b) {
    return a + b;
};

module.exports = {
    add: add
};

In this case, it will work fine, however, "this" is not equal to module.exports anymore, because a new object was created.

console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false

And now, what will be returned by the require is what was defined inside the module.exports, not this or exports, anymore.

Another way to do it would be:

math.js

module.exports.add = function (a, b) {
    return a + b;
};

Or:

math.js

exports.add = function (a, b) {
    return a + b;
};

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Take a look at http://start.spring.io/ it basically gives you a kick starter with either maven or gradle build.

Note: This is a Spring Boot based archetype.

Iterate over model instance field names and values in template

_x000D_
_x000D_
<table border='1'>_x000D_
 <tr>_x000D_
  {% for mfild in fields%}_x000D_
   <td>{{mfild}}</td>_x000D_
  {% endfor%}_x000D_
 </tr>_x000D_
    {%for v in records%}_x000D_
        <tr>_x000D_
         <td>{{v.id}}</td>_x000D_
         <td>{{v.title}}</td>_x000D_
         <td class="">{{v.desc}}</td>_x000D_
_x000D_
        </tr>_x000D_
_x000D_
    {% endfor%}_x000D_
 </table>_x000D_
 _x000D_
 _x000D_
enter code here
_x000D_
_x000D_
_x000D_

Sending HTML email using Python

You might try using my mailer module.

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)

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

If you need only the application name, not the package name, then just write this code.

 String app_name = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:

Get-ChildItem C:\\\\\Windows

Do I need to pass the full path of a file in another directory to open()?

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

Dynamically change color to lighter or darker by percentage CSS (Javascript)

You could use RGBa ('a' being alpha transparency), but it's not widely supported yet. It will be, though, so you could use it now and add a fallback:

a:link { 
    color: rgb(0,0,255); 
    }
a:link.lighter {
    color: rgb(128,128,255); /* This gets applied only in browsers that don't apply the rgba line */
    }
a:link.lighter { /* This comes after the previous line, so has priority in supporting browsers */
    color: rgba(0,0,255,0.5); /* last value is transparency */
    }

Importing CommonCrypto in a Swift framework

I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.

Based on the above, the steps are:

1) Create a CommonCrypto directory inside the project directory. Within, create a module.map file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    link "CommonCrypto"
    export *
}

2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto directory to Import Paths (SWIFT_INCLUDE_PATHS).

Build Settings

3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:

import CommonCrypto

extension String {

    func hnk_MD5String() -> String {
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
        {
            let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
            let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
            CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
            let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
            let MD5 = NSMutableString()
            for c in resultEnumerator {
                MD5.appendFormat("%02x", c)
            }
            return MD5
        }
        return ""
    }
}

Limitations

Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths) in the project that uses the framework.

The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.

Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.

UPDATE / EDIT

I kept getting the following build error:

ld: library not found for -lCommonCrypto for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Unless I removed the line link "CommonCrypto" from the module.map file I created. Once I removed this line it built ok.

How to properly upgrade node using nvm

You can more simply run one of the following commands:

Latest version:
nvm install node --reinstall-packages-from=node
Stable (LTS) version:
nvm install lts/* --reinstall-packages-from=node

This will install the appropriate version and reinstall all packages from the currently used node version. This saves you from manually handling the specific versions.

Edit - added command for installing LTS version according to @m4js7er comment.

How to convert from Hex to ASCII in JavaScript?

I found a useful function present in web3 library.

var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)

Are HTTP headers case-sensitive?

the Headers word are not case sensitive, but on the right like the Content-Type, is good practice to write it this way, because its case sensitve. like my example below

headers = headers.set('Content-Type'

Time stamp in the C programming language

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

If might be better off to use gettimeofday() as mentioned here

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

In any case you are confused with your password.You can use hit and trial. It will ask you for password.If it right then it will show you the list.

  • List item

$ keytool -list -v -keystore filename

When do we need curly braces around shell variables?

You are also able to do some text manipulation inside the braces:

STRING="./folder/subfolder/file.txt"
echo ${STRING} ${STRING%/*/*}

Result:

./folder/subfolder/file.txt ./folder

or

STRING="This is a string"
echo ${STRING// /_}

Result:

This_is_a_string

You are right in "regular variables" are not needed... But it is more helpful for the debugging and to read a script.

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

Delete all the queues from RabbitMQ?

This commands deletes all your queues

python rabbitmqadmin.py \
  -H YOURHOST -u guest -p guest -f bash list queues | \
xargs -n1 | \
xargs -I{} \
  python rabbitmqadmin.py -H YOURHOST -u guest -p guest delete queue name={}

This script is super simple because it uses -f bash, which outputs the queues as a list.

Then we use xargs -n1 to split that up into multiple variables

Then we use xargs -I{} that will run the command following, and replace {} in the command.

Class JavaLaunchHelper is implemented in two places

Since “this message is harmless”(see the @CrazyCoder's answer), a simple and safe workaround is that you can fold this buzzing message in console by IntelliJ IDEA settings:

  1. ?Preferences?- ?Editor?-?General?-?Console?- ?Fold console lines that contain?
    Of course, you can use ?Find Action...?(cmd+shift+A on mac) and type Fold console lines that contain so as to navigate more effectively.
  2. add Class JavaLaunchHelper is implemented in both

image

On my computer, It turns out: (LGTM :b )

image

And you can unfold the message to check it again:

image

PS:

As of October 2017, this issue is now resolved in jdk1.9/jdk1.8.152/jdk1.7.161
for more info, see the @muttonUp's answer)

How to loop and render elements in React-native?

render() {
  return (
    <View style={...}>
       {initialArr.map((prop, key) => {
         return (
           <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>
         );
      })}
     </View>
  )
}

should do the trick

Java getting the Enum name given the Enum Value

Try, the following code..

    @Override
    public String toString() {
    return this.name();
    }

Why can't Visual Studio find my DLL?

To add to Oleg's answer:

I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath) to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!

* I actually don't know if the $(ExecutablePath) macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.

How to add an image to an svg container using D3.js

I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv enter image description here

d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);            
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));    
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`

Populate a datagridview with sql query results

you have to add the property Tables to the DataGridView Data Source

 dataGridView1.DataSource = table.Tables[0];

Check if a string contains an element from a list (of strings)

If speed is critical, you might want to look for the Aho-Corasick algorithm for sets of patterns.

It's a trie with failure links, that is, complexity is O(n+m+k), where n is the length of the input text, m the cumulative length of the patterns and k the number of matches. You just have to modify the algorithm to terminate after the first match is found.

HTML5 phone number validation with pattern

How about

<input type="text" pattern="[789][0-9]{9}">

Reading Email using Pop3 in C#

call me old fashion but why use a 3rd party library for a simple protocol. I've implemented POP3 readers in web based ASP.NET application with System.Net.Sockets.TCPClient and System.Net.Security.SslStream for the encryption and authentication. As far as protocols go, once you open up communication with the POP3 server, there are only a handful of commands that you have to deal with. It is a very easy protocol to work with.

Bootstrap 3 Glyphicons are not working

If the other solutions aren't working, you may want to try importing Glyphicons from an external source, rather than relying on Bootstrap to do everything for you. To do this:

You can either do this in HTML:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

Or CSS:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css")

Credit to edsiofi from this thread: Bootstrap 3 Glyphicons CDN

Removing time from a Date object?

If you are using Java 8+, use java.time.LocalDate type instead.

LocalDate now = LocalDate.now();
System.out.println(now.toString());

The output:

2019-05-30

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

SQL Server : How to test if a string has only digit characters

There is a system function called ISNUMERIC for SQL 2008 and up. An example:

SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;

I did a couple of quick tests and also looked further into the docs:

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

Which means it is fairly predictable for example

-9879210433 would pass but 987921-0433 does not. $9879210433 would pass but 9879210$433 does not.

So using this information you can weed out based on the list of valid currency symbols and + & - characters.

How to insert a SQLite record with a datetime set to 'now' in Android application?

There are a couple options you can use:

  1. You could try using the string "(DATETIME('now'))" instead.
  2. Insert the datetime yourself, ie with System.currentTimeMillis()
  3. When creating the SQLite table, specify a default value for the created_date column as the current date time.
  4. Use SQLiteDatabase.execSQL to insert directly.

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

How to check if a String contains any of some strings

// Nice method's name, @Dan Tao

public static bool ContainsAny(this string value, params string[] params)
{
    return params.Any(p => value.Compare(p) > 0);
    // or
    return params.Any(p => value.Contains(p));
}

Any for any, All for every

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

I was also facing the same error in my node application today.

enter image description here

Below was my node API.

app.get('azureTable', (req, res) => {
  const tableSvc = azure.createTableService(config.azureTableAccountName, config.azureTableAccountKey);
  const query = new azure.TableQuery().top(1).where('PartitionKey eq ?', config.azureTablePartitionKey);
  tableSvc.queryEntities(config.azureTableName, query, null, (error, result, response) => {
    if (error) { return; }
    res.send(result);
    console.log(result)
  });
});

The fix was very simple, I was missing a slash "/" before my API. So after changing the path from 'azureTable' to '/azureTable', the issue was resolved.

Linking to an external URL in Javadoc?

Taken from the javadoc spec

@see <a href="URL#value">label</a> : Adds a link as defined by URL#value. The URL#value is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<) as the first character.

For example : @see <a href="http://www.google.com">Google</a>

Modifying CSS class property values on the fly with JavaScript / jQuery

This may be late to the discussion, but I needed something like what is being talked about here, but didn't find anything that really did what I wanted, and did it easily. What I needed was to hide and show numerous elements without explicitly visiting each element individually to update them in some way that changed the display style to and from hidden. So I came up with the following:

<style>
  /* The bulk of the css rules should go here or in an external css file */
  /* None of these rules will be changed, but may be overridden */
  .aclass { display: inline-block; width: 50px; height: 30px; }
</style>
<style id="style">
  /* Only the rules to be changed should go in this style */
  .bclass { display: inline-block; }
</style>
<script>
  //
  // This is a helper function that returns the named style as an object.
  // This could also be done in other ways.
  // 
  function setStyle() { return document.getElementById( 'style' ); }
</script>
<div id="d1" class="aclass" style="background-color: green;">
  Hi
</div>
<!-- The element to be shown and hidden --> 
<div id="d2" class="aclass bclass" style="background-color: yellow;">
  there
</div>
<div id="d3" class="aclass" style="background-color: lightblue;">
  sailor
</div>
<hr />
<!-- These buttons demonstrate hiding and showing the d3 dive element -->
<button onclick="setStyle().innerHTML = '.bclass { display: none; }';">
  Hide
</button>&nbsp;&nbsp;
<button onclick="setStyle().innerHTML = '.bclass { display: inline-block; }';">
  Show
</button>

By toggling the bclass rule in the embedded and named stylesheet, which comes after the any other relevant style sheets, in this case one with the aclass rule, I could update the just the display css rule in one place and have it override the aclass rule, which also had it's own display rule.

The beauty of this technique is that it is so simple, effectively one line that does the actual work, it doesn't require any libraries, such as JQuery or plug-ins, and the real work of updating all of the places where the change applies is performed by the browser's css core functionality, not in JavaScript. Also, it works in IE 9 and above, Chrome, Safari, Opera, and all of the other browsers that MicroSoft Edge could emulate, for desktop and tablet/phones devices.

Adding a leading zero to some values in column in MySQL

I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):

UPDATE table SET phone_num = concat('0', phone_num) 

I just concated 0 in front of the phone_num.

Changing the row height of a datagridview

You can set the row height by code

dataGridView.RowTemplate.Height = 35;

or by property panel

enter image description here

How can one see content of stack with GDB?

info frame to show the stack frame info

To read the memory at given addresses you should take a look at x

x/x $esp for hex x/d $esp for signed x/u $esp for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip etc.

Is it fine to have foreign key as primary key?

Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.

Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.

The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.

How do I update the password for Git?

In my Windows machine, I tried the solution of @nzrytmn i.e., Control Panel>Search Credentials>Select "ManageCredentials">modified new credentials under git option category corresponding to my username. And then,

Deleted current password:

git config --global --unset user.password

Added new password:

git config --global --add user.password "new_password"

And It worked for me.