Programs & Examples On #Pycairo

A set of Python bindings for the cairo graphics library.

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

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

Unable to set variables in bash script

Five problems:

  1. Don't put a space before or after the equal sign.
  2. Use "$(...)" to get the output of a command as text.
  3. [ is a command. Put a space between it and the arguments.
  4. Commands are case-sensitive. You want echo.
  5. Use double quotes around variables. rm "$folderToBeMoved"

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Length of a JavaScript object

What about something like this --

function keyValuePairs() {
    this.length = 0;
    function add(key, value) { this[key] = value; this.length++; }
    function remove(key) { if (this.hasOwnProperty(key)) { delete this[key]; this.length--; }}
}

How to plot a subset of a data frame in R?

This chunk should do the work:

plot(var2 ~ var1, data=subset(dataframe, var3 < 150))

My best regards.

How this works:

  1. Fisrt, we make selection using the subset function. Other possibilities can be used, like, subset(dataframe, var4 =="some" & var5 > 10). The "&" operator can be used to select all "some" and over 10. Also the operator "|" could be used to select "some" or "over 10".
  2. The next step is to plot the results of the subset, using tilde (~) operator, that just imply a formula, in this case var.response ~ var.independet. Of course this is not a formula, but works great for this case.

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

This is a very old thread but thought to share this answer as it took lot of my development time to manage NULL return of BitmapFactory.decodeByteArray() as @Anirudh has faced.

If the encodedImage string is a JSON response, simply use Base64.URL_SAFE instead of Base64.DEAULT

byte[] decodedString = Base64.decode(encodedImage, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

How to get the instance id from within an ec2 instance?

Motivation: User would like to Retrieve aws instance metadata.

Solution: The IP address 169.254.169.254 is a link-local address (and is valid only from the instance) aws gives us link with dedicated Restful API for Retrieving metadata of our running instance (Note that you are not billed for HTTP requests used to retrieve instance metadata and user data) . for Additional Documentation

Example:

//Request:
curl http://169.254.169.254/latest/meta-data/instance-id

//Response
ami-123abc

You able to get additional metadata labels of your instance using this link http://169.254.169.254/latest/meta-data/<metadata-field> just choose the right tags:

  1. ami-id
  2. ami-launch-index
  3. ami-manifest-path
  4. block-device
  5. mapping
  6. events
  7. hibernation
  8. hostname
  9. iam
  10. identity-credentials
  11. instance-action
  12. instance-id
  13. instance-type
  14. local-hostname
  15. local-ipv4
  16. mac
  17. metrics
  18. network
  19. placement
  20. profile
  21. reservation-id
  22. security-groups
  23. services

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

You don't need to add the concat package, you can do this via cssmin like this:

cssmin : {
      options: {
            keepSpecialComments: 0
      },
      minify : {
            expand : true,
            cwd : '/library/css',
            src : ['*.css', '!*.min.css'],
            dest : '/library/css',
            ext : '.min.css'
      },
      combine : {
        files: {
            '/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
        }
      }
    }

And for js, use uglify like this:

uglify: {
      my_target: {
        files: {
            '/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
        }
      }
    }

getActionBar() returns null

I faced the above issue where getActionBar() method returns null. I was calling the getActionBar() after setting the setContentView() and still its returning a null.

I resolved the issue by setting the min-sdk version in Android Manifest file that was missing initially. <uses-sdk android:minSdkVersion="11" />

Order data frame rows according to vector with specific order

We can adjust the factor levels based on target and use it in arrange

library(dplyr)
df %>% arrange(factor(name, levels = target))

#  name value
#1    b  TRUE
#2    c FALSE
#3    a  TRUE
#4    d FALSE

Or order it and use it in slice

df %>% slice(order(factor(name, levels = target)))

Remove spaces from std::string in C++

I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.

EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.

You should try different approaches and see what is best for you: you might not have any performance issues at all.

How to set bootstrap navbar active class with Angular JS?

Just you'll have to add the required active-class with required color code.

Ex: ng-class="{'active': currentNavSelected}" ng-click="setNav"

Access nested dictionary items via a list of keys?

How about using recursive functions?

To get a value:

def getFromDict(dataDict, maplist):
    first, rest = maplist[0], maplist[1:]

    if rest: 
        # if `rest` is not empty, run the function recursively
        return getFromDict(dataDict[first], rest)
    else:
        return dataDict[first]

And to set a value:

def setInDict(dataDict, maplist, value):
    first, rest = maplist[0], maplist[1:]

    if rest:
        try:
            if not isinstance(dataDict[first], dict):
                # if the key is not a dict, then make it a dict
                dataDict[first] = {}
        except KeyError:
            # if key doesn't exist, create one
            dataDict[first] = {}

        setInDict(dataDict[first], rest, value)
    else:
        dataDict[first] = value

Can jQuery provide the tag name?

I think you cannot use the nodeName in jQuery since nodeName is a DOM property and jQuery itself do not have a either a nodeName function or property. But based on the respondent who first mentioned about this nodeName stuff, this is how I was able to resolve the problem:

this.attr("id", "rnd" + this.attr("nodeName") + "_" + i.toString());

NOTE: this here is a jQuery object.

Removing carriage return and new-line from the end of a string in c#

This will trim off any combination of carriage returns and newlines from the end of s:

s = s.TrimEnd(new char[] { '\r', '\n' });

Edit: Or as JP kindly points out, you can spell that more succinctly as:

s = s.TrimEnd('\r', '\n');

JavaScript - document.getElementByID with onClick

The onclick property is all lower-case, and accepts a function, not a string.

document.getElementById("test").onclick = foo2;

See also addEventListener.

How to choose an AWS profile when using boto3 to connect to CloudFront

Just add profile to session configuration before client call. boto3.session.Session(profile_name='YOUR_PROFILE_NAME').client('cloudwatch')

SSIS Convert Between Unicode and Non-Unicode Error

  1. First, add a data conversion block into your data flow diagram.

  2. Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.

  3. Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.

  4. Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).

XAMPP: Couldn't start Apache (Windows 10)

Steps:

  • Open the XAMMP Control Panel
  • Open Apache Config, and then select the Apache - xammp- configuration file
  • Search for "Port 443", and then change it to some other port, let’s say 4433
  • Then restart.

Cookie blocked/not saved in IFRAME in Internet Explorer

I was investigating this problem with regard to login-off via Azure Access Control Services, and wasn't able to connect head and tails of anything.

Then, stumbled over this post https://blogs.msdn.microsoft.com/ieinternals/2011/03/10/beware-cookie-sharing-in-cross-zone-scenarios/

In short, IE doesn't share cookies across zones (eg. Internet vs. Trusted sites).

So, if your IFrame target and html page are in different zone's P3P won't help with anything.

Rails params explained?

Params contains the following three groups of parameters:

  1. User supplied parameters
    • GET (http://domain.com/url?param1=value1&param2=value2 will set params[:param1] and params[:param2])
    • POST (e.g. JSON, XML will automatically be parsed and stored in params)
    • Note: By default, Rails duplicates the user supplied parameters and stores them in params[:user] if in UsersController, can be changed with wrap_parameters setting
  2. Routing parameters
    • match '/user/:id' in routes.rb will set params[:id]
  3. Default parameters
    • params[:controller] and params[:action] is always available and contains the current controller and action

How do I disable orientation change on Android?

You need to modify AndroidManifest.xml as Intrications (previously Ashton) mentioned and make sure the activity handles the onConfigurationChanged event as you want it handled. This is how it should look:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Why do we use __init__ in Python classes?

It seems like you need to use __init__ in Python if you want to correctly initialize mutable attributes of your instances.

See the following example:

>>> class EvilTest(object):
...     attr = []
... 
>>> evil_test1 = EvilTest()
>>> evil_test2 = EvilTest()
>>> evil_test1.attr.append('strange')
>>> 
>>> print "This is evil:", evil_test1.attr, evil_test2.attr
This is evil: ['strange'] ['strange']
>>> 
>>> 
>>> class GoodTest(object):
...     def __init__(self):
...         self.attr = []
... 
>>> good_test1 = GoodTest()
>>> good_test2 = GoodTest()
>>> good_test1.attr.append('strange')
>>> 
>>> print "This is good:", good_test1.attr, good_test2.attr
This is good: ['strange'] []

This is quite different in Java where each attribute is automatically initialized with a new value:

import java.util.ArrayList;
import java.lang.String;

class SimpleTest
{
    public ArrayList<String> attr = new ArrayList<String>();
}

class Main
{
    public static void main(String [] args)
    {
        SimpleTest t1 = new SimpleTest();
        SimpleTest t2 = new SimpleTest();

        t1.attr.add("strange");

        System.out.println(t1.attr + " " + t2.attr);
    }
}

produces an output we intuitively expect:

[strange] []

But if you declare attr as static, it will act like Python:

[strange] [strange]

Access a URL and read Data with R

In the simplest case, just do

X <- read.csv(url("http://some.where.net/data/foo.csv"))

plus which ever options read.csv() may need.

Edit in Sep 2020 or 9 years later:

For a few years now R also supports directly passing the URL to read.csv:

X <- read.csv("http://some.where.net/data/foo.csv")

End of 2020 edit. Original post continutes.

Long answer: Yes this can be done and many packages have use that feature for years. E.g. the tseries packages uses exactly this feature to download stock prices from Yahoo! for almost a decade:

R> library(tseries)
Loading required package: quadprog
Loading required package: zoo

    ‘tseries’ version: 0.10-24

    ‘tseries’ is a package for time series analysis and computational finance.

    See ‘library(help="tseries")’ for details.

R> get.hist.quote("IBM")
trying URL 'http://chart.yahoo.com/table.csv?    ## manual linebreak here
  s=IBM&a=0&b=02&c=1991&d=5&e=08&f=2011&g=d&q=q&y=0&z=IBM&x=.csv'
Content type 'text/csv' length unknown
opened URL
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
.......... .......... .......... .......... ..........
........
downloaded 258 Kb

             Open   High    Low  Close
1991-01-02 112.87 113.75 112.12 112.12
1991-01-03 112.37 113.87 112.25 112.50
1991-01-04 112.75 113.00 111.87 112.12
1991-01-07 111.37 111.87 110.00 110.25
1991-01-08 110.37 110.37 108.75 109.00
1991-01-09 109.75 110.75 106.75 106.87
[...]

This is all exceedingly well documented in the manual pages for help(connection) and help(url). Also see the manul on 'Data Import/Export' that came with R.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;
}
System.out.println(sum);

// while loop

sum = 0;
int j = 1;

while(j<=100){
    sum = sum + j;
    j++;
}

System.out.println(sum);

// do while loop

sum = 0;
j = 1;

do{
    sum = sum + j;
    j++;
}
while(j<=100);

System.out.println(sum);

In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

How to negate the whole regex?

Use negative lookaround: (?!pattern)

Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

Links to regular-expressions.info

See also

More examples

These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):

How can I color dots in a xy scatterplot according to column value?

I answered a very similar question:

https://stackoverflow.com/a/15982217/1467082

You simply need to iterate over the series' .Points collection, and then you can assign the points' .Format.Fill.ForeColor.RGB value based on whatever criteria you need.

UPDATED

The code below will color the chart per the screenshot. This only assumes three colors are used. You can add additional case statements for other color values, and update the assignment of myColor to the appropriate RGB values for each.

screenshot

Option Explicit
Sub ColorScatterPoints()
    Dim cht As Chart
    Dim srs As Series
    Dim pt As Point
    Dim p As Long
    Dim Vals$, lTrim#, rTrim#
    Dim valRange As Range, cl As Range
    Dim myColor As Long

    Set cht = ActiveSheet.ChartObjects(1).Chart
    Set srs = cht.SeriesCollection(1)

   '## Get the series Y-Values range address:
    lTrim = InStrRev(srs.Formula, ",", InStrRev(srs.Formula, ",") - 1, vbBinaryCompare) + 1
    rTrim = InStrRev(srs.Formula, ",")
    Vals = Mid(srs.Formula, lTrim, rTrim - lTrim)
    Set valRange = Range(Vals)

    For p = 1 To srs.Points.Count
        Set pt = srs.Points(p)
        Set cl = valRange(p).Offset(0, 1) '## assume color is in the next column.

        With pt.Format.Fill
            .Visible = msoTrue
            '.Solid  'I commented this out, but you can un-comment and it should still work
            '## Assign Long color value based on the cell value
            '## Add additional cases as needed.
            Select Case LCase(cl)
                Case "red"
                    myColor = RGB(255, 0, 0)
                Case "orange"
                    myColor = RGB(255, 192, 0)
                Case "green"
                    myColor = RGB(0, 255, 0)
            End Select

            .ForeColor.RGB = myColor

        End With
    Next


End Sub

Maximum execution time in phpMyadmin

Changing php.ini for a web application requires restarting Apache.

You should verify that the change took place by running a PHP script that executes the function phpinfo(). The output of that function will tell you a lot of PHP parameters, including the timeout value.

You might also have changed a copy of php.ini that is not the same file used by Apache.

Why are the Level.FINE logging messages not showing?

Tried other variants, this can be proper

    Logger logger = Logger.getLogger(MyClass.class.getName());        
    Level level = Level.ALL;
    for(Handler h : java.util.logging.Logger.getLogger("").getHandlers())    
        h.setLevel(level);
    logger.setLevel(level);
// this must be shown
    logger.fine("fine");
    logger.info("info");

Is there a way to get version from package.json in nodejs code?

NPM one liner:

npm -s run env echo '$npm_package_version'

Plotting lines connecting points

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

Plot of two pairs of points, each connected by a separate line

How to check task status in Celery?

I found helpful information in the

Celery Project Workers Guide inspecting-workers

For my case, I am checking to see if Celery is running.

inspect_workers = task.app.control.inspect()
if inspect_workers.registered() is None:
    state = 'FAILURE'
else:
    state = str(task.state) 

You can play with inspect to get your needs.

How can I match a string with a regex in Bash?

if [[ $STR == *pattern* ]]
then
    echo "It is the string!"
else
    echo "It's not him!"
fi

Works for me! GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Can Twitter Bootstrap alerts fade in as well as out?

Add hide class to alert-message. Then put the following code after your jQuery script import:

$(document).ready( function(){
    $(".alert-message").animate({ 'height':'toggle','opacity':'toggle'});
    window.setTimeout( function(){
        $(".alert-message").slideUp();
    }, 2500);
});

If you want handle multiple messages, this code will hide them in ascending order:

$(document).ready( function(){
   var hide_delay = 2500;  // starting timeout before first message is hidden
   var hide_next = 800;   // time in mS to wait before hiding next message
   $(".alert-message").slideDown().each( function(index,el) {
      window.setTimeout( function(){
         $(el).slideUp();  // hide the message
      }, hide_delay + hide_next*index);
   });
});

Rails: update_attribute vs update_attributes

update_attribute simply updates only one attribute of a model, but we can pass multiple attributes in update_attributes method.

Example:

user = User.last

#update_attribute
user.update_attribute(:status, "active")

It pass the validation

#update_attributes
user.update_attributes(first_name: 'update name', status: "active")

it doesn't update if validation fails.

How do I start a process from C#?

To start Microsoft Word for example, use this code:

private void button1_Click(object sender, EventArgs e)
{
    string ProgramName = "winword.exe";
    Process.Start(ProgramName);
}

For more explanations, check out this link.

Location of ini/config files in linux/unix?

Newer Applications

Follow XDG Base Directory Specification usually ~/.config/yourapp/* can be INF, JSON, YML or whatever format floats your boat, and whatever files... yourapp should match your executable name, or be namespaced with your organization/company/username/handle to ~/.config/yourorg/yourapp/*

Older Applications

Per-user configuration, usually right in your home directory...

  • ~/.yourapp file for a single file
  • ~/.yourapp/ for multiple files + data usually in ~/.yourapp/config

Global configurations are generally in /etc/appname file or /etc/appname/ directory.

Global App data: /var/lib/yourapp/

Cache data: /var/cache/

Log data: /var/log/yourapp/


Some additional info from tutorialhelpdesk.com

The directory structure of Linux/other Unix-like systems and directory details.

In Windows, almost all programs install their files (all files) in the directory named: 'Program Files' Such is not the case in Linux. The directory system categorizes all installed files. All configuration files are in /etc, all binary files are in /bin or /usr/bin or /usr/local/bin. Here is the entire directory structure along with what they contain:

/ - Root directory that forms the base of the file system. All files and directories are logically contained inside the root directory regardless of their physical locations.

/bin - Contains the executable programs that are part of the Linux operating system. Many Linux commands, such as cat, cp, ls, more, and tar, are locate in /bin

/boot - Contains the Linux kernel and other files needed by LILO and GRUB boot managers.

/dev - Contains all device files. Linux treats each device as a special file. All such files are located in /dev.

/etc - Contains most system configuration files and the initialisation scripts in /etc/rc.d subdirectory.

/home - Home directory is the parent to the home directories of users.

/lib - Contains library files, including loadable driver modules needed to boot the system.

/lost+found - Directory for lost files. Every disk partition has a lost+found directory.

/media - Directory for mounting files systems on removable media like CD-ROM drives, floppy disks, and Zip drives.

/mnt - A directory for temporarily mounted filesystems.

/opt - Optional software packages copy/install files here.

/proc - A special directory in a virtual filesystem. It contains the information about various aspects of a Linux system.

/root - Home directory of the root user.

/sbin - Contains administrative binary files. Commands such as mount, shutdown, umount, reside here.

/srv - Contains data for services (HTTP, FTP, etc.) offered by the system.

/sys - A special directory that contains information about the devices, as seen by the Linux kernel.

/tmp - Temporary directory which can be used as a scratch directory (storage for temporary files). The contents of this directory are cleared each time the system boots.

/usr - Contains subdirectories for many programs such as the X Window System.

/usr/bin - Contains executable files for many Linux commands. It is not part of the core Linux operating system.

/usr/include - Contains header files for C and C++ programming languages

/usr/lib - Contains libraries for C and C++ programming languages.

/usr/local - Contains local files. It has a similar directories as /usr contains.

/usr/sbin - Contains administrative commands.

/usr/share - Contains files that are shared, like, default configuration files, images, documentation, etc.

/usr/src - Contains the source code for the Linux kernel.

/var - Contains various system files such as log, mail directories, print spool, etc. which tend to change in numbers and size over time.

/var/cache - Storage area for cached data for applications.

/var/lib - Contains information relating to the current state of applications. Programs modify this when they run.

/var/lock - Contains lock files which are checked by applications so that a resource can be used by one application only.

/var/log - Contains log files for different applications.

/var/mail - Contains users' emails.

/var/opt - Contains variable data for packages stored in /opt directory.

/var/run - Contains data describing the system since it was booted.

/var/spool - Contains data that is waiting for some kind of processing.

/var/tmp - Contains temporary files preserved between system reboots.

Signing a Windows EXE file

The ASP's magazine ASPects has a detailed description on how to sign code (You have to be a member to read the article). You can download it through http://www.asp-shareware.org/

Here's link to a description how you can make your own test certificate.

This might also be interesting.

jQuery click not working for dynamically created items

Try something like

$("#container").on('click', 'someLinkSelector', function(){ $("#container").html( <new html with new spans> ) });

You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.

Can an AWS Lambda function call another

I'm having the same problem but the Lambda function that I implement will insert an entry in DynamoDB, so my solution uses DynamoDB Triggers.

I make the DB invoke a Lambda function for every insert/update in the table, so this separates the implementation of two Lambda functions.

Documentation is here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html

Here is a guided walkthrough: https://aws.amazon.com/blogs/aws/dynamodb-update-triggers-streams-lambda-cross-region-replication-app/

Where are the Properties.Settings.Default stored?

thanks for pointing me in the right direction. I found user.config located at this monstrosity: c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.

I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.

What is the iPhone 4 user-agent?

You cannot identify the (hardware) version of an iPhone by user agent.

It's only possible to recognize that it's an iPhone and which software versions it's running.

Using the Safari User Agent String

Not even WURLF can.

AngularJS - value attribute for select

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):

HTML:

<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

Javascript:

App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>

and

<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.

How do I send a file in Android from a mobile device to server using http?

This can be done with a HTTP Post request to the server:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

Rename master branch for both local and remote Git repositories

The selected answer failed when I tried it. It throws an error: refusing to delete the current branch: refs/heads/master. I guess I'll post what works for me:

git checkout master             # if not in master already

git branch placeholder          # create placeholder branch
git checkout placeholder        # checkout to placeholder
git push remote placeholder     # push placeholder to remote repository

git branch -d master            # remove master in local repository
git push remote :master         # remove master from remote repository.

The trick is to checkout to the placeholder right before pushing it to remote repository. The rest is self explanatory, deleting the master branch and push it to the remote repository should works now. Excerpted from here.

Is there a way to reset IIS 7.5 to factory settings?

You need to uninstall IIS (Internet Information Services) but the key thing here is to make sure you uninstall the Windows Process Activation Service or otherwise your ApplicationHost.config will be still around. When you uninstall WAS then your configuration will be cleaned up and you will truly start with a fresh new IIS (and all data/configuration will be lost).

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using logging in multiple modules

A simple way of using one instance of logging library in multiple modules for me was following solution:

base_logger.py

import logging

logger = logging
logger.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)

Other files

from base_logger import logger

if __name__ == '__main__':
    logger.info("This is an info message")

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

At startup, we do:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

How to use timeit module

This works great:

  python -m timeit -c "$(cat file_name.py)"

How to delete a whole folder and content?

private static void deleteRecursive(File dir)
{
    //Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
    if (dir.isDirectory())
    {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++)
        {
            File temp = new File(dir, children[i]);
            deleteRecursive(temp);
        }

    }

    if (dir.delete() == false)
    {
        Log.d("DeleteRecursive", "DELETE FAIL");
    }
}

Display unescaped HTML in Vue.js

You can use the directive v-html to show it. like this:

<td v-html="desc"></td>

Use child_process.execSync but keep output in console

Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.

To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:

var spawn = require('child_process').spawn;

//kick off process of listing files
var child = spawn('ls', ['-l', '/']);

//spit stdout to screen
child.stdout.on('data', function (data) {   process.stdout.write(data.toString());  });

//spit stderr to screen
child.stderr.on('data', function (data) {   process.stdout.write(data.toString());  });

child.on('close', function (code) { 
    console.log("Finished with code " + code);
});

I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.

However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:

var execSync = require('child_process').execSync;

execSync("xterm -title RecursiveFileListing -e ls -latkR /");

This will allow you to see what your command is doing in the new terminal but still have the synchronous call.

How do I extract value from Json

Use a JSON parser. There are plenty of JSON parsers written in Java.

http://www.json.org/

Look under the Java section and find one you like.

Get records of current month

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());

Regarding 'main(int argc, char *argv[])'

With argc (argument count) and argv (argument vector) you can get the number and the values of passed arguments when your application has been launched.

This way you can use parameters (such as -version) when your application is started to act a different way.

But you can also use int main(void) as a prototype in C.

There is a third (less known and nonstandard) prototype with a third argument which is envp. It contains environment variables.


Resources:

Using "label for" on radio buttons

Either structure is valid and accessible, but the for attribute should be equal to the id of the input element:

<input type="radio" ... id="r1" /><label for="r1">button text</label>

or

<label for="r1"><input type="radio" ... id="r1" />button text</label>

The for attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +:

input[type="radio"]:checked+label {font-weight:bold;}

How to reset postgres' primary key sequence when it falls out of sync?

This command for only change auto generated key sequence value in postgresql

ALTER SEQUENCE "your_sequence_name" RESTART WITH 0;

In place of zero you can put any number from which you want to restart sequence.

default sequence name will "TableName_FieldName_seq". For example, if your table name is "MyTable" and your field name is "MyID", then your sequence name will be "MyTable_MyID_seq".

This is answer is same as @murugesanponappan's answer, but there is a syntax error in his solution. you can not use sub query (select max()...) in alter command. So that either you have to use fixed numeric value or you need to use a variable in place of sub query.

how to change namespace of entire project?

I imagine a simple Replace in Files (Ctrl+Shift+H) will just about do the trick; simply replace namespace DemoApp with namespace MyApp. After that, build the solution and look for compile errors for unknown identifiers. Anything that fully qualified DemoApp will need to be changed to MyApp.

What's the difference between a Future and a Promise?

Future and Promise are proxy object for unknown result

Promise completes a Future

  • Future - read/consumer of unknown result

  • Promise - write/producer of unknown result.

//Future has a reference to Promise
Future -> Promise

As a producer I promise something and responsible for it

As a consumer who retrieved a promise I expect to have a result in future

As for Java CompletableFutures it is a Promise because you can set the result and also it implements Future

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.

TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.

Python module for converting PDF to text

slate is a project that makes it very simple to use PDFMiner from a library:

>>> with open('example.pdf') as f:
...    doc = slate.PDF(f)
...
>>> doc
[..., ..., ...]
>>> doc[1]
'Text from page 2...'   

Closing WebSocket correctly (HTML5, Javascript)

The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF] protocol, and then there's the new version using Hybi formatted packets.

The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!

However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88 (better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.

Appending a line to a file only if it does not already exist

If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"

Composer: The requested PHP extension ext-intl * is missing from your system

(with xampp server)open php.ini in ".\xampp\php"

change ;extension=intl to extension=intl

How to post SOAP Request from PHP

You might want to look here and here.

A Little code example from the first link:

<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
        print "Error: ". $fault;
        }
else if ($price == -1) {
        print "The book is not in the database.";
} else {
        // otherwise output the result
        print "The price of book number ". $param[isbn] ." is $". $price;
        }
// kill object
unset($client);
?>

Adding content to a linear layout dynamically?

LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);

JavaScript check if value is only undefined, null or false

Another solution:

Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

So

if(Boolean(val))
{
//executable...
}

Understanding events and event handlers in C#

C# knows two terms, delegate and event. Let's start with the first one.

Delegate

A delegate is a reference to a method. Just like you can create a reference to an instance:

MyClass instance = myFactory.GetInstance();

You can use a delegate to create an reference to a method:

Action myMethod = myFactory.GetInstance;

Now that you have this reference to a method, you can call the method via the reference:

MyClass instance = myMethod();

But why would you? You can also just call myFactory.GetInstance() directly. In this case you can. However, there are many cases to think about where you don't want the rest of the application to have knowledge of myFactory or to call myFactory.GetInstance() directly.

An obvious one is if you want to be able to replace myFactory.GetInstance() into myOfflineFakeFactory.GetInstance() from one central place (aka factory method pattern).

Factory method pattern

So, if you have a TheOtherClass class and it needs to use the myFactory.GetInstance(), this is how the code will look like without delegates (you'll need to let TheOtherClass know about the type of your myFactory):

TheOtherClass toc;
//...
toc.SetFactory(myFactory);


class TheOtherClass
{
   public void SetFactory(MyFactory factory)
   {
      // set here
   }

}

If you'd use delegates, you don't have to expose the type of my factory:

TheOtherClass toc;
//...
Action factoryMethod = myFactory.GetInstance;
toc.SetFactoryMethod(factoryMethod);


class TheOtherClass
{
   public void SetFactoryMethod(Action factoryMethod)
   {
      // set here
   }

}

Thus, you can give a delegate to some other class to use, without exposing your type to them. The only thing you're exposing is the signature of your method (how many parameters you have and such).

"Signature of my method", where did I hear that before? O yes, interfaces!!! interfaces describe the signature of a whole class. Think of delegates as describing the signature of only one method!

Another large difference between an interface and a delegate is that when you're writing your class, you don't have to say to C# "this method implements that type of delegate". With interfaces, you do need to say "this class implements that type of an interface".

Further, a delegate reference can (with some restrictions, see below) reference multiple methods (called MulticastDelegate). This means that when you call the delegate, multiple explicitly-attached methods will be executed. An object reference can always only reference to one object.

The restrictions for a MulticastDelegate are that the (method/delegate) signature should not have any return value (void) and the keywords out and ref is not used in the signature. Obviously, you can't call two methods that return a number and expect them to return the same number. Once the signature complies, the delegate is automatically a MulticastDelegate.

Event

Events are just properties (like the get;set; properties to instance fields) which expose subscription to the delegate from other objects. These properties, however, don't support get;set;. Instead, they support add; remove;

So you can have:

    Action myField;

    public event Action MyProperty
    {
        add { myField += value; }
        remove { myField -= value; }
    }

Usage in UI (WinForms,WPF,UWP So on)

So, now we know that a delegate is a reference to a method and that we can have an event to let the world know that they can give us their methods to be referenced from our delegate, and we are a UI button, then: we can ask anyone who is interested in whether I was clicked, to register their method with us (via the event we exposed). We can use all those methods that were given to us and reference them by our delegate. And then, we'll wait and wait.... until a user comes and clicks on that button, then we'll have enough reason to invoke the delegate. And because the delegate references all those methods given to us, all those methods will be invoked. We don't know what those methods do, nor we know which class implements those methods. All we do care about is that someone was interested in us being clicked, and gave us a reference to a method that complied with our desired signature.

Java

Languages like Java don't have delegates. They use interfaces instead. The way they do that is to ask anyone who is interested in 'us being clicked', to implement a certain interface (with a certain method we can call), then give us the whole instance that implements the interface. We keep a list of all objects implementing this interface and can call their 'certain method we can call' whenever we get clicked.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

By default, oracle date subtraction returns a result in # of days.

So just multiply by 24 to get # of hours, and again by 60 for # of minutes.

Example:

select
  round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
  (
  select
    to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
   ,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
  from
    dual
  ) test_data

Html attributes for EditorFor() in ASP.NET MVC

Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (It's either a case of Great mind thinking alike or they read my answer :)

End Update

If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.

@Html.EditorFor(modelItem => item.YourProperty, 
  new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px"  } })

then in your template (not required for simple types in MVC 5.1)

@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

What is the difference between "INNER JOIN" and "OUTER JOIN"?

In Simple Terms,

1.INNER JOIN OR EQUI JOIN : Returns the resultset that matches only the condition in both the tables.

2.OUTER JOIN : Returns the resultset of all the values from both the tables even if there is condition match or not.

3.LEFT JOIN : Returns the resultset of all the values from left table and only rows that match the condition in right table.

4.RIGHT JOIN : Returns the resultset of all the values from right table and only rows that match the condition in left table.

5.FULL JOIN : Full Join and Full outer Join are same.

How to Save Console.WriteLine Output to Text File

For the question:

How to save Console.Writeline Outputs to text file?

I would use Console.SetOut as others have mentioned.


However, it looks more like you are keeping track of your program flow. I would consider using Debug or Trace for keeping track of the program state.

It works similar the console except you have more control over your input such as WriteLineIf.

Debug will only operate when in debug mode where as Trace will operate in both debug or release mode.

They both allow for listeners such as output files or the console.

TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);

TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
Debug.Listeners.Add(tr2);

-http://support.microsoft.com/kb/815788

Character Limit in HTML

use the "maxlength" attribute as others have said.

if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

you can create a service and generate excel on server and then allow clients download excel. cos buying excel license for 1000 ppl, it is better to have one license for server.

hope that helps.

"Eliminate render-blocking CSS in above-the-fold content"

I too have struggled with this new pagespeed metric.

Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.

Combining all css into one file helped a lot. All my sites are back up to %95 - %98.

The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.

PHP array printing using a loop

Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.

batch file Copy files with certain extensions from multiple directories into one directory

In a batch file solution

for /R c:\source %%f in (*.xml) do copy %%f x:\destination\

The code works as such;

for each file for in directory c:\source and subdirectories /R that match pattern (\*.xml) put the file name in variable %%f, then for each file do copy file copy %%f to destination x:\\destination\\

Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f variable name version, as described in the linked question above.

Java Spring Boot: How to map my app root (“/”) to index.html?

It would have worked out of the box if you hadn't used @EnableWebMvc annotation. When you do that you switch off all the things that Spring Boot does for you in WebMvcAutoConfiguration. You could remove that annotation, or you could add back the view controller that you switched off:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}

Can I access a form in the controller?

Yes, you can access a form in the controller (as stated in the docs).

Except when your form is not defined in the controller scope and is defined in a child scope instead.

Basically, some angular directives, such as ng-if, ng-repeat or ng-include, will create an isolated child scope. So will any custom directives with a scope: {} property defined. Probably, your foundation components are also in your way.

I had the same problem when introducing a simple ng-if around the <form> tag.

See these for more info:

Note: I suggest you re-write your question. The answer to your question is yes but your problem is slightly different:

Can I access a form in a child scope from the controller?

To which the answer would simply be: no.

How to convert a file to utf-8 in Python?

To guess what's the source encoding you can use the file *nix command.

Example:

$ file --mime jumper.xml

jumper.xml: application/xml; charset=utf-8

How to format a number as percentage in R?

try this~

data_format <- function(data,digit=2,type='%'){
if(type=='d') {
    type = 'f';
    digit = 0;
}
switch(type,
    '%' = {format <- paste("%.", digit, "f%", type, sep='');num <- 100},
    'f' = {format <- paste("%.", digit, type, sep='');num <- 1},
    cat(type, "is not a recognized type\n")
)
sprintf(format, num * data)
}

Do I really need to encode '&' as '&amp;'?

In HTML a & marks the begin of a reference, either of a character reference or of an entity reference. From that point on the parser expects either a # denoting a character reference, or an entity name denoting an entity reference, both followed by a ;. That’s the normal behavior.

But if the reference name or just the reference opening & is followed by a white space or other delimiters like ", ', <, >, &, the ending ; and even a reference to represent a plain & can be omitted:

<p title="&amp;">foo &amp; bar</p>
<p title="&amp">foo &amp bar</p>
<p title="&">foo & bar</p>

Only in these cases the ending ; or even the reference itself can be omitted (at least in HTML 4). I think HTML 5 requires the ending ;.

But the specification recommends to always use a reference like the character reference &#38; or the entity reference &amp; to avoid confusion:

Authors should use "&amp;" (ASCII decimal 38) instead of "&" to avoid confusion with the beginning of a character reference (entity reference open delimiter). Authors should also use "&amp;" in attribute values since character references are allowed within CDATA attribute values.

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

Android Studio 3.0 Execution failed for task: unable to merge dex

For me, adding

multiDexEnabled true

and

packagingOptions {
        exclude 'META-INF/NOTICE' 
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }

into the app level Build.gradle file solved the issue

How to make git mark a deleted and a new file as a file move?

There is a probably a better “command line” way to do this, and I know this is a hack, but I’ve never been able to find a good solution.

Using TortoiseGIT: If you have a GIT commit where some file move operations are showing up as load of adds/deletes rather than renames, even though the files only have small changes, then do this:

  1. Check in what you have done locally
  2. Check in a mini one-line change in a 2nd commit
  3. Go to GIT log in tortoise git
  4. Select the two commits, right click, and select “merge into one commit”

The new commit will now properly show the file renames… which will help maintain proper file history.

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

Perhaps something that's not been mentioned is that of locality.

A MAC address or time-based ordering (UUID1) can afford increased database performance, since it's less work to sort numbers closer-together than those distributed randomly (UUID4) (see here).

A second related issue, is that using UUID1 can be useful in debugging, even if origin data is lost or not explicitly stored (this is obviously in conflict with the privacy issue mentioned by the OP).

How to reenable event.preventDefault?

You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding. There is no magical event.cancelled=false;

As requested

 $('form').submit( function(ev){

         ev.preventDefault();

         //later you decide you want to submit
         $(this).unbind('submit').submit()

  });

How do I pass multiple parameters into a function in PowerShell?

I don't know what you're doing with the function, but have a look at using the 'param' keyword. It's quite a bit more powerful for passing parameters into a function, and makes it more user friendly. Below is a link to an overly complex article from Microsoft about it. It isn't as complicated as the article makes it sound.

Param Usage

Also, here is an example from a question on this site:

Check it out.

SQL Server - INNER JOIN WITH DISTINCT

Try this:

select distinct a.FirstName, a.LastName, v.District
from AddTbl a 
  inner join ValTbl v
  on a.LastName = v.LastName
order by a.FirstName;

Or this (it does the same, but the syntax is different):

select distinct a.FirstName, a.LastName, v.District
from AddTbl a, ValTbl v
where a.LastName = v.LastName
order by a.FirstName;

How to find common elements from multiple vectors?

intersect_all <- function(a,b,...){
  all_data <- c(a,b,...)
  require(plyr)
  count_data<- length(list(a,b,...))
  freq_dist <- count(all_data)
  intersect_data <- freq_dist[which(freq_dist$freq==count_data),"x"]
  intersect_data
}


intersect_all(a,b,c)

UPDATE EDIT A simpler code

intersect_all <- function(a,b,...){
  Reduce(intersect, list(a,b,...))
}

intersect_all(a,b,c)

How to get distinct values from an array of objects in JavaScript?

_x000D_
_x000D_
const array = [_x000D_
  { "name": "Joe", "age": 17 }, _x000D_
  { "name":"Bob", "age":17 },_x000D_
  { "name":"Carl", "age": 35 }_x000D_
]_x000D_
_x000D_
const allAges = array.map(a => a.age);_x000D_
_x000D_
const uniqueSet = new Set(allAges)_x000D_
const uniqueArray = [...uniqueSet]_x000D_
_x000D_
console.log(uniqueArray)
_x000D_
_x000D_
_x000D_

What is Java Servlet?

I think servlet is basically a java class which acts as a middle way between HTTP request and HTTP response.Servlet is also used to make your web page dynamic. Suppose for example if you want to redirect to another web page on server then you have to use servlets. Another important thing is that servlet can run on localhost as well as a web browser.

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:

list.Sort();

That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need

_details.Sort();

as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
{
    List<T> tmp = new List<T>(list);
    tmp.Sort();
    for (int i = 0; i < tmp.Count; i++)
    {
        list[i] = tmp[i];
    }
}

In other words, copy, sort in place, then copy the sorted list back.


You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

SELECT using 'CASE' in SQL

which platform ?

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    ELSE FRUIT ='B' THEN 'BANANA' 
   END AS FRUIT     
FROM FRUIT_TABLE;

Map vs Object in JavaScript

Summary:

  • Object: A data structure in which data is stored as key value pairs. In an object the key has to be a number, string, or symbol. The value can be anything so also other objects, functions etc. A object is an non ordered data structure, i.e. the sequence of insertion of key value pairs is not remembered
  • ES6 Map: A data structure in which data is stored as key value pairs. In which a unique key maps to a value. Both the key and the value can be in any data type. A map is a iterable data structure, this means that the sequence of insertion is remembered and that we can access the elements in e.g. a for..of loop

Key differences:

  • A Map is ordered and iterable, whereas a objects is not ordered and not iterable

  • We can put any type of data as a Map key, whereas objects can only have a number, string, or symbol as a key.

  • A Map inherits from Map.prototype. This offers all sorts of utility functions and properties which makes working with Map objects a lot easier.

Example:

object:

_x000D_
_x000D_
let obj = {};_x000D_
_x000D_
// adding properties to a object_x000D_
obj.prop1 = 1;_x000D_
obj[2]    =  2;_x000D_
_x000D_
// getting nr of properties of the object_x000D_
console.log(Object.keys(obj).length)_x000D_
_x000D_
// deleting a property_x000D_
delete obj[2]_x000D_
_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Map:

_x000D_
_x000D_
const myMap = new Map();_x000D_
_x000D_
const keyString = 'a string',_x000D_
    keyObj = {},_x000D_
    keyFunc = function() {};_x000D_
_x000D_
// setting the values_x000D_
myMap.set(keyString, "value associated with 'a string'");_x000D_
myMap.set(keyObj, 'value associated with keyObj');_x000D_
myMap.set(keyFunc, 'value associated with keyFunc');_x000D_
_x000D_
console.log(myMap.size); // 3_x000D_
_x000D_
// getting the values_x000D_
console.log(myMap.get(keyString));    // "value associated with 'a string'"_x000D_
console.log(myMap.get(keyObj));       // "value associated with keyObj"_x000D_
console.log(myMap.get(keyFunc));      // "value associated with keyFunc"_x000D_
_x000D_
console.log(myMap.get('a string'));   // "value associated with 'a string'"_x000D_
                         // because keyString === 'a string'_x000D_
console.log(myMap.get({}));           // undefined, because keyObj !== {}_x000D_
console.log(myMap.get(function() {})) // undefined, because keyFunc !== function () {}
_x000D_
_x000D_
_x000D_

source: MDN

C# looping through an array

string[] friends = new string[4];
friends[0]= "ali";
friends[1]= "Mike";
friends[2]= "jan";
friends[3]= "hamid";

for (int i = 0; i < friends.Length; i++)
{
    Console.WriteLine(friends[i]);
}Console.ReadLine();

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height in the Navbar section.

Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.

How to get everything after last slash in a URL?

One more (idio(ma)tic) way:

URL.split("/")[-1]

Origin http://localhost is not allowed by Access-Control-Allow-Origin

There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

app.get('/item', item.list);
app.options('/item', item.preflight);

and then have the following functions...

exports.list = function (req, res) {
Items.allItems(function (err, items) {
    ...
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(items);
      }
   );
};

and for the pre-flight checks

exports.preflight = function (req, res) {
Items.allItems(function (err, items) {
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(200);
    }
  );
};

You can consolidate the res.header() code into a single function if you want.

Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!

Capturing a single image from my webcam in Java or Python

I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.

You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:

from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave

graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()

Use sudo with password as parameter

One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.

Bootstrap: align input with button

I was also struggling with same issue. The bootstrap classes I use are not working for me. I came up with an workaround, as below:

<form action='...' method='POST' class='form-group'>
  <div class="form-horizontal">
    <input type="text" name="..." 
        class="form-control" 
        placeholder="Search People..."
        style="width:280px;max-width:280px;display:inline-block"/>

    <button type="submit" 
        class="btn btn-primary" 
        style="margin-left:-8px;margin-top:-2px;min-height:36px;">
      <i class="glyphicon glyphicon-search"></i>
     </button>
  </div>
</form>

Basically, I overrode the display property of class "form-control", and used other style properties for correcting the size and position.

Following is the result:

enter image description here

Non greedy (reluctant) regex matching in sed?

sed 's|(http:\/\/[^\/]+\/).*|\1|'

Auto-click button element on page load using jQuery

I tried the following ways in first jQuery, then JavaScript:

jQuery:

 window.location.href = $(".contact").attr('href');
 $('.contactformone').trigger('click');  

This is the best way in JavaScript:

 document.getElementById("id").click();

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

Is there a download function in jsFiddle?

Still no download functionality supported.. BUT.. you can use the jsfiddle-downloader node script.

Installation:

npm install jsfiddle-downloader -g

To download a single fiddle from its id:

jsfiddle-downloader -i <fiddle-id> [-o <output file>]

To download a single fiddle from its url:

jsfiddle-downloader -l <url> [-o <output file>]
jsfiddle-downloader -l jsfiddle.net/<user>/<fiddle-id>
jsfiddle-downloader -l https://jsfiddle.net/<fiddle-id>
jsfiddle-downloader -l https://jsfiddle.net/<user>/<fiddle-id>/show/ -o myfiddle.html

To download all scripts of a determinated 'user' from jsFiddle.net:

jsfiddle-downloader -u <user> [-o <output file>]

It'll download all backups in the currrent directory, the jsFiddles scripts will be named as:

[<output-folder>/]<id-fiddle>.html

In MVC, how do I return a string result?

You can also just return string if you know that's the only thing the method will ever return. For example:

public string MyActionName() {
  return "Hi there!";
}

<Django object > is not JSON serializable

The easiest way is to use a JsonResponse.

For a queryset, you should pass a list of the the values for that queryset, like so:

from django.http import JsonResponse

queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

How can I count the number of elements of a given value in a matrix?

This is a very good function file available on Matlab Central File Exchange.

countmember.m link

This function file is totally vectorized and hence very quick. Plus, in comparison to the function being referred to in aioobe's answer, this function doesn't use the accumarray function, which is why this is even compatible with older versions of Matlab. Also, it works for cell arrays as well as numeric arrays.

SOLUTION : You can use this function in conjunction with the built in matlab function, "unique".

occurance_count = countmember(unique(M),M)

occurance_count will be a numeric array with the same size as that of unique(M) and the different values of occurance_count array will correspond to the count of corresponding values (same index) in unique(M).

Escape a string in SQL Server so that it is safe to use in LIKE expression

Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become

WHERE ... LIKE '%aa[%]bb%'

If you need proof:

create table test (field nvarchar(100))
go
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
go
select * from test where field like 'abcdef[%]hijklm'
go

How best to determine if an argument is not sent to the JavaScript function

Some times you may also want to check for type, specially if you are using the function as getter and setter. The following code is ES6 (will not run in EcmaScript 5 or older):

class PrivateTest {
    constructor(aNumber) {
        let _aNumber = aNumber;

        //Privileged setter/getter with access to private _number:
        this.aNumber = function(value) {
            if (value !== undefined && (typeof value === typeof _aNumber)) {
                _aNumber = value;
            }
            else {
                return _aNumber;
            }
        }
    }
}

How do CSS triangles work?

CSS clip-path

This is something I feel this question has missed; clip-path

clip-path in a nutshell

Clipping, with the clip-path property, is akin to cutting a shape (like a circle or a pentagon) from a rectangular piece of paper. The property belongs to the “CSS Masking Module Level 1” specification. The spec states, “CSS masking provides two means for partially or fully hiding portions of visual elements: masking and clipping”.


clip-path will use the element itself rather than its borders to cut the shape you specify in its parameters. It uses a super simple percentage based co-ordinate system which makes editing it very easy and means you can pick it up and create weird and wonderful shapes in a matter of minutes.


Triangle Shape Example

_x000D_
_x000D_
div {_x000D_
  -webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);_x000D_
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);_x000D_
  background: red;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


Downside

It does have a major downside at the moment, one being it's major lack of support, only really being covered within -webkit- browsers and having no support on IE and only very partial in FireFox.


Resources

Here are some useful resources and material to help better understand clip-path and also start creating your own.

Can we make unsigned byte in Java

I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter

This is not substantially different from a function accepting an integer to which you want to pass a value larger than 2^32-1.

That sounds like it depends on how the function is defined and documented; I can see three possibilities:

  1. It may explicitly document that the function treats the byte as an unsigned value, in which case the function probably should do what you expect but would seem to be implemented wrong. For the integer case, the function would probably declare the parameter as an unsigned integer, but that is not possible for the byte case.

  2. It may document that the value for this argument must be greater than (or perhaps equal to) zero, in which case you are misusing the function (passing an out-of-range parameter), expecting it to do more than it was designed to do. With some level of debugging support you might expect the function to throw an exception or fail an assertion.

  3. The documentation may say nothing, in which case a negative parameter is, well, a negative parameter and whether that has any meaning depends on what the function does. If this is meaningless then perhaps the function should really be defined/documented as (2). If this is meaningful in an nonobvious manner (e.g. non-negative values are used to index into an array, and negative values are used to index back from the end of the array so -1 means the last element) the documentation should say what it means and I would expect that it isn't what you want it to do anyway.

Styling Google Maps InfoWindow

Google wrote some code to assist with this. Here are some examples: Example using InfoBubble, Styled markers and Info Window Custom (using OverlayView).

The code in the links above take different routes to achieve similar results. The gist of it is that it is not easy to style InfoWindows directly, and it might be easier to use the additional InfoBubble class instead of InfoWindow, or to override GOverlay. Another option would be to modify the elements of the InfoWindow using javascript (or jQuery), like later ATOzTOA suggested.

Possibly the simplest of these examples is using InfoBubble instead of InfoWindow. InfoBubble is available by importing this file (which you should host yourself): http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js

InfoBubble's Github project page.

InfoBubble is very stylable, compared to InfoWindow:

 infoBubble = new InfoBubble({
      map: map,
      content: '<div class="mylabel">The label</div>',
      position: new google.maps.LatLng(-32.0, 149.0),
      shadowStyle: 1,
      padding: 0,
      backgroundColor: 'rgb(57,57,57)',
      borderRadius: 5,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 30,
      backgroundClassName: 'transparent',
      arrowStyle: 2
});

infoBubble.open();

You can also call it with a given map and marker to open on:

infoBubble.open(map, marker);

As another example, the Info Window Custom example extends the GOverlay class from the Google Maps API and uses this as a base for creating a more flexible info window. It first creates the class:

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -195;
  this.offsetHorizontal_ = 0;
  this.height_ = 165;
  this.width_ = 266;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

after which it proceeds to override GOverlay:

InfoBox.prototype = new google.maps.OverlayView();

You should then override the methods you need: createElement, draw, remove and panMap. It gets rather involved, but in theory you are just drawing a div on the map yourself now, instead of using a normal Info Window.

Concatenating string and integer in python

Let's assume you want to concatenate string and integer in a situation like this:

for i in range(1,11):
   string="string"+i 

and you are getting type or concatenation error

The best way to go about it is to do something like this:

for i in range(1,11):
   print("string",i)    

This will give you concatenated results like string 1, string 2, string 3 ...etc

Best way to determine user's locale within browser

Combining the multiple ways browsers are using to store the user's language, you get this function :

const getNavigatorLanguage = () => {
  if (navigator.languages && navigator.languages.length) {
    return navigator.languages[0];
  } else {
    return navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';
  }
}

We first check the navigator.languages array for its first element.
Then we get either navigator.userLanguage or navigator.language.
If this fails we get navigator.browserLanguage.
Finally, we set it to 'en' if everything else failed.


And here's the sexy one-liner :

const getNavigatorLanguage = () => (navigator.languages && navigator.languages.length) ? navigator.languages[0] : navigator.userLanguage || navigator.language || navigator.browserLanguage || 'en';

Create a symbolic link of directory in Ubuntu

In script is usefull something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

How to create a floating action button (FAB) in android, using AppCompat v21?

I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="#08000000"/>
                <padding
                    android:bottom="3px"
                    android:left="3px"
                    android:right="3px"
                    android:top="3px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#09000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#10000000"/>
                <padding
                    android:bottom="2px"
                    android:left="2px"
                    android:right="2px"
                    android:top="2px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#11000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#12000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#13000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#14000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#15000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#16000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
        <item>
            <shape android:shape="oval">
                <solid android:color="#17000000"/>
                <padding
                    android:bottom="1px"
                    android:left="1px"
                    android:right="1px"
                    android:top="1px"
                    />
            </shape>
        </item>
    </layer-list>
</item>
<item>
    <shape android:shape="oval">
        <solid android:color="?attr/colorPrimary"/>
    </shape>
</item>
</layer-list>

In place of ?attr/colorPrimary you can choose any color. Here's a screenshot of the result:

enter image description here

Build fails with "Command failed with a nonzero exit code"

I had files with the same name in different folders which caused this error.

How to delete a workspace in Eclipse?

I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.

Eclipse Neon - Remove Workspace

of course this won't remove the original files. It simply removes it from the list of suggested workspaces.

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

How do I use Safe Area Layout programmatically?

This extension helps you to constraint a UIVIew to its superview and superview+safeArea:

extension UIView {

    ///Constraints a view to its superview
    func constraintToSuperView() {
        guard let superview = superview else { return }
        translatesAutoresizingMaskIntoConstraints = false

        topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
        leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
        bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
        rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
    }

    ///Constraints a view to its superview safe area
    func constraintToSafeArea() {
        guard let superview = superview else { return }
        translatesAutoresizingMaskIntoConstraints = false

        topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor).isActive = true
        leftAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.leftAnchor).isActive = true
        bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor).isActive = true
        rightAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.rightAnchor).isActive = true
    }

}

Show and hide divs at a specific time interval using jQuery

Heres a another take on this problem, using recursion and without using mutable variables. Also, im not using setInterval so theres no cleanup that has to be done.

Having this HTML

<section id="testimonials">
    <h2>My testimonial spinner</h2>
    <div class="testimonial">
      <p>First content</p>
    </div>
    <div class="testimonial">
      <p>Second content</p>
    </div>
    <div class="testimonial">
       <p>Third content</p>
    </div>
</section>

Using ES2016

Here you call the function recursively and update the arguments.

  const testimonials = $('#testimonials')
      .children()
      .filter('div.testimonial');

  const showTestimonial = index => {

    testimonials.hide();
    $(testimonials[index]).fadeIn();

    return index === testimonials.length
      ? showTestimonial(0)
      : setTimeout(() => { showTestimonial(index + 1); }, 10000);
   }

showTestimonial(0); // id of the first element you want to show.

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

JSON parsing using Gson for Java

Firstly generate getter and setter using below parsing site

http://www.jsonschema2pojo.org/

Now use Gson

GettetSetterClass object=new Gson().fromjson(jsonLine, GettetSetterClass.class);

Now use object to get values such as data,translationText

Do the parentheses after the type name make a difference with new?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

The gotcha lies in-between:

struct Thingy {
  ~Thingy(); // No-longer a trivial class
  virtual WaxOn();
  int i;
};

The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

How does one sum only those rows in excel not filtered out?

If you aren't using an auto-filter (i.e. you have manually hidden rows), you will need to use the AGGREGATE function instead of SUBTOTAL.

Why is Visual Studio 2013 very slow?

I had similar problems when moving from Visual Studio 2012 → Visual Studio 2013. The IDE would lock up after almost every click or save, and building would take several times longer. None of the solutions listed here helped.

What finally did help was moving my projects to a local drive. Visual Studio 2012 had no problems storing my projects on a network share, but Visual Studio 2013 for some reason couldn't handle it.

How to compare two colors for similarity/difference

A simple method that only uses RGB is

cR=R1-R2 
cG=G1-G2 
cB=B1-B2 
uR=R1+R2 
distance=cR*cR*(2+uR/256) + cG*cG*4 + cB*cB*(2+(255-uR)/256)

I've used this one for a while now, and it works well enough for most purposes.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

Visualizing branch topology in Git

99.999% of my time is looking at history by git lg and the 0.001% is by git log.

I just want to share two log aliases that might be useful (configure from .gitconfig):

[Alias]
     lg = log --graph --pretty=format:'%Cred%h%Creset %ad %s %C(yellow)%d%Creset %C(bold blue)<%an>%Creset' --date=short
     hist = log --graph --full-history --all --pretty=format:'%Cred%h%Creset %ad %s %C(yellow)%d%Creset %C(bold blue)<%an>%Creset' --date=short
  • git lg will see the current branch history.
  • git hist will see the whole branch history.

How to use ArrayAdapter<myClass>

You could just add a toString() method to MyClass, per http://developer.android.com/reference/android/widget/ArrayAdapter.html:

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

class MyClass {

 @Override
 public String toString() {
  return "Hello, world.";
 }
}

gson throws MalformedJsonException

I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);

Nullable types: better way to check for null or zero in c#

You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

How to handle login pop up window using Selenium WebDriver?

Solution: Windows active directory authentication using Thread and Robot

I used Java Thread and Robot with Selenium webdriver to automate windows active directory authentication process of our website. This logic worked fine in Firefox and Chrome but it didn't work in IE. For some reason IE kills the webdriver when authentication window pops up whereas Chrome and Firefox prevents the web driver from getting killed. I didn't try in other web browser such as Safari.

//...
//Note: this logic works in Chrome and Firefox. It did not work in IE and I did not try Safari.
//...

//import relevant packages here

public class TestDemo {

    static WebDriver driver;

    public static void main(String[] args) {

        //setup web driver
        System.setProperty("webdriver.chrome.driver", "path to your chromedriver.exe");
        driver = new ChromeDriver();

        //create new thread for interaction with windows authentication window
        (new Thread(new LoginWindow())).start();                

        //open your url. this will prompt you for windows authentication
        driver.get("your url");

        //add test scripts below ...
        driver.findElement(By.linkText("Home")).click();    
        //.....
        //.....
    }

    //inner class for Login thread    
    public class LoginWindow implements Runnable {

        @Override
        public void run() {
            try {
                login();
            } catch (Exception ex) {
                System.out.println("Error in Login Thread: " + ex.getMessage());
            }
        }

        public void login() throws Exception {

            //wait - increase this wait period if required
            Thread.sleep(5000);

            //create robot for keyboard operations
            Robot rb = new Robot();

            //Enter user name by ctrl-v
            StringSelection username = new StringSelection("username");
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);            
            rb.keyPress(KeyEvent.VK_CONTROL);
            rb.keyPress(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_CONTROL);

            //tab to password entry field
            rb.keyPress(KeyEvent.VK_TAB);
            rb.keyRelease(KeyEvent.VK_TAB);
            Thread.sleep(2000);

            //Enter password by ctrl-v
            StringSelection pwd = new StringSelection("password");
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
            rb.keyPress(KeyEvent.VK_CONTROL);
            rb.keyPress(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_V);
            rb.keyRelease(KeyEvent.VK_CONTROL);

            //press enter
            rb.keyPress(KeyEvent.VK_ENTER);
            rb.keyRelease(KeyEvent.VK_ENTER);

            //wait
            Thread.sleep(5000);
        }                        
    }      
}

What is the difference between linear regression and logistic regression?

Cannot agree more with the above comments. Above that, there are some more differences like

In Linear Regression, residuals are assumed to be normally distributed. In Logistic Regression, residuals need to be independent but not normally distributed.

Linear Regression assumes that a constant change in the value of the explanatory variable results in constant change in the response variable. This assumption does not hold if the value of the response variable represents a probability (in Logistic Regression)

GLM(Generalized linear models) does not assume a linear relationship between dependent and independent variables. However, it assumes a linear relationship between link function and independent variables in logit model.

Connect multiple devices to one device via Bluetooth

Bluetooth 4.0 Allows you in a Bluetooth piconet one master can communicate up to 7 active slaves, there can be some other devices up to 248 devices which sleeping.

Also you can use some slaves as bridge to participate with more devices.

Send values from one form to another form

There are several solutions to this but this is the pattern I tend to use.

// Form 1
// inside the button click event
using(Form2 form2 = new Form2()) 
{
    if(form2.ShowDialog() == DialogResult.OK) 
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue 
{
    get { return someTextBoxOnForm2.Text; }
}

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

How to set the matplotlib figure default size in ipython notebook?

In iPython 3.0.0, the inline backend needs to be configured in ipython_kernel_config.py. You need to manually add the c.InlineBackend.rc... line (as mentioned in Greg's answer). This will affect both the inline backend in the Qt console and the notebook.

How to get distinct values for non-key column fields in Laravel?

For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7

A. Records in DB

UserFile::orderBy('created_at','desc')->get()->toArray();

Array
(
    [0] => Array
        (
            [id] => 2073
            [type] => 'DL'
            [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
            [created_at] => 2020-08-05 17:16:48
            [updated_at] => 2020-08-06 18:08:38
        )

    [1] => Array
        (
            [id] => 2074
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 17:20:06
            [updated_at] => 2020-08-06 18:08:38
        )

    [2] => Array
        (
            [id] => 2076
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 17:22:01
            [updated_at] => 2020-08-06 18:08:38
        )

    [3] => Array
        (
            [id] => 2086
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [created_at] => 2020-08-05 19:22:41
            [updated_at] => 2020-08-06 18:08:38
        )
)

B. Desired Grouped result

UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();

Array
(
    [0] => Array
        (
            [type] => 'DL'
            [url] => 'https://i.picsum.photos/12/884/200/300.jpg'
            [updated_at] => 2020-08-06 18:08:38 
        )

    [1] => Array
        (
            [type] => 'PROFILE'
            [url] => 'https://i.picsum.photos/13/884/200/300.jpg'
            [updated_at] => 2020-08-06 18:08:38
        )
)

So Pass only those columns in "select()", values of which are same. For example: 'type','url'. You can add more columns provided they have same value like 'updated_at'.

If you try to pass "created_at" or "id" in "select()", then you will get the records same as A. Because they are different for each row in DB.

Is there a good jQuery Drag-and-drop file upload plugin?

http://blueimp.github.com/jQuery-File-Upload/ = great solution

According to their docs, the following browsers support drag & drop:

  • Firefox 4+
  • Safari 5+
  • Google Chrome
  • Microsoft Internet Explorer 10.0+

expected assignment or function call: no-unused-expressions ReactJS

In my case it is happened due to curly braces of function if you use jsx then you need to change curly braces to Parentheses, see below code

const [countries] = useState(["USA", "UK", "BD"])

I tried this but not work, don't know why

 {countries.map((country) => {
        <MenuItem value={country}>{country}</MenuItem>
  })}

But when I change Curly Braces to parentheses and Its working fine for me

  {countries.map((country) => ( //Changes is here instead of {
        <MenuItem value={country}>{country}</MenuItem>
  ))} //and here instead of }
             

Hopefully it will help you too...

How to resolve the C:\fakepath?

You would be able to get at least temporary created copy of the file path on your machine. The only condition here is your input element should be within a form What you have to do else is putting in the form an attribute enctype, e.g.:

<form id="formid" enctype="multipart/form-data" method="post" action="{{url('/add_a_note' )}}">...</form>

enter image description here you can find the path string at the bottom. It opens stream to file and then deletes it.

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

Switch/toggle div (jQuery)

function toggling_fields_contact_bank(class_name) {
    jQuery("." + class_name).animate({
        height: 'toggle'
    });
}

How do you use "git --bare init" repository?

I'm adding this answer because after arriving here (with the same question), none of the answers really describe all the required steps needed to go from nothing to a fully usable remote (bare) repo.

Note: this example uses local paths for the location of the bare repo, but other git protocols (like SSH indicated by the OP) should work just fine.

I've tried to add some notes along the way for those less familiar with git.

1. Initialise the bare repo...

> git init --bare /path/to/bare/repo.git
Initialised empty Git repository in /path/to/bare/repo.git/

This creates a folder (repo.git) and populates it with git files representing a git repo. As it stands, this repo is useless - it has no commits and more importantly, no branches. Although you can clone this repo, you cannot pull from it.

Next, we need to create a working folder. There are a couple of ways of doing this, depending upon whether you have existing files.

2a. Create a new working folder (no existing files) by cloning the empty repo

git clone /path/to/bare/repo.git /path/to/work
Cloning into '/path/to/work'...
warning: You appear to have cloned an empty repository.
done.

This command will only work if /path/to/work does not exist or is an empty folder. Take note of the warning - at this stage, you still don't have anything useful. If you cd /path/to/work and run git status, you'll get something like:

On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)

but this is a lie. You are not really on branch master (because git branch returns nothing) and so far, there are no commits.

Next, copy/move/create some files in the working folder, add them to git and create the first commit.

> cd /path/to/work
> echo 123 > afile.txt
> git add .
> git config --local user.name adelphus
> git config --local user.email [email protected]
> git commit -m "added afile"
[master (root-commit) 614ab02] added afile
 1 file changed, 1 insertion(+)
 create mode 100644 afile.txt

The git config commands are only needed if you haven't already told git who you are. Note that if you now run git branch, you'll now see the master branch listed. Now run git status:

On branch master
Your branch is based on 'origin/master', but the upstream is gone.
  (use "git branch --unset-upstream" to fixup)

nothing to commit, working directory clean

This is also misleading - upstream has not "gone", it just hasn't been created yet and git branch --unset-upstream will not help. But that's OK, now that we have our first commit, we can push and master will be created on the bare repo.

> git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master

At this point, we have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

> git pull
Already up-to-date.
> git push origin master
Everything up-to-date

2b. Create a working folder from existing files If you already have a folder with files in it (so you cannot clone into it), you can initialise a new git repo, add a first commit and then link it to the bare repo afterwards.

> cd /path/to/work_with_stuff
> git init 
Initialised empty Git repository in /path/to/work_with_stuff
> git add .
# add git config stuff if needed
> git commit -m "added stuff"

[master (root-commit) 614ab02] added stuff
 20 files changed, 1431 insertions(+)
 create mode 100644 stuff.txt
...

At this point we have our first commit and a local master branch which we need to turn into a remote-tracked upstream branch.

> git remote add origin /path/to/bare/repo.git
> git push -u origin master
Counting objects: 31, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (31/31), done.
Writing objects: 100% (31/31), 43.23 KiB | 0 bytes/s, done.
Total 31 (delta 11), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

Note the -u flag on git push to set the (new) tracked upstream branch. Just as before, we now have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

All this may seem obvious to some, but git confuses me at the best of times (it's error and status messages really need some rework) - hopefully, this will help others.

Binding arrow keys in JS/jQuery

I came here looking for a simple way to let the user, when focused on an input, use the arrow keys to +1 or -1 a numeric input. I never found a good answer but made the following code that seems to work great - making this site-wide now.

$("input").bind('keydown', function (e) {
    if(e.keyCode == 40 && $.isNumeric($(this).val()) ) {
        $(this).val(parseFloat($(this).val())-1.0);
    } else if(e.keyCode == 38  && $.isNumeric($(this).val()) ) { 
        $(this).val(parseFloat($(this).val())+1.0);
    }
}); 

How to use If Statement in Where Clause in SQL?

SELECT *
  FROM Customer
 WHERE (I.IsClose=@ISClose OR @ISClose is NULL)  
   AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
   AND (isnull(@Value,1) <> 2
        OR I.RecurringCharge = @Total
        OR @Total is NULL )    
   AND (isnull(@Value,2) <> 3
        OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
        OR @Total is NULL )

Basically, your condition was

if (@Value=2)
   TEST FOR => (I.RecurringCharge=@Total  or @Total is NULL )    

flipped around,

AND (isnull(@Value,1) <> 2                -- A
        OR I.RecurringCharge = @Total    -- B
        OR @Total is NULL )              -- C

When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2, which is the original intention.

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

How do I get the title of the current active window using c#?

Loop over Application.Current.Windows[] and find the one with IsActive == true.

Move entire line up and down in Vim

This worked for me:

http://vim.wikia.com/wiki/Moving_lines_up_or_down_in_a_file

BTW, if you want to use ALT+some_key and your terminal (urxvt does this) refuses to comply, you should enter something like this in your .vimrc:

" For moving lines (^] is a special character; use <M-k> and <M-j> if it works)
nnoremap ^]k mz:m-2<CR>`z==
inoremap ^]j <Esc>:m+<CR>==gi
inoremap ^]k <Esc>:m-2<CR>==gi
vnoremap ^]j :m'>+<CR>gv=`<my`>mzgv`yo`z
nnoremap ^]j mz:m+<CR>`z==
vnoremap ^]k :m'<-2<CR>gv=`>my`<mzgv`yo`z

where ^] is a single character that represents the ALT key. To input that character, use C+v, Esc in Vim (C+q, Esc on Windows).

MongoDB/Mongoose querying at a specific date?

That should work if the dates you saved in the DB are without time (just year, month, day).

Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.

db.posts.find({ //query today up to tonight
    created_on: {
        $gte: new Date(2012, 7, 14), 
        $lt: new Date(2012, 7, 15)
    }
})

Sum the digits of a number

You can try this

def sumDigits(number):
    sum = 0
    while(number>0):
        lastdigit = number%10
        sum += lastdigit
        number = number//10

    return sum

How do you read from stdin?

When using -c command, as a tricky way, instead of reading the stdin (and more flexible in some cases) you can pass a shell script command as well to your python command by putting the shell command in quotes within a parenthesis started by $ sign.

e.g.

python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"

This will count the number of lines from goldendict's history file.

How to send POST request?

If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:

>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>> 

What's a clean way to stop mongod on Mac OS X?

This is an old question, but its one I found while searching as well.

If you installed with brew then the solution would actually be the this:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

Find all special characters in a column in SQL Server 2008

select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}

What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

How to recursively download a folder via FTP on Linux

You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:

wget -r ftp://user:[email protected]/

You can also use -m which is suitable for mirroring. It is currently equivalent to -r -N -l inf.

If you've some special characters in the credential details, you can specify the --user and --password arguments to get it to work. Example with custom login with specific characters:

wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/

As pointed out by @asmaier, watch out that even if -r is for recursion, it has a default max level of 5:

-r
--recursive
    Turn on recursive retrieving.

-l depth
--level=depth
    Specify recursion maximum depth level depth.  The default maximum depth is 5.

If you don't want to miss out subdirs, better use the mirroring option, -m:

-m
--mirror
    Turn on options suitable for mirroring.  This option turns on recursion and time-stamping, sets infinite
    recursion depth and keeps FTP directory listings.  It is currently equivalent to -r -N -l inf
    --no-remove-listing.

How to fetch JSON file in Angular 2

In Angular 5

you can just say

this.http.get<Example>('assets/example.json')

This will give you Observable<Example>

Call multiple functions onClick ReactJS

You can use nested.

There are tow function one is openTab() and another is closeMobileMenue(), Firstly we call openTab() and call another function inside closeMobileMenue().

function openTab() {
    window.open('https://play.google.com/store/apps/details?id=com.drishya');
    closeMobileMenue()   //After open new tab, Nav Menue will close.  
}

onClick={openTab}

How to terminate the script in JavaScript?

This little function comes pretty close to mimicking PHP's exit(). As with the other solutions, don't add anything else.

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit

Null check in an enhanced for loop

With Java 8 Optional:

for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
    // do whatever
}

How to trigger click on page load?

try this,

$("document").ready(function(){

$("your id here").trigger("click");
});

Javascript Array of Functions

It's basically the same as Darin Dimitrov's but it shows how you could use it do dynamically create and store functions and arguments. I hope it's useful for you :)

_x000D_
_x000D_
var argsContainer = ['hello', 'you', 'there'];_x000D_
var functionsContainer = [];_x000D_
_x000D_
for (var i = 0; i < argsContainer.length; i++) {_x000D_
var currentArg = argsContainer[i]; _x000D_
_x000D_
  functionsContainer.push(function(currentArg){_x000D_
    console.log(currentArg);_x000D_
  });_x000D_
};_x000D_
_x000D_
for (var i = 0; i < functionsContainer.length; i++) {_x000D_
  functionsContainer[i](argsContainer[i]);_x000D_
}
_x000D_
_x000D_
_x000D_

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

Options (Query Results/SQL Server/Results to Grid Page)

To change the options for the current queries, click Query Options on the Query menu, or right-click in the SQL Server Query window and select Query Options.

...

Maximum Characters Retrieved
Enter a number from 1 through 65535 to specify the maximum number of characters that will be displayed in each cell.

Maximum is, as you see, 64k. The default is much smaller.

BTW Results to Text has even more drastic limitation:

Maximum number of characters displayed in each column
This value defaults to 256. Increase this value to display larger result sets without truncation. The maximum value is 8,192.

How to stop PHP code execution?

You can use __halt_compiler function which will Halt the compiler execution

http://www.php.net/manual/en/function.halt-compiler.php

How to play .mp4 video in videoview in android?

In Kotlin you can do as

 val videoView = findViewById<VideoView>(R.id.videoView)

       // If url is from raw
   /* val url = "android.resource://" + packageName
        .toString() + "/" + R.raw.video*/

    // If url is from network
    val url = "http://www.servername.com/projects/projectname/videos/1361439400.mp4"

    val video =
        Uri.parse(url)
    videoView.setVideoURI(video)
    videoView.setOnPreparedListener{
        videoView.start()
    }

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

How can I show a hidden div when a select option is selected?

Check this code. It awesome code for hide div using select item.

HTML

<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
    <option value="1">YES</option>
    <option value="2">NO</option>
</select>

<div id="div1" style="display:block;">
    <input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
    <input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
    <input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
    <input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
    <datalist id="cars">
        <option>Value 1</option>
        <option>Value 2</option>
        <option>Value 3</option>
        <option>Value 4</option>
    </datalist>
</div>

JS

<script>
    function showDiv(prefix,chooser) 
    {
            for(var i=0;i<chooser.options.length;i++) 
            {
                var div = document.getElementById(prefix+chooser.options[i].value);
                div.style.display = 'none';
            }

            var selectedOption = (chooser.options[chooser.selectedIndex].value);

            if(selectedOption == "1")
            {
                displayDiv(prefix,"1");
            }
            if(selectedOption == "2")
            {
                displayDiv(prefix,"2");
            }
    }

    function displayDiv(prefix,suffix) 
    {
            var div = document.getElementById(prefix+suffix);
            div.style.display = 'block';
    }
</script>

Python error: AttributeError: 'module' object has no attribute

More accurately, your mod1 and lib directories are not modules, they are packages. The file mod11.py is a module.

Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.

>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12

An alternative is to use the from syntax to "pull" a module from a package into you scripts namespace.

>>> from lib.pkg1 import mod11

Then reference the function as simply mod11.mod12().

How to get PHP $_GET array?

You can get them using the Query String:

$idArray = explode('&',$_SERVER["QUERY_STRING"]);

This will give you:

$idArray[0] = "id=1";
$idArray[1] = "id=2";
$idArray[2] = "id=3";

Then

foreach ($idArray as $index => $avPair)
{
  list($ignore, $value) = explode("=", $avPair);
  $id[$index] = $value;
}

This will give you

$id[0] = "1";
$id[1] = "2";
$id[2] = "3";

How do I convert a Django QuerySet into list of dicts?

Use the .values() method:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

Note: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.

How do I do an OR filter in a Django query?

You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

How to debug Apache mod_rewrite

The LogRewrite directive as mentioned by Ben is not available anymore in Apache 2.4. You need to use the LogLevel directive instead. E.g.

LogLevel alert rewrite:trace6

See http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging

Can I use CASE statement in a JOIN condition?

Try this:

...JOIN sys.allocation_units a ON 
  (a.type=2 AND a.container_id = p.partition_id)
  OR (a.type IN (1, 3) AND a.container_id = p.hobt_id)

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

Babel 6 regeneratorRuntime is not defined

Alternatively, if you are not using a bundler like webpack or rollup, you could as a workaround just import the contents of https://raw.githubusercontent.com/facebook/regenerator/master/packages/regenerator-runtime/runtime.js using a plain old script tag in your index.html.

Not optimal, but in my case the only solution.

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

I've found many problems here, so I made my own.

Here it is in all it's glory, with tests:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^a-zA-Z\d\s])).{9,}$

https://regex101.com/r/DCRR65/4/tests

Things to look out for:

  1. doesn't use \w because that includes _, which I'm testing for.
  2. I've had lots of troubles matching symbols, without matching the end of the line.
  3. Doesn't specify symbols specifically, this is also because different locales may have different symbols on their keyboards that they may want to use.

How do I get currency exchange rates via an API such as Google Finance?

You can try geoplugin

Beside the geolocation done by IP (but the IP is the provider IP, so not so accurate), they return currencies also and have a currency converter: see examples.

They have 111 currencies updated.

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

How to remove array element in mongodb?

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

Make Iframe to fit 100% of container's remaining height

or you can go old-school and use a frameset perhaps:

<frameset rows="30,*">
  <frame src="banner.swf"/>
  <frame src="inner.html" />
</frameset>

How to backup Sql Database Programmatically in C#

You can use the following queries to Backup and Restore, you must change the path for your backup

Database name=[data]

Backup:

BACKUP DATABASE [data] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT,  NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

Restore:

RESTORE DATABASE [data] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
GO

FCM getting MismatchSenderId

THIS WORKED FOR ME:

  • CHECK WHICH FIREBASE PROJECT YOUR CURRENT ANDROID PROJECT IS LINKED TO AND USE Server Key FROM THAT PROJECT.

I was using Server key from a different firebase project(say Project 2). I used the same server key as linked with my android project(Say Project 1) and it worked. In my experience, using one firebase app for one entire android project seemed to fix the problem.

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

How to check if my string is equal to null?

Exception may also help:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

What are the main differences between JWT and OAuth authentication?

Jwt is a strict set of instructions for the issuing and validating of signed access tokens. The tokens contain claims that are used by an app to limit access to a user

OAuth2 on the other hand is not a protocol, its a delegated authorization framework. think very detailed guideline, for letting users and applications authorize specific permissions to other applications in both private and public settings. OpenID Connect which sits on top of OAUTH2 gives you Authentication and Authorization.it details how multiple different roles, users in your system, server side apps like an API, and clients such as websites or native mobile apps, can authenticate with each othe

Note oauth2 can work with jwt , flexible implementation, extandable to different applications