Programs & Examples On #Rsvg

psycopg2: insert multiple rows with one query

All of these techniques are called 'Extended Inserts" in Postgres terminology, and as of the 24th of November 2016, it's still a ton faster than psychopg2's executemany() and all the other methods listed in this thread (which i tried before coming to this answer).

Here's some code which doesnt use cur.mogrify and is nice and simply to get your head around:

valueSQL = [ '%s', '%s', '%s', ... ] # as many as you have columns.
sqlrows = []
rowsPerInsert = 3 # more means faster, but with diminishing returns..
for row in getSomeData:
        # row == [1, 'a', 'yolo', ... ]
        sqlrows += row
        if ( len(sqlrows)/len(valueSQL) ) % rowsPerInsert == 0:
                # sqlrows == [ 1, 'a', 'yolo', 2, 'b', 'swag', 3, 'c', 'selfie' ]
                insertSQL = 'INSERT INTO "twitter" VALUES ' + ','.join(['(' + ','.join(valueSQL) + ')']*rowsPerInsert)
                cur.execute(insertSQL, sqlrows)
                con.commit()
                sqlrows = []
insertSQL = 'INSERT INTO "twitter" VALUES ' + ','.join(['(' + ','.join(valueSQL) + ')']*len(sqlrows))
cur.execute(insertSQL, sqlrows)
con.commit()

But it should be noted that if you can use copy_from(), you should use copy_from ;)

How do you run a crontab in Cygwin on Windows?

Applied the instructions from this answer and it worked Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:

 cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
 set package_name=cygrunsrv cron
 setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%

Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...

Now in cmd promt:

 C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D   

or whatever full file path you might have to the cygrunsrv.exe and start the cron as windows service in the cmd prompt

 net start cron

Now in bash terminal run crontab -e

set up you cron entry an example bellow:

        #sync my gdrive each 10th minute
    */10 * * * * /home/Yordan/sync_gdrive.sh

    # * * * * * command to be executed
    # - - - - -
    # | | | | |
    # | | | | +- - - - day of week (0 - 6) (Sunday=0)
    # | | | +- - - - - month (1 - 12)
    # | | +- - - - - - day of month (1 - 31)
    # | +- - - - - - - hour (0 - 23)
    # +--------------- minute

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store   users.store
GET           /users/{user}               show    users.show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}

}

You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']
]);

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']
]);

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation


Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
    {
        // GET request to index
    }

    public function getShow($id)
    {
        // get request to 'users/show/{id}'
    }

    public function postStore()
    {
        // POST request to 'users/store'
    }

}

Implicit Controller documentation


It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

Is there a "goto" statement in bash?

If you are using it to skip part of a large script for debugging (see Karl Nicoll's comment), then if false could be a good option (not sure if "false" is always available, for me it is in /bin/false):

# ... Code I want to run here ...

if false; then

# ... Code I want to skip here ...

fi

# ... I want to resume here ...

The difficulty comes in when it's time to rip out your debugging code. The "if false" construct is pretty straightforward and memorable, but how do you find the matching fi? If your editor allows you to block indent, you could indent the skipped block (then you'll want to put it back when you're done). Or a comment on the fi line, but it would have to be something you'll remember, which I suspect will be very programmer-dependent.

add commas to a number in jQuery

Take a look at recently released Globalization plugin to jQuery by Microsoft

How to initialize a two-dimensional array in Python?

Here is an easier way :

import numpy as np
twoD = np.array([[]*m]*n)

For initializing all cells with any 'x' value use :

twoD = np.array([[x]*m]*n

How to get cookie expiration date / creation date from javascript?

you can't get the expiration date of a cookie through javascript because when you try to read the cookie from javascript the document.cookie return just the name and the value of the cookie as pairs

Mocking Extension Methods with Moq

I like to use the wrapper (adapter pattern) when I am wrapping the object itself. I'm not sure I'd use that for wrapping an extension method, which is not part of the object.

I use an internal Lazy Injectable Property of either type Action, Func, Predicate, or delegate and allow for injecting (swapping out) the method during a unit test.

    internal Func<IMyObject, string, object> DoWorkMethod
    {
        [ExcludeFromCodeCoverage]
        get { return _DoWorkMethod ?? (_DoWorkMethod = (obj, val) => { return obj.DoWork(val); }); }
        set { _DoWorkMethod = value; }
    } private Func<IMyObject, string, object> _DoWorkMethod;

Then you call the Func instead of the actual method.

    public object SomeFunction()
    {
        var val = "doesn't matter for this example";
        return DoWorkMethod.Invoke(MyObjectProperty, val);
    }

For a more complete example, check out http://www.rhyous.com/2016/08/11/unit-testing-calls-to-complex-extension-methods/

How to implement a FSM - Finite State Machine in Java

EasyFSM is a dynamic Java Library which can be used to implement an FSM.

You can find documentation for the same at : Finite State Machine in Java

Also, you can download the library at : Java FSM Library : DynamicEasyFSM

java.nio.file.Path for a classpath resource

You need to define the Filesystem to read resource from jar file as mentioned in https://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemprovider.html. I success to read resource from jar file with below codes:

Map<String, Object> env = new HashMap<>();
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {

        Path path = fs.getPath("/path/myResource");

        try (Stream<String> lines = Files.lines(path)) {
            ....
        }
    }

How do I add a new sourceset to Gradle?

I gather the documentation wasn't great back in 2012 when this question was asked, but for anyone reading this in 2020+: There's now a whole section in the docs about how to add a source set for integration tests. You really should read it instead of copy/pasting code snippets here and banging your head against the wall trying to figure out why an answer from 2012-2016 doesn't quite work.

The answer is most likely simple but more nuanced than you may think, and the exact code you'll need is likely to be different from the code I'll need. For example, do you want your integration tests to use the same dependencies as your unit tests?

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

How to add text inside the doughnut chart using Chart.js?

This is based on Cmyker's update for Chart.js 2. (posted as another answer as I can't comment yet)

I had an issue with the text alignment on Chrome when the legend is displayed as the chart height does not include this so it's not aligned correctly in the middle. Fixed this by accounting for this in the calculation of fontSize and textY.

I calculated percentage inside the method rather than a set value as I have multiple of these on the page. Assumptions are that your chart only has 2 values (otherwise what is the percentage of? and that the first is the one you want to show the percentage for. I have a bunch of other charts too so I do a check for type = doughnut. I'm only using doughnuts to show percentages so it works for me.

Text color seems a bit hit and miss depending on what order things run in etc so I ran into an issue when resizing that the text would change color (between black and the primary color in one case, and secondary color and white in another) so I "save" whatever the existing fill style was, draw the text (in the color of the primary data) then restore the old fill style. (Preserving the old fill style doesn't seem needed but you never know.)

https://jsfiddle.net/g733tj8h/

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx,
        type = chart.config.type;

    if (type == 'doughnut')
    {
      var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /
                    (chart.config.data.datasets[0].data[0] +
                    chart.config.data.datasets[0].data[1]));
      var oldFill = ctx.fillStyle;
      var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);

      ctx.restore();
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "middle"

      var text = percent + "%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = (height + chart.chartArea.top) / 2;

      ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];
      ctx.fillText(text, textX, textY);
      ctx.fillStyle = oldFill;
      ctx.save();
    }
  }
});

_x000D_
_x000D_
var data = {_x000D_
  labels: ["Red","Blue"],_x000D_
  datasets: [_x000D_
    {_x000D_
      data: [300, 50],_x000D_
      backgroundColor: ["#FF6384","#36A2EB"],_x000D_
    }]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
  beforeDraw: function(chart) {_x000D_
    var width = chart.chart.width,_x000D_
        height = chart.chart.height,_x000D_
        ctx = chart.chart.ctx,_x000D_
        type = chart.config.type;_x000D_
_x000D_
    if (type == 'doughnut')_x000D_
    {_x000D_
     var percent = Math.round((chart.config.data.datasets[0].data[0] * 100) /_x000D_
                    (chart.config.data.datasets[0].data[0] +_x000D_
                    chart.config.data.datasets[0].data[1]));_x000D_
   var oldFill = ctx.fillStyle;_x000D_
      var fontSize = ((height - chart.chartArea.top) / 100).toFixed(2);_x000D_
      _x000D_
      ctx.restore();_x000D_
      ctx.font = fontSize + "em sans-serif";_x000D_
      ctx.textBaseline = "middle"_x000D_
_x000D_
      var text = percent + "%",_x000D_
          textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
          textY = (height + chart.chartArea.top) / 2;_x000D_
   _x000D_
      ctx.fillStyle = chart.config.data.datasets[0].backgroundColor[0];_x000D_
      ctx.fillText(text, textX, textY);_x000D_
      ctx.fillStyle = oldFill;_x000D_
      ctx.save();_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
var myChart = new Chart(document.getElementById('myChart'), {_x000D_
  type: 'doughnut',_x000D_
  data: data,_x000D_
  options: {_x000D_
   responsive: true,_x000D_
    legend: {_x000D_
      display: true_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
_x000D_
_x000D_

Encode URL in JavaScript?

You have three options:

  • escape() will not encode: @*/+

  • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

  • encodeURIComponent() will not encode: ~!*()'

But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

What is the easiest way to install BLAS and LAPACK for scipy?

Either use SciPy whl, download the appropriate one and run pip install <whl_file>

OR

Read through SciPy Windows issue and run one of the methods.

OR

Use Miniconda.

Additionally, install Visual C++ compiler for python2.7 in-case it asks for it.

Please initialize the log4j system properly. While running web service

Well, if you had already created the log4j.properties you would add its path to the classpath so it would be found during execution.
Yes, the thingy will search for this file in the classpath.
Since you said you looked into axis and didnt find one, I am assuming you dont have a log4j.properties, so here's a crude but complete example.
Create it somewhere and add to your classpath. Put it for example, in c:/proj/resources/log4j.properties

In your classpath you simple add .......;c:/proj/resources

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=c:/project/resources/t-output/log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

ng-if check if array is empty

post.capabilities.items will still be defined because it's an empty array, if you check post.capabilities.items.length it should work fine because 0 is falsy.

How to hide a View programmatically?

Try this:

linearLayout.setVisibility(View.GONE);

Posting array from form

What you are doing is not necessarily bad practice but it does however require an extraordinary amount of typing. I would accomplish what you are trying to do like this.

foreach($_POST as $var => $val){
    $$var = $val;
}

This will take all the POST variables and put them in their own individual variables. So if you have a input field named email and the luser puts in [email protected] you will have a var named $email with a value of "[email protected]".

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

How to enable native resolution for apps on iPhone 6 and 6 Plus?

If you are using asset catalog, and have multiple targets both using same asset catalog file, be sure that this file has checked both targets in the right panel in xcode.

That was my problem.

enter image description here

How to get scrollbar position with Javascript?

Answer for 2018:

The best way to do things like that is to use the Intersection Observer API.

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. Unfortunately, as the web has matured, the need for this kind of information has grown. Intersection information is needed for many reasons, such as:

  • Lazy-loading of images or other content as a page is scrolled.
  • Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
  • Reporting of visibility of advertisements in order to calculate ad revenues.
  • Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

Implementing intersection detection in the past involved event handlers and loops calling methods like Element.getBoundingClientRect() to build up the needed information for every element affected. Since all this code runs on the main thread, even one of these can cause performance problems. When a site is loaded with these tests, things can get downright ugly.

See the following code example:

var options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

var target = document.querySelector('#listItem');
observer.observe(target);

Most modern browsers support the IntersectionObserver, but you should use the polyfill for backward-compatibility.

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

Java: Sending Multiple Parameters to Method

Suppose you have void method that prints many objects;

public static void print( Object... values){
   for(Object c : values){
      System.out.println(c);
   }
}

Above example I used vararge as an argument that accepts values from 0 to N.

From comments: What if 2 strings and 5 integers ??

Answer:

print("string1","string2",1,2,3,4,5);

How to delete from multiple tables in MySQL?

I don't have a mysql database to test on at the moment, but have you tried specifying what to delete prior to the from clause? For example:

DELETE p, pa FROM `pets` p,
        `pets_activities` pa
  WHERE p.`order` > :order
    AND p.`pet_id` = :pet_id
    AND pa.`id` = p.`pet_id`

I think the syntax you used is limited to newer versions of mysql.

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

Return multiple values from a function, sub or type?

I always approach returning more than one result from a function by always returning an ArrayList. By using an ArrayList I can return only one item, consisting of many multiple values, mixing between Strings and Integers.

Once I have the ArrayList returned in my main sub, I simply use ArrayList.Item(i).ToString where i is the index of the value I want to return from the ArrayList

An example:

 Public Function Set_Database_Path()
        Dim Result As ArrayList = New ArrayList
        Dim fd As OpenFileDialog = New OpenFileDialog()


        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.RestoreDirectory = True
        fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        fd.FilterIndex = 2
        fd.Multiselect = False


        If fd.ShowDialog() = DialogResult.OK Then

            Dim Database_Location = Path.GetFullPath(fd.FileName)

            Dim Database_Connection_Var = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & Database_Location & """"

            Result.Add(Database_Connection_Var)
            Result.Add(Database_Location)

            Return (Result)

        Else

            Return (Nothing)

        End If
    End Function

And then call the Function like this:

Private Sub Main_Load()
  Dim PathArray As ArrayList

            PathArray = Set_Database_Path()
            My.Settings.Database_Connection_String = PathArray.Item(0).ToString
            My.Settings.FilePath = PathArray.Item(1).ToString
            My.Settings.Save()
End Sub

CSS: styled a checkbox to look like a button, is there a hover?

Do this for a cool border and font effect:

#ck-button:hover {             /*ADD :hover */
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid red;      /*change border color*/ 
    overflow:auto;
    float:left;
    color:red;                 /*add font color*/
}

Example: http://jsfiddle.net/zAFND/6/

Use RSA private key to generate public key?

Use the following commands:

  1. openssl req -x509 -nodes -days 365 -sha256 -newkey rsa:2048 -keyout mycert.pem -out mycert.pem

     Loading 'screen' into random state - done
     Generating a 2048 bit RSA private key
     .............+++
     ..................................................................................................................................................................+++
     writing new private key to 'mycert.pem'
     -----
     You are about to be asked to enter information that will be incorporated
     into your certificate request.
     What you are about to enter is what is called a Distinguished Name or a DN.
     There are quite a few fields but you can leave some blank
     For some fields there will be a default value,
     If you enter '.', the field will be left blank.
    
  2. If you check there will be a file created by the name : mycert.pem

  3. openssl rsa -in mycert.pem -pubout > mykey.txt

    writing RSA key
    
  4. If you check the same file location a new public key mykey.txt has been created.

How to display multiple notifications in android

You just need to change your one-line from notificationManager.notify(0, notification); to notificationManager.notify((int) System.currentTimeMillis(), notification);...

This will change the id of notification whenever the new notification will appear

Add a row number to result set of a SQL query

The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):

SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
  FROM dbo.tableZ AS t
  ORDER BY t.A;

Not sure what the variables in your question are supposed to represent (they don't match).

How do I turn off Unicode in a VC++ project?

None of the above solutions worked for me. But

#include <Windows.h>

worked fine.

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

In your INSERT statements:

INSERT INTO employee(hans,germany) values(?,?)

You've got your values where your field names belong. Change it to be:

INSERT INTO employee(emp_name,emp_address) values(?,?)

If you were to run that statement from a SQL prompt, it would look like this:

INSERT INTO employee(emp_name,emp_address) values('hans','germany');

Note that you'd need to put single quotes around the string/varchar values.

Additionally, you are also not adding any parameters to your prepared statement. That is what's actually causing the error you're seeing. Try this:

PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.execute();

Also (according to Oracle), you can use "execute" for any SQL statement. Using "executeUpdate" would also be valid in this situation, which would return an integer to indicate the number of rows affected.

Add more than one parameter in Twig path

You can pass as many arguments as you want, separating them by commas:

{{ path('_files_manage', {project: project.id, user: user.id}) }}

How to create PDFs in an Android app?

PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

You don't need to uninstall WebDAV, just add these lines to the web.config:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Downgrading the version of Gradle worked for me:

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

How to count number of files in each directory?

find . -type f -printf '%h\n' | sort | uniq -c

gives for example:

  5 .
  4 ./aln
  5 ./aln/iq
  4 ./bs
  4 ./ft
  6 ./hot

iOS Simulator to test website on Mac

You can check and use their free trial browserstack , saucelabs or browser shots I know this is a very old question and I am answering too late and today there are many options available but may be someone get this usefull.

UICollectionView current visible cell index

Also check this snippet

let isCellVisible = collectionView.visibleCells.map { collectionView.indexPath(for: $0) }.contains(inspectingIndexPath)

What does -save-dev mean in npm install grunt --save-dev

Documentation from npm for npm install <package-name> --save and npm install <package-name> --save-dev can be found here:

https://docs.npmjs.com/getting-started/using-a-package.json#the-save-and-save-dev-install-flags

A package.json file declares metadata about the module you are developing. Both aforementioned commands modify this package.json file. --save will declare the installed package (in this case, grunt) as a dependency for your module; --save-dev will declare it as a dependency for development of your module.

Ask yourself: will the installed package be required for use of my module, or will it only be required for developing it?

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Is there a numpy builtin to reject outliers from a list

Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.

Building on eumiro's answer:

def reject_outliers(data, m = 2.):
    d = np.abs(data - np.median(data))
    mdev = np.median(d)
    s = d/mdev if mdev else 0.
    return data[s<m]

Here I have replace the mean with the more robust median and the standard deviation with the median absolute distance to the median. I then scaled the distances by their (again) median value so that m is on a reasonable relative scale.

Note that for the data[s<m] syntax to work, data must be a numpy array.

Modifying a query string without reloading the page

I've used the following JavaScript library with great success:

https://github.com/balupton/jquery-history

It supports the HTML5 history API as well as a fallback method (using #) for older browsers.

This library is essentially a polyfill around `history.pushState'.

How do you properly determine the current script directory?

Here is a partial solution, still better than all published ones so far.

import sys, os, os.path, inspect

#os.chdir("..")

if '__file__' not in locals():
    __file__ = inspect.getframeinfo(inspect.currentframe())[0]

print os.path.dirname(os.path.abspath(__file__))

Now this works will all calls but if someone use chdir() to change the current directory, this will also fail.

Notes:

  • sys.argv[0] is not going to work, will return -c if you execute the script with python -c "execfile('path-tester.py')"
  • I published a complete test at https://gist.github.com/1385555 and you are welcome to improve it.

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

Work with a time span in Javascript

a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat

some formatting examples

/** delta: 1234567890, @locale: 'en-US', @style: 'long' */

/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds

/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890

/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms

/* D,h:m:s.f */
14,06:56:07.890

/* D~, h:m:s.f */
14 days, 06:56:07.890

/* h~ m~ s~ */
342 hours 56 minutes 7 seconds

/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days

/* up D~, h:m */
up 14 days, 06:56

the code & test

_x000D_
_x000D_
/**
    Init locale formatter:
    
        timespan.locale(@locale, @style)
    
    Example:

        timespan.locale('en-US', 'long');
        timespan.locale('es', 'narrow');

    Format time delta:
    
        timespan.format(@pattern, @milliseconds)

        @pattern tokens:
            D: days, h: hours, m: minutes, s: seconds, f: millis

        @pattern token extension:
            h  => '0'-padded value, 
            h# => raw value,
            h~ => locale formatted value

    Example:

        timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
        
        output: 14 days 6 hours 56 minutes 7 seconds 890 millis

    NOTES:

    * milliseconds unit have no locale translation
    * may encounter declension issues for some locales
    * use quoted text for raw inserts
            
*/

const timespan = (() => {
    let rtf, tokensRtf;
    const
    tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
    map = [
        {t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
        {t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
        {t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
        {t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
        {t: [['f', 3], ['f#'], ['f~']], u: 1}
    ],
    locale = (value, style = 'long') => {
        try {
            rtf = new Intl.RelativeTimeFormat(value, {style});
        } catch (e) {
            if (rtf) throw e;
            return;
        }
        const h = rtf.format(1, 'hour').split(' ');
        tokensRtf = new Set(rtf.format(1, 'day').split(' ')
            .filter(t => t != 1 && h.indexOf(t) > -1));
        return true;
    },
    fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
    mapper = {
        number: (t, u) => (u + '').padStart(t.fmt, '0'),
        string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
            .filter(t => !tokensRtf.has(t)).join(' ')
            .trim().replace(/[+-]/g, '') : fallback(t, u),
    },
    replace = (out, t) => out[t] || t.slice(1, t.length - 1),
    format = (pattern, value) => {
        if (typeof pattern !== 'string')
            throw Error('invalid pattern');
        if (!Number.isFinite(value))
            throw Error('invalid value');
        if (!pattern)
            return '';
        const out = {};
        value = Math.abs(value);
        pattern.match(tokens)?.forEach(t => out[t] = null);
        map.forEach(m => {
            let u = null;
            m.t.forEach(t => {
                if (out[t.token] !== null)
                    return;
                if (u === null) {
                    u = Math.floor(value / m.u);
                    value %= m.u;
                }
                out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
            })
        });
        return pattern.replace(tokens, replace.bind(null, out));
    };
    map.forEach(m => m.t = m.t.map(t => ({
        token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
    })));
    locale('en');
    return {format, locale};
})();


/************************** test below *************************/

const
cfg = {
  locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
  style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
  try {
      const tv = new Date(td.value);
      if (isNaN(tv)) throw Error('invalid "datetime2" value');
      timespan.locale(loc.value || locale.value, style.value);
      const delta = fd.getTime() - tv.getTime();
      out.innerHTML = timespan.format(fmt.value, delta);
  } catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
  const elm = el(id);
  value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
_x000D_
_x000D_

Verify object attribute value with mockito

I think the easiest way for verifying an argument object is to use the refEq method:

Mockito.verify(mockedObject).someMethodOnMockedObject(ArgumentMatchers.refEq(objectToCompareWith));

It can be used even if the object doesn't implement equals(), because reflection is used. If you don't want to compare some fields, just add their names as arguments for refEq.

Scroll back to the top of scrollable div

For me the scrollTop way did not work, but I found other:

element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);

Did not check the minimum time for reliable css rendering though, 100ms might be overkill.

ECMAScript 6 class destructor

Is there such a thing as destructors for ECMAScript 6?

No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.

If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted

A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).

1): Well, there is a beginning with the specification of WeakMap and WeakSet objects. However, true weak references are still in the pipeline [1][2].

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Context envContext = (Context)initContext.lookup("java:comp/env");

not:Context envContext = (Context)initContext.lookup("java:/comp/env");

How to overwrite the output directory in spark

The documentation for the parameter spark.files.overwrite says this: "Whether to overwrite files added through SparkContext.addFile() when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.

You could do this before saving the file:

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }

Aas explained here: http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html

How to access form methods and controls from a class in C#?

You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.

If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.

Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg

public void DoSomethingWithText(string formText)
{
   // do something text in here
}

or exposing properties on your form class and setting the form text in there - eg

string SomeProperty
{
   get 
   {
      return textBox1.Text;
   }
   set
   {
      textBox1.Text = value;
   }
}

Error on renaming database in SQL Server 2008 R2

Try to close all connections to your database first:

use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]

ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER

Taken from here

Retrieving the last record in each group - MySQL

The below query will work fine as per your question.

SELECT M1.* 
FROM MESSAGES M1,
(
 SELECT SUBSTR(Others_data,1,2),MAX(Others_data) AS Max_Others_data
 FROM MESSAGES
 GROUP BY 1
) M2
WHERE M1.Others_data = M2.Max_Others_data
ORDER BY Others_data;

How can I get the domain name of my site within a Django template?

from django.contrib.sites.models import Site
if Site._meta.installed:
    site = Site.objects.get_current()
else:
    site = RequestSite(request)

Check if element is visible on screen

--- Shameless plug ---
I have added this function to a library I created vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------

Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.

If you don't use jQuery then the script would be something like this:

function posY(elm) {
    var test = elm, top = 0;

    while(!!test && test.tagName.toLowerCase() !== "body") {
        top += test.offsetTop;
        test = test.offsetParent;
    }

    return top;
}

function viewPortHeight() {
    var de = document.documentElement;

    if(!!window.innerWidth)
    { return window.innerHeight; }
    else if( de && !isNaN(de.clientHeight) )
    { return de.clientHeight; }
    
    return 0;
}

function scrollY() {
    if( window.pageYOffset ) { return window.pageYOffset; }
    return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible( elm ) {
    var vpH = viewPortHeight(), // Viewport Height
        st = scrollY(), // Scroll Top
        y = posY(elm);
    
    return (y > (vpH + st));
}

Using jQuery is a lot easier:

function checkVisible( elm, evalType ) {
    evalType = evalType || "visible";

    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elm).offset().top,
        elementHeight = $(elm).height();

    if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
    if (evalType === "above") return ((y < (vpH + st)));
}

This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.

See in action: http://jsfiddle.net/RJX5N/2/

I hope this answers your question.

-- IMPROVED VERSION--

This is a lot shorter and should do it as well:

function checkVisible(elm) {
  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}

with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/

And a version with threshold and mode included:

function checkVisible(elm, threshold, mode) {
  threshold = threshold || 0;
  mode = mode || 'visible';

  var rect = elm.getBoundingClientRect();
  var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
  var above = rect.bottom - threshold < 0;
  var below = rect.top - viewHeight + threshold >= 0;

  return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}

and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/

How to include a quote in a raw Python string

Use:

dqote='"'
sqote="'"

Use the '+' operator and dqote and squote variables to get what you need.

If I want sed -e s/",u'"/",'"/g -e s/^"u'"/"'"/, you can try the following:

dqote='"'
sqote="'"
cmd1="sed -e s/" + dqote + ",u'" + dqote + "/" + dqote + ",'" + dqote + '/g -e s/^"u' + sqote + dqote + '/' + dqote + sqote + dqote + '/'

How to pass a parameter to Vue @click event handler

I had the same issue and here is how I manage to pass through:

In your case you have addToCount() which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"

in your function implementation you can receive the params like:

addToCount(paramContactID){
 // the paramContactID contains the value you passed into the function when you called it
 // you can do what you want to do with the paramContactID in here!

}

Selecting specific rows and columns from NumPy array

As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.

>>> a[[0,1,3], :]            # Returns the rows you want
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]]  # Selects the columns you want as well
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

[Edit] The built-in method: np.ix_

I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

So you use it like this:

>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:

>>> np.ix_([0,1,3], [0,2])
(array([[0],
        [1],
        [3]]), array([[0, 2]]))

Also, as MikeC says in a comment, np.ix_ has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:

>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a    
array([[-1,  1, -1,  3],
       [-1,  5, -1,  7],
       [ 8,  9, 10, 11],
       [-1, 13, -1, 15],
       [16, 17, 18, 19]])

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

Endless loop in C/C++

They probably compile down to nearly the same machine code, so it is a matter of taste.

Personally, I would chose the one that is the clearest (i.e. very clear that it is supposed to be an infinite loop).

I would lean towards while(true){}.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

Detecting scroll direction

It can be detected by storing the previous scrollTop value and comparing the current scrollTop value with it.

JavaScript :

var lastScrollTop = 0;

// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
   var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
   if (st > lastScrollTop){
      // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);

Changing MongoDB data store directory

Here is what I did, hope it is helpful to anyone else :

Steps:

  1. Stop your services that are using mongodb
  2. Stop mongod - my way of doing this was with my rc file /etc/rc.d/rc.mongod stop, if you use something else, like systemd you should check your documentation how to do that
  3. Create a new directory on the fresh harddisk - mkdir /mnt/database
  4. Make sure that mongodb has privileges to read / write from that directory ( usually chown mongodb:mongodb -R /mnt/database/mongodb ) - thanks @DanailGabenski.
  5. Copy the data folder of your mongodb to the new location - cp -R /var/lib/mongodb/ /mnt/database/
  6. Remove the old database folder - rm -rf /var/lib/mongodb/
  7. Create symbolic link to the new database folder - ln -s /mnt/database/mongodb /var/lib/mongodb
  8. Start mongod - /etc/rc.d/rc.mongod start
  9. Check the log of your mongod and do some sanity checking ( try mongo to connect to your database to see if everything is all right )
  10. Start your services that you stopped in point 1

There is no need to tell that you should be careful when you do this, especialy with rm -rf but I think this is the best way to do it.

You should never try to copy database dir while mongod is running, because there might be services that write / read from it which will change the content of your database.

How to format DateTime columns in DataGridView?

You can set the format in aspx, just add the property "DateFormatString" in your BoundField.

DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

passing several arguments to FUN of lapply (and others *apply)

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}

x is a vector or a list and myfun in lapply(x, myfun) is called for each element of x separately.

Option 1

If you'd like to use whole arg1 in each myfun call (myfun(x[1], arg1), myfun(x[2], arg1) etc.), use lapply(x, myfun, arg1) (as stated above).

Option 2

If you'd however like to call myfun to each element of arg1 separately alongside elements of x (myfun(x[1], arg1[1]), myfun(x[2], arg1[2]) etc.), it's not possible to use lapply. Instead, use mapply(myfun, x, arg1) (as stated above) or apply:

 apply(cbind(x,arg1), 1, myfun)

or

 apply(rbind(x,arg1), 2, myfun).

VueJs get url query

Current route properties are present in this.$route, this.$router is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query

How to display count of notifications in app launcher icon

I have figured out how this is done for Sony devices.

I've blogged about it here. I've also posted a seperate SO question about this here.


Sony devices use a class named BadgeReciever.

  1. Declare the com.sonyericsson.home.permission.BROADCAST_BADGE permission in your manifest file:

  2. Broadcast an Intent to the BadgeReceiver:

    Intent intent = new Intent();
    
    intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", "com.yourdomain.yourapp.MainActivity");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", "99");
    intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", "com.yourdomain.yourapp");
    
    sendBroadcast(intent);
    
  3. Done. Once this Intent is broadcast the launcher should show a badge on your application icon.

  4. To remove the badge again, simply send a new broadcast, this time with SHOW_MESSAGE set to false:

    intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
    

I've excluded details on how I found this to keep the answer short, but it's all available in the blog. Might be an interesting read for someone.

Regular Expression for password validation

Thanks Nicholas Carey. I was going to use regex first but what you wrote changed my mind. It is so much easier to maintain this way.

//You can set these from your custom service methods
int minLen = 8;
int minDigit 2;
int minSpChar 2;

Boolean ErrorFlag = false;
//Check for password length
if (model.NewPassword.Length < minLen)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must be at least " + minLen + " characters long.");
}

//Check for Digits and Special Characters
int digitCount = 0;
int splCharCount = 0;
foreach (char c in model.NewPassword)
{
    if (char.IsDigit(c)) digitCount++;
    if (Regex.IsMatch(c.ToString(), @"[!#$%&'()*+,-.:;<=>?@[\\\]{}^_`|~]")) splCharCount++;
}

if (digitCount < minDigit)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must have at least " + minDigit + " digit(s).");
}
if (splCharCount < minSpChar)
{
    ErrorFlag = true;
    ModelState.AddModelError("NewPassword", "Password must have at least " + minSpChar + " special character(s).");
}

if (ErrorFlag)
    return View(model);

What special characters must be escaped in regular expressions?

Unfortunately there really isn't a set set of escape codes since it varies based on the language you are using.

However, keeping a page like the Regular Expression Tools Page or this Regular Expression Cheatsheet can go a long way to help you quickly filter things out.

When to use single quotes, double quotes, and backticks in MySQL

SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').

Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.

If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:

let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';

If ther's a where statement in your query and/or trying to insert a value and/or an update of value which is string use single quote(') for these values like:

let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";

//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error

let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';

//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.

If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:

let query = 'select is, name from accounts where name = \'John\'';

Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:

let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith

//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";

//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';

If need further clearance do follow quotes in JavaScript

Make a negative number positive

When you need to represent a value without the concept of a loss or absence (negative value), that is called "absolute value".


The logic to obtain the absolute value is very simple: "If it's positive, maintain it. If it's negative, negate it".


What this means is that your logic and code should work like the following:

//If value is negative...
if ( value < 0 ) {
  //...negate it (make it a negative negative-value, thus a positive value).
  value = negate(value);
}

There are 2 ways you can negate a value:

  1. By, well, negating it's value: value = (-value);
  2. By multiplying it by "100% negative", or "-1": value = value * (-1);

Both are actually two sides of the same coin. It's just that you usually don't remember that value = (-value); is actually value = 1 * (-value);.


Well, as for how you actually do it in Java, it's very simple, because Java already provides a function for that, in the Math class: value = Math.abs(value);

Yes, doing it without Math.abs() is just a line of code with very simple math, but why make your code look ugly? Just use Java's provided Math.abs() function! They provide it for a reason!

If you absolutely need to skip the function, you can use value = (value < 0) ? (-value) : value;, which is simply a more compact version of the code I mentioned in the logic (3rd) section, using the Ternary operator (? :).


Additionally, there might be situations where you want to always represent loss or absence within a function that might receive both positive and negative values.

Instead of doing some complicated check, you can simply get the absolute value, and negate it: negativeValue = (-Math.abs(value));


With that in mind, and considering a case with a sum of multiple numbers such as yours, it would be a nice idea to implement a function:

int getSumOfAllAbsolutes(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += Math.abs(values[i]);
  }
  return total;
}

Depending on the probability you might need related code again, it might also be a good idea to add them to your own "utils" library, splitting such functions into their core components first, and maintaining the final function simply as a nest of calls to the core components' now-split functions:

int[] makeAllAbsolute(int[] values){
  //@TIP: You can also make a reference-based version of this function, so that allocating 'absolutes[]' is not needed, thus optimizing.
  int[] absolutes = values.clone();
  for(int i=0; i<values.lenght; i++){
    absolutes[i] = Math.abs(values[i]);
  }
  return absolutes;
}

int getSumOfAllValues(int[] values){
  int total = 0;
  for(int i=0; i<values.lenght; i++){
    total += values[i];
  }
return total;
}

int getSumOfAllAbsolutes(int[] values){
  return getSumOfAllValues(makeAllAbsolute(values));
}

Running interactive commands in Paramiko

I'm not familiar with paramiko, but this may work:

ssh_stdin.write('input value')
ssh_stdin.flush()

For information on stdin:

http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin

How to create a bash script to check the SSH connection?

I feel like you're trying to solve the wrong problem here. Shouldn't you be trying to make the ssh daemons more stable? Try running something like monit, which will check to see if the daemon is running and restart it if it isn't (giving you time to find the root problem behind sshd shutting down on you). Or is the network service troublesome? Try looking at man ifup. Does the Whole Damn Thing just like to shut down on you? Well, that's a bigger problem ... try looking at your logs (start with syslog) to find hardware failures or services that are shutting your boxen down (maybe a temperature monitor?).

Making your scripts fault tolerant is great, but you might also want to make your boxen fault tolerant.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

Ajax Success and Error function failure

You can implement error-specific logic as follows:

error: function (XMLHttpRequest, textStatus, errorThrown) {
    if (textStatus == 'Unauthorized') {
        alert('custom message. Error: ' + errorThrown);
    } else {
        alert('custom message. Error: ' + errorThrown);
    }
}

create table with sequence.nextval in oracle

In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:

E.g.,

CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
  id          NUMBER DEFAULT t1_seq.NEXTVAL,
  description VARCHAR2(30)
);

How can I create an editable combo box in HTML/Javascript?

try doing this

<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2"  style="width: 140px;
    position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
        <div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
    onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
    top: 0px; left: 0px; z-index: 1; width: 165px;">
    <option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>
</select>

please look at following example fiddle

SQL grouping by all the columns

I wanted to do counts and sums over full resultset. I achieved grouping by all with GROUP BY 1=1.

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

Error: free(): invalid next size (fast):

I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it. So, if the same case, better allocate some memory using resize() and then access vector elements.

Exclude all transitive dependencies of a single dependency

Use the latest maven in your classpath.. It will remove the duplicate artifacts and keep the latest maven artifact..

Getting "Cannot call a class as a function" in my React Project

I had it when I did so :

function foo() (...) export default foo

correctly:

export default  () =>(...);

or

const foo = ...
export default foo

How do you create a UIImage View Programmatically - Swift

You can use above in one line.

  let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

This is a very simple solution, but it works for me:

_x000D_
_x000D_
<!--TEXT-AREA-->_x000D_
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>_x000D_
_x000D_
<!--JAVASCRIPT-->_x000D_
<script type="text/javascript">_x000D_
function setHeight(fieldId){_x000D_
    document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';_x000D_
}_x000D_
setHeight('textBox1');_x000D_
</script>
_x000D_
_x000D_
_x000D_

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Python-Requests close http connection

I think a more reliable way of closing a connection is to tell the sever explicitly to close it in a way compliant with HTTP specification:

HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example,

   Connection: close

in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' (section 8.1) after the current request/response is complete.

The Connection: close header is added to the actual request:

r = requests.post(url=url, data=body, headers={'Connection':'close'})

PHP __get and __set magic methods

From the PHP manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.

Installing Python 2.7 on Windows 8

there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables then add new path enter this in your variable path and values

enter image description here

Javascript communication between browser tabs/windows

Below window(w1) opens another window(w2). Any window can send/receive message to/from another window. So we should ideally verify that the message originated from the window(w2) we opened.

In w1

var w2 = window.open("abc.do");
window.addEventListener("message", function(event){
    console.log(event.data);
});

In w2(abc.do)

window.opener.postMessage("Hi! I'm w2", "*");

How can I get the count of line in a file in an efficient way?

The buffered reader is overkill

Reader r = new FileReader("f.txt");

int count = 0;
int nextchar = 0;
while (nextchar != -1){
        nextchar = r.read();
        if (nextchar == Character.getNumericValue('\n') ){
            count++;
        }
    }

My search for a simple example has createde one thats actually quite poor. calling read() repeadedly for a single character is less than optimal. see here for examples and measurements.

How to scan multiple paths using the @ComponentScan annotation?

You use ComponentScan to scan multiple packages using

@ComponentScan({"com.my.package.first","com.my.package.second"})

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

For me, I was accessing my XLS file from a network share. Moving the file for my connection manager to a local folder fixed the issue.

How to select a node of treeview programmatically in c#?

yourNode.Toggle(); //use that function on your node, it toggles it

How can I do a case insensitive string comparison?

You should use static String.Compare function like following

x => String.Compare (x.Username, (string)drUser["Username"],
                     StringComparison.OrdinalIgnoreCase) == 0

In Objective-C, how do I test the object type?

Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.

For the line below, we have some poorly formed data that can be an NSArray, an NSDictionary or (null).

NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];

These are the tests that were performed:

NSLog(@"%@", [hits class]);

if ([hits isMemberOfClass:[NSMutableArray class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isMemberOfClass:[NSArray class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isMemberOfClass:[NSDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSMutableDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSDictionary class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSArray class]]) {
    NSLog(@"%@", [hits class]);
}

if ([hits isKindOfClass:[NSMutableArray class]]) {
    NSLog(@"%@", [hits class]);
}

isKindOfClass worked rather well while isMemberOfClass didn't.

How to check if a Ruby object is a Boolean

As stated above there is no boolean class just TrueClass and FalseClass however you can use any object as the subject of if/unless and everything is true except instances of FalseClass and nil

Boolean tests return an instance of the FalseClass or TrueClass

(1 > 0).class #TrueClass

The following monkeypatch to Object will tell you whether something is an instance of TrueClass or FalseClass

class Object
  def boolean?
    self.is_a?(TrueClass) || self.is_a?(FalseClass) 
  end
end

Running some tests with irb gives the following results

?> "String".boolean?
=> false
>> 1.boolean?
=> false
>> Time.now.boolean?
=> false
>> nil.boolean?
=> false
>> true.boolean?
=> true
>> false.boolean?
=> true
>> (1 ==1).boolean?
=> true
>> (1 ==2).boolean?
=> true

What is mutex and semaphore in Java ? What is the main difference?

A semaphore is a counting synchronization mechanism, a mutex isn't.

How to parse this string in Java?

String s = "prefix/dir1/dir2/dir3/dir4"

String parts[] = s.split("/");

System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...

MySQL Insert into multiple tables? (Database normalization?)

try this

$sql= " INSERT INTO users (username, password) VALUES('test', 'test') ";
mysql_query($sql);
$user_id= mysql_insert_id();
if(!empty($user_id) {

$sql=INSERT INTO profiles (userid, bio, homepage) VALUES($user_id,'Hello world!', 'http://www.stackoverflow.com');
/* or 
 $sql=INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello   world!', 'http://www.stackoverflow.com'); */
 mysql_query($sql);
};

References
PHP
MYSQL

How-to turn off all SSL checks for postman for a specific site

enter image description here

This steps are used in spring boot with self signed ssl certificate implementation

if SSL turns off then HTTPS call will be worked as expected.

https://localhost:8443/test/hello

These are the steps we have to follow,

  1. Generate self signed ssl certificate
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

after key generation has done then copy that file in to the resource foder in your project

  1. add key store properties in applicaiton.properties
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
  1. change your postman ssl verification settings to turn OFF

now verify the url: https://localhost:8443/test/hello

Equivalent of jQuery .hide() to set visibility: hidden

There isn't one built in but you could write your own quite easily:

(function($) {
    $.fn.invisible = function() {
        return this.each(function() {
            $(this).css("visibility", "hidden");
        });
    };
    $.fn.visible = function() {
        return this.each(function() {
            $(this).css("visibility", "visible");
        });
    };
}(jQuery));

You can then call this like so:

$("#someElem").invisible();
$("#someOther").visible();

Here's a working example.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.

SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

How copy data from Excel to a table using Oracle SQL Developer

For PLSQL version 9.0.0.1601

  1. From the context menu of the Table, choose "Edit Data"
  2. Insert or edit the data
  3. Post change

How do you get the current page number of a ViewPager for Android?

If you only want the position, vp.getCurrentItem() will give it to you, no need to apply the onPageChangeListener() for that purpose alone.

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

Full width image with fixed height

<div id="container">
    <img style="width: 100%; height: 40%;" id="image" src="...">
</div>

I hope this will serve your purpose.

How to check if text fields are empty on form submit using jQuery?

A simple solution would be something like this

$( "form" ).on( "submit", function() { 

   var has_empty = false;

   $(this).find( 'input[type!="hidden"]' ).each(function () {

      if ( ! $(this).val() ) { has_empty = true; return false; }
   });

   if ( has_empty ) { return false; }
});

Note: The jQuery.on() method is only available in jQuery version 1.7+, but it is now the preferred method of attaching event handlers.

This code loops through all of the inputs in the form and prevents form submission by returning false if any of them have no value. Note that it doesn't display any kind of message to the user about why the form failed to submit (I would strongly recommend adding one).

Or, you could look at the jQuery validate plugin. It does this and a lot more.

NB: This type of technique should always be used in conjunction with server side validation.

Remove non-ASCII characters from CSV

A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>

-i says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak.

What is the { get; set; } syntax in C#?

It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):

private string name;
public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}

How to print GETDATE() in SQL Server with milliseconds in time?

If your SQL Server version supports the function FORMAT you could do it like this:

select format(getdate(), 'yyyy-MM-dd HH:mm:ss.fff')

What does "restore purchases" in In-App purchases mean?

You typically restore purchases with this code:

[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];

It will reinvoke -paymentQueue:updatedTransactions on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.

Not all types of In-App purchases can be restored.

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

When managing the actual files, things can get out of sync pretty easily unless you're really vigilant. So we've launched a (beta) free service called String which allows you to keep track of your language files easily, and collaborate with translators.

You can either import existing language files (in PHP array, PHP Define, ini, po or .strings formats) or create your own sections from scratch and add content directly through the system.

String is totally free so please check it out and tell us what you think.

It's actually built on Codeigniter too! Check out the beta at http://mygengo.com/string

MySQL, Concatenate two columns

In query, CONCAT_WS() function.

This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).

Syntax –

CONCAT_WS( SEPERATOR, column1, column2, ... )

Example

SELECT 
topic, 
CONCAT_WS( " ", subject, year ) AS subject_year 
FROM table

Easiest way to split a string on newlines in .NET?

Try to avoid using string.Split for a general solution, because you'll use more memory everywhere you use the function -- the original string, and the split copy, both in memory. Trust me that this can be one hell of a problem when you start to scale -- run a 32-bit batch-processing app processing 100MB documents, and you'll crap out at eight concurrent threads. Not that I've been there before...

Instead, use an iterator like this;

    public static IEnumerable<string> SplitToLines(this string input)
    {
        if (input == null)
        {
            yield break;
        }

        using (System.IO.StringReader reader = new System.IO.StringReader(input))
        {
            string line;
            while( (line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

This will allow you to do a more memory efficient loop around your data;

foreach(var line in document.SplitToLines()) 
{
    // one line at a time...
}

Of course, if you want it all in memory, you can do this;

var allTheLines = document.SplitToLines.ToArray();

Run a PostgreSQL .sql file using command line arguments

If you are logged in into psql on the Linux shell the command is:

\i fileName.sql

for an absolute path and

\ir filename.sql

for the relative path from where you have called psql.

How to copy and edit files in Android shell?

I tried following on mac.

  1. Launch Terminal and move to folder where adb is located. On Mac, usually at /Library/Android/sdk/platform-tools.
  2. Connect device now with developer mode on and check device status with command ./adb status. "./" is to be prefixed with "adb".
  3. Now we may need know destination folder location in our device. You can check this with adb shell. Use command ./adb shell to enter an adb shell. Now we have access to device's folder using shell.
  4. You may list out all folders using command ls -la.
  5. Usually we find a folder /sdcard within our device.(You can choose any folder here.) Suppose my destination is /sdcard/3233-3453/DCIM/Videos and source is ~/Documents/Videos/film.mp4
  6. Now we can exit adb shell to access filesystem on our machine. Command: ./adb exit
  7. Now ./adb push [source location] [destination location]
    i.e. ./adb push ~/Documents/Videos/film.mp4 /sdcard/3233-3453/DCIM/Videos
  8. Voila.

Google access token expiration time

Since there is no accepted answer I will try to answer this one:

[s] - seconds

Laravel Request getting current path with query string

public functin func_name(Request $request){$reqOutput = $request->getRequestUri();}

Convert a Pandas DataFrame to a dictionary

Try to use Zip

df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d

Output:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

Mac OS X and multiple Java versions

For macOS Sierra 420

This guide was cobbled together from various sources (replies above as well as other posts), and works perfect.

0. If you haven't already, install homebrew.

See https://brew.sh/

1. Install jenv

brew install jenv

2. Add jenv to the bash profile

if which jenv > /dev/null; then eval "$(jenv init -)"; fi

3. Add jenv to your path

export PATH="$HOME/.jenv/shims:$PATH"

4. Tap "caskroom/versions"

FYI: "Tap" extends brew's list of available repos it can install, above and beyond brew's default list of available repos.

brew tap caskroom/versions

5. Install the latest version of java

brew cask install java

6. Install java 6 (or 7 or 8 whatever you need)

brew cask install java6
#brew cask install java7
#brew cask install java8

? Maybe close and restart Terminal so it sees any new ENV vars that got setup.

7. Review Installations

All Java version get installed here: /Library/Java/JavaVirtualMachines lets take a look.

ls -la /Library/Java/JavaVirtualMachines

8. Add each path to jenv one-at-a-time.

We need to add "/Contents/Home" to the version folder. WARNING: Use the actual paths on your machine... these are just EXAMPLE's

jenv add /Library/Java/JavaVirtualMachines/1.6.0___EXAMPLE___/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk___EXAMPLE___/Contents/Home

9. Check if jenv registered OK

jenv versions

10. Set java version to use (globably)

Where XX matches one of the items in the versions list above.

jenv global XX

Check java version

java -version

Check jenv versions

Should also indicate the current version being used with an asterisk.

jenv versions

DONE


Quick future reference

To change java versions

... See the list of available java versions

jenv versions

... then, where XX matches an item in the list above

jenv global XX

How can I get the SQL of a PreparedStatement?

To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.

Take a look at log4jdbc

How to output in CLI during execution of PHP Unit tests?

I had to modify source code for this code to work so you need to add URL for this forked repos to composer for this will work

class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     *  Save last response
     * @var Response|null A Response instance
     */
    static $lastResponse;
    /**
     *  Modify to save response
     *
     * @param  string $method
     * @param  string $uri
     * @param  array $parameters
     * @param  array $files
     * @param  array $server
     * @param  string $content
     * @param  bool $changeHistory
     * @return \Illuminate\Http\Response
     */
    final public function call(
        $method,
        $uri,
        $parameters = [],
        $files = [],
        $server = [],
        $content = null,
        $changeHistory = true
    ) {

        $response = parent::call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
        static::$lastResponse = $this->client->getResponse();
        return $response;
    }


    /**
     * Modify message to add response text
     *
     * @param mixed $value
     * @param PHPUnit_Framework_Constraint $constraint
     * @param string $message
     * @since  Method available since Release 3.0.0
     */
    final public static function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '')
    {
        $message .= PHP_EOL . static::$lastResponse . PHP_EOL;
        parent::assertThat($value, $constraint, $message);
    }
}

How to create a data file for gnuplot?

Create your Datafile like this:

# X      Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45

And plot it with

$ gnuplot -p -e "plot 'filename.dat'"

There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/

System.drawing namespace not found under console application

  1. Add using System.Drawing;
  2. Go to solution explorer and right click on references and select add reference
  3. Click on assemblies on the left
  4. search for system.drawing
  5. check system.drawing
  6. Click OK
  7. Done

Showing an image from console in Python

Or simply execute the image through the shell, as in

import subprocess
subprocess.call([ fname ], shell=True)

and whatever program is installed to handle images will be launched.

How to check if ping responded or not in a batch file

I know this is an old thread, but I wanted to test if a machine was up on my system and unless I have misunderstood, none of the above works if my router reports that an address is unreachable. I am using a batch file rather than a script because I wanted to "KISS" on pretty much any WIN machine. So the approach I used was to do more than one ping and test for "Lost = 0" as follows

ping -n 2 %pingAddr% | find /I "Lost = 0"  
if %errorlevel% == 0 goto OK

I haven't tested this rigorously but so far it does the job for me

Convert Dictionary<string,string> to semicolon separated string in c#

Another option is to use the Aggregate extension rather than Join:

String s = myDict.Select(x => x.Key + "=" + x.Value).Aggregate((s1, s2) => s1 + ";" + s2);

ORACLE and TRIGGERS (inserted, updated, deleted)

From Using Triggers:

Detecting the DML Operation That Fired a Trigger

If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

So

IF DELETING THEN ... END IF;

should work for your case.

React JS Error: is not defined react/jsx-no-undef

Here you have not specified class name to be imported from Map.js file. If Map is class exportable class name exist in the Map.js file, your code should be as follow.

import React, { Component } from 'react';
import Map from  './Map';
class App extends Component {
   render() {
     return (
         <div className="App">
            <Map/>
         </div>
     );
   }
}
export default App;

How to change the color of a CheckBox?

You can change checkbox color using singe line of code

android:buttonTint="@color/app_color" //whatever color

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

Get file version in PowerShell

This is based on the other answers, but is exactly what I was after:

(Get-Command C:\Path\YourFile.Dll).FileVersionInfo.FileVersion

Simple Deadlock Examples

I found that a bit hard to understand when reading the dining philosophers' problem, deadlock IMHO is actually related to resource allocation. Would like to share a more simple example where 2 Nurse need to fight for 3 equipment in order to complete a task. Although it's written in java. A simple lock() method is created to simulate how the deadlock happen, so it can apply in other programming language as well. http://www.justexample.com/wp/example-of-deadlock/

How to pass a JSON array as a parameter in URL

let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');

jquery $.each() for objects

$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

Aggregate function in SQL WHERE-Clause

Another solution is to Move the aggregate fuction to Scalar User Defined Function

Create Your Function:

CREATE FUNCTION getTotalSalesByProduct(@ProductName VARCHAR(500))
RETURNS INT
AS
BEGIN

DECLARE @TotalAmount INT

SET @TotalAmount = (select SUM(SaleAmount) FROM Sales where Product=@ProductName)

RETURN @TotalAmount

END

Use Function in Where Clause

SELECT ProductName, SUM(SaleAmount) AS TotalSales
FROM Sales
WHERE dbo.getTotalSalesByProduct(ProductName)  > 1000
GROUP BY Product

References:

1. 2.

Hope helps someone.

Is there a decent wait function in C++?

the equivalent to the batch program would be

#include<iostream>
int main()
{
    std::cout<<"Hello, World!\n";
    std::cin.get();
    return 0;
}

The additional line does exactly what PAUSE does, waits for a single character input

New lines (\r\n) are not working in email body

Another thing use "", there is a difference between "\r\n" and '\r\n'.

TortoiseGit save user authentication / credentials

For TortoiseGit 1.8.1.2 or later, there is a GUI to switch on/off credential helper.

It supports git-credential-wincred and git-credential-winstore.

TortoiseGit 1.8.16 add support for git-credential-manager (Git Credential Manager, the successor of git-credential-winstore)

For the first time you sync you are asked for user and password, you enter them and they will be saved to Windows credential store. It won't ask for user or password the next time you sync.

To use: Right click → TortoiseGit → Settings → Git → Credential. Select Credential helper: wincred - this repository only / wincred - current Windows user

enter image description here

MySQL: How to copy rows, but change a few fields?

If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;

SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO

UPDATE #TEMP
SET Column = "Changed"
GO

INSERT INTO Table
SELECT *
FROM #Temp

ngOnInit not being called when Injectable class is Instantiated

Lifecycle hooks, like OnInit() work with Directives and Components. They do not work with other types, like a service in your case. From docs:

A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.

What does the ^ (XOR) operator do?

One thing that other answers don't mention here is XOR with negative numbers -

 a  |  b  | a ^ b
----|-----|------
 0  |  0  |  0
 0  |  1  |  1
 1  |  0  |  1
 1  |  1  |  0

While you could easily understand how XOR will work using the above functional table, it doesn't tell how it will work on negative numbers.


How XOR works with Negative Numbers :

Since this question is also tagged as python, I will be answering it with that in mind. The XOR ( ^ ) is an logical operator that will return 1 when the bits are different and 0 elsewhere.

A negative number is stored in binary as two's complement. In 2's complement, The leftmost bit position is reserved for the sign of the value (positive or negative) and doesn't contribute towards the value of number.

In, Python, negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your two's-complement numbers, then you treat patterns from 00000000 to 01111111 as the whole numbers from 0 to 127, and reserve 1xxxxxxx for writing negative numbers.

With that in mind, lets understand how XOR works on negative number with an example. Lets consider the expression - ( -5 ^ -3 ) .

  • The binary representation of -5 can be considered as 1000...101 and
  • Binary representation of -3 can be considered as 1000...011.

Here, ... denotes all 0s, the number of which depends on bits used for representation (32-bit, 64-bit, etc). The 1 at the MSB ( Most Significant Bit ) denotes that the number represented by the binary representation is negative. The XOR operation will be done on all bits as usual.

XOR Operation :

      -5   :  10000101          |
     ^                          | 
      -3   :  10000011          |  
    ===================         |
    Result :  00000110  =  6    |
________________________________|


     ? -5 ^ -3 = 6

Since, the MSB becomes 0 after the XOR operation, so the resultant number we get is a positive number. Similarly, for all negative numbers, we consider their representation in binary format using 2's complement (one of most commonly used) and do simple XOR on their binary representation.

The MSB bit of result will denote the sign and the rest of the bits will denote the value of the final result.

The following table could be useful in determining the sign of result.

  a   |   b   | a ^ b
------|-------|------
  +   |   +   |   +
  +   |   -   |   -
  -   |   +   |   -
  -   |   -   |   +

The basic rules of XOR remains same for negative XOR operations as well, but how the operation really works in negative numbers could be useful for someone someday .

Mocking methods of local scope objects with Mockito

You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest.

package hello.easymock.constructor;

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
    
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
        
    @Test
    public void testMockFile() throws Exception {

        // first, create a mock for File
        final File fileMock = EasyMock.createMock(File.class);
        EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
        EasyMock.replay(fileMock);

        // then return the mocked object if the constructor is invoked
        Class<?>[] parameterTypes = new Class[] { String.class };
        PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
        PowerMock.replay(File.class); 
    
        // try constructing a real File and check if the mock kicked in
        final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
        Assert.assertEquals("/my/fake/file/path", mockedFilePath);
    }
}

How to show changed file name only with git log?

If you need just file names like:

dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php

(which I use as a source for tar command) you will also need to filter out commit messages.

In order to do this I use following command:

git log --name-only --oneline | grep -v '.{7} '

Grep command excludes (-v param) every line which starts with seven symbols (which is the length of my git hash for git log command) followed by space. So it filters out every git hash message line and leave only lines with file names.

One useful improvement is to append uniq to remove duplicate lines so it will looks as follow:

git log --name-only --oneline | grep -v '.{7} ' | uniq

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

I will add my experience using saga in production system in addition to the library author's rather thorough answer.

Pro (using saga):

  • Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.

  • redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.

  • Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.

Con:

  • Generator syntax.

  • Lots of concepts to learn.

  • API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.

Get first word of string

var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');

//Now i want to get the first word of every split-ed sting parts:

for (var i=0;i<str1.length;i++)
{
    //What to do here to get the first word :)
    var firstWord = str1[i].split(' ')[0];
    alert(firstWord);
}

How to set opacity in parent div and not affect in child div?

May be it's good if you define your background-image in the :after pseudo class. Write like this:

.parent{
    width:300px;
    height:300px;
    position:relative;
    border:1px solid red;
}
.parent:after{
    content:'';
    background:url('http://www.dummyimage.com/300x300/000/fff&text=parent+image');
    width:300px;
    height:300px;
    position:absolute;
    top:0;
    left:0;
    opacity:0.5;
}
.child{
    background:yellow;
    position:relative;
    z-index:1;
}

Check this fiddle

Parsing boolean values with argparse

Simplest way would be to use choices:

parser = argparse.ArgumentParser()
parser.add_argument('--my-flag',choices=('True','False'))

args = parser.parse_args()
flag = args.my_flag == 'True'
print(flag)

Not passing --my-flag evaluates to False. The required=True option could be added if you always want the user to explicitly specify a choice.

how to check for null with a ng-if values in a view with angularjs?

You should check for !test, here is a fiddle showing that.

<span ng-if="!test">null</span>

How to add a custom button to the toolbar that calls a JavaScript function?

This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal

There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

Convert Iterable to Stream using Java 8 JDK

You can easily create a Stream out of an Iterable or Iterator:

public static <T> Stream<T> stream(Iterable<T> iterable) {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(
            iterable.iterator(),
            Spliterator.ORDERED
        ),
        false
    );
}

How do I escape a percentage sign in T-SQL?

Use brackets. So to look for 75%

WHERE MyCol LIKE '%75[%]%'

This is simpler than ESCAPE and common to most RDBMSes.

How to temporarily disable a click handler in jQuery?

I just barely ran into this problem when trying to display a loading spinner while I waited for a function to complete. Because I was appending the spinner into the HTML, the spinner would be duplicated each time the button was clicked, if you're not against defining a variable on the global scale, then this worked well for me.

    var hasCardButtonBeenClicked = '';
    $(".js-mela-card-button").on("click", function(){  
        if(!hasCardButtonBeenClicked){
            hasCardButtonBeenClicked = true;
            $(this).append('<i class="fa fa-circle-o-notch fa-spin" style="margin-left: 3px; font-size: 15px;" aria-hidden="true"></i>');
        }    
    });

Notice, all I'm doing is declaring a variable, and as long as its value is null, the actions following the click will occur and then subsequently set the variables value to "true" (it could be any value, as long as it's not empty), further disabling the button until the browser is refreshed or the variable is set to null.

Looking back it probably would have made more sense to just set the hasCardButtonBeenClicked variable to "false" to begin with, and then alternate between "true" and "false" as needed.

Inline JavaScript onclick function

Based on the answer that @Mukund Kumar gave here's a version that passes the event argument to the anonymous function:

<a href="#" onClick="(function(e){
    console.log(e);
    alert('Hey i am calling');
    return false;
})(arguments[0]);return false;">click here</a>

How to post object and List using postman

I also had a similar question, sharing the below example if it helps.

My Controller:

@RequestMapping(value = {"/batchDeleteIndex"}, method = RequestMethod.POST)
@ResponseBody
public BaseResponse batchDeleteIndex(@RequestBody List<String> datasetQnames)

Postman: Set the Body type to raw and add header Content-Type: application/json

["aaa","bbb","ccc"]

Can you delete multiple branches in one command with Git?

You might like this little item... It pulls the list and asks for confirmation of each item before finally deleting all selections...

git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "remove branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done`

Use -D to force deletions (like usual).

For readability, here is that broken up line by line...

git branch -d `git for-each-ref --format="%(refname:short)" refs/heads/\* |
    while read -r line; do 
        read -p "remove branch: $line (y/N)?" answer </dev/tty;
        case "$answer" in y|Y) echo "$line";; 
        esac; 
    done`

here is the xargs approach...

git for-each-ref --format="%(refname:short)" refs/heads/\* |
while read -r line; do 
    read -p "remove branch: $line (y/N)?" answer </dev/tty;
    case "$answer" in 
        y|Y) echo "$line";; 
    esac; 
done | xargs git branch -D

finally, I like to have this in my .bashrc

alias gitselect='git for-each-ref --format="%(refname:short)" refs/heads/\* | while read -r line; do read -p "select branch: $line (y/N)?" answer </dev/tty; case "$answer" in y|Y) echo "$line";; esac; done'

That way I can just say

gitSelect | xargs git branch -D.

How do you get the Git repository's name in some Git repository?

In general, you cannot do this. Git does not care how your git repository is named. For example, you can rename directory containing your repository (one with .git subdirectory), and git will not even notice it - everything will continue to work.

However, if you cloned it, you can use command:

git remote show origin

to display a lot of information about original remote that you cloned your repository from, and it will contain original clone URL.

If, however, you removed link to original remote using git remote rm origin, or if you created that repository using git init, such information is simply impossible to obtain - it does not exist anywhere.

dotnet ef not found in .NET Core 3

For everyone using .NET Core CLI on MinGW MSYS. After installing using

dotnet tool install --global dotnet-ef

add this line to to bashrc file c:\msys64\home\username\ .bashrc (location depend on your setup)

export PATH=$PATH:/c/Users/username/.dotnet/tools

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

The provider is bundled with PowerShell>=6.0.

If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.

Java string to date conversion

Also, SimpleDateFormat is not available with some of the client-side technologies, like GWT.

It's a good idea to go for Calendar.getInstance(), and your requirement is to compare two dates; go for long date.

How do I convert a PDF document to a preview image in PHP?

Think differently, You can use the following library to convert pdf to image using javascript

http://usefulangle.com/post/24/pdf-to-jpeg-png-with-pdfjs

Best way to access a control on another form in Windows Forms?

Do your child forms really need to be Forms? Could they be user controls instead? This way, they could easily raise events for the main form to handle and you could better encapsulate their logic into a single class (at least, logically, they are after all classes already).

@Lars: You are right here. This was something I did in my very beginning days and have not had to do it since, that is why I first suggested raising an event, but my other method would really break any semblance of encapsulation.

@Rob: Yup, sounds about right :). 0/2 on this one...

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

What happens if you don't commit a transaction to a database (say, SQL Server)?

Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.

Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).

How do I set a textbox's text to bold at run time?

 txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
 //Font(Font Name,Font Size,Font.Style)

Copy files from one directory into an existing directory

For inside some directory, this will be use full as it copy all contents from "folder1" to new directory "folder2" inside some directory.

$(pwd) will get path for current directory.

Notice the dot (.) after folder1 to get all contents inside folder1

cp -r $(pwd)/folder1/. $(pwd)/folder2

Disable vertical sync for glxgears

If you're using the NVIDIA closed-source drivers you can vary the vertical sync mode on the fly using the __GL_SYNC_TO_VBLANK environment variable:

~$ __GL_SYNC_TO_VBLANK=1 glxgears
Running synchronized to the vertical refresh.  The framerate should be
approximately the same as the monitor refresh rate.
299 frames in 5.0 seconds = 59.631 FPS

~$ __GL_SYNC_TO_VBLANK=0 glxgears
123259 frames in 5.0 seconds = 24651.678 FPS

This works for me on Ubuntu 14.04 using the 346.46 NVIDIA drivers.

Place a button right aligned

In my case the

<p align="right"/>

worked fine

How to Find the Default Charset/Encoding in Java?

Is this a bug or feature?

Looks like undefined behaviour. I know that, in practice, you can change the default encoding using a command-line property, but I don't think what happens when you do this is defined.

Bug ID: 4153515 on problems setting this property:

This is not a bug. The "file.encoding" property is not required by the J2SE platform specification; it's an internal detail of Sun's implementations and should not be examined or modified by user code. It's also intended to be read-only; it's technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

The preferred way to change the default encoding used by the VM and the runtime system is to change the locale of the underlying platform before starting your Java program.

I cringe when I see people setting the encoding on the command line - you don't know what code that is going to affect.

If you do not want to use the default encoding, set the encoding you do want explicitly via the appropriate method/constructor.

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

For this error in macOS Catalina and macOS Big Sur use this line:

php -d memory_limit=-1 /usr/local/bin/composer update --no-plugins

I used this line to update on Symfony 5. This command also worked with laravel 7.

Use String.split() with multiple delimiters

It's better to use something like this:

s.split("[\\s\\-\\.\\'\\?\\,\\_\\@]+");

Have added a few other characters as sample. This is the safest way to use, because the way . and ' is treated.

If "0" then leave the cell blank

An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.

=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Column/Vertical selection with Keyboard in SublimeText 3

Commenting just so people can have a solution to the intended question.

You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.

In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.

The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.

When to use 'raise NotImplementedError'?

Consider if instead it was:

class RectangularRoom(object):
    def __init__(self, width, height):
        pass

    def cleanTileAtPosition(self, pos):
        pass

    def isTileCleaned(self, m, n):
        pass

and you subclass and forget to tell it how to isTileCleaned() or, perhaps more likely, typo it as isTileCLeaned(). Then in your code, you'll get a None when you call it.

  • Will you get the overridden function you wanted? Definitely not.
  • Is None valid output? Who knows.
  • Is that intended behavior? Almost certainly not.
  • Will you get an error? It depends.

raise NotImplmentedError forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.

Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).

ng-mouseover and leave to toggle item using mouse in angularjs

I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)

<ul ng-repeat="task in tasks">
    <li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
    <span ng-show="hoverEdit"><a>Edit</a></span>
</ul>

How to parse JSON using Node.js?

NodeJs is a JavaScript based server, so you can do the way you do that in pure JavaScript...

Imagine you have this Json in NodeJs...

var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);

And you can do above to get a parsed version of your json...

How to make the background DIV only transparent using CSS

background-image:url('image/img2.jpg'); 
background-repeat:repeat-x;

Use some image for internal image and use this.

How to len(generator())

The conversion to list that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:

sum(1 for x in generator)

Of course, be aware that this might be slower than len(list(generator)) in common Python implementations, and if the generators are long enough for the memory complexity to matter, the operation would take quite some time. Still, I personally prefer this solution as it describes what I want to get, and it doesn't give me anything extra that's not required (such as a list of all the elements).

Also listen to delnan's advice: If you're discarding the output of the generator it is very likely that there is a way to calculate the number of elements without running it, or by counting them in another manner.

How to get param from url in angular 4?

constructor(private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
    this.activatedRoute.params.subscribe(paramsId => {
        this.id = paramsId.id;
        console.log(this.id);
    });
  
 }

List all tables in postgresql information_schema

For listing your tables use:

SELECT table_name FROM information_schema.tables WHERE table_schema='public'

It will only list tables that you create.

How to force an entire layout View refresh?

This is how i used to Refresh my layout

Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);

What is [Serializable] and when should I use it?

What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field.

See MSDN for more details.

Edit 1

Any reason to not mark something as serializable

When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.

PHP is not recognized as an internal or external command in command prompt

Extra info:

If you are using PhpStorm as IDE, after updating the path variable you need to restart PhpStorm so that it takes effect.

Restarting terminal window was not enough for me. (PhpStorm 2020.3.2)

Insert images to XML file

Here's some code taken from Kirk Evans Blog that demonstrates how to encode an image in C#;

//Load the picture from a file
Image picture = Image.FromFile(@"c:\temp\test.gif");

//Create an in-memory stream to hold the picture's bytes
System.IO.MemoryStream pictureAsStream = new System.IO.MemoryStream();
picture.Save(pictureAsStream, System.Drawing.Imaging.ImageFormat.Gif);

//Rewind the stream back to the beginning
pictureAsStream.Position = 0;
//Get the stream as an array of bytes
byte[] pictureAsBytes = pictureAsStream.ToArray();

//Create an XmlTextWriter to write the XML somewhere... here, I just chose
//to stream out to the Console output stream
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Console.Out);

//Write the root element of the XML document and the base64 encoded data
writer.WriteStartElement("w", "binData",
                         "http://schemas.microsoft.com/office/word/2003/wordml");

writer.WriteBase64(pictureAsBytes, 0, pictureAsBytes.Length);

writer.WriteEndElement();
writer.Flush();

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

Before you start merging MVC and Web API projects I would suggest to read about cons and pros to separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.

IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.

To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.

So, be aware.

How do you get a timestamp in JavaScript?

Here is another solution to generate a timestamp in JavaScript - including a padding method for single numbers - using day, month, year, hour, minute and seconds in its result (working example at jsfiddle):

var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();

    timestamp.day = [
        pad(timestamp.getDate()),
        pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
        timestamp.getFullYear()
    ];

    timestamp.time = [
        pad(timestamp.getHours()),
        pad(timestamp.getMinutes()),
        pad(timestamp.getSeconds())
    ];

timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);