Programs & Examples On #Session scope

A state of the Java bean that holds it during HTTP session.

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

https://stackoverflow.com/a/30640097/2569475

For This Issue check My answer at above given url

Using a request scoped bean outside of an actual web request

Check if registry key exists using VBScript

edit (sorry I thought you wanted VBA).

Anytime you try to read a non-existent value from the registry, you get back a Null. Thus all you have to do is check for a Null value.

Use IsNull not IsEmpty.

Const HKEY_LOCAL_MACHINE = &H80000002

strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & _ 
    strComputer & "\root\default:StdRegProv")

strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "Test Value"
objRegistry.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue

If IsNull(strValue) Then
    Wscript.Echo "The registry key does not exist."
Else
    Wscript.Echo "The registry key exists."
End If

Apply CSS Style to child elements

As far as I know this:

div[class=yourclass] table {  your style here; } 

or in your case even this:

div.yourclass table { your style here; }

(but this will work for elements with yourclass that might not be divs) will affect only tables inside yourclass. And, as Ken says, the > is not supported everywhere (and div[class=yourclass] too, so use the point notation for classes).

How to resolve 'unrecognized selector sent to instance'?

A lot of people have given some very technical answers for this and similar questions, but I think it's simpler than that. Sometimes if you're not paying attention a selector that you don't intend to use can be attached to something in the interface. You might be getting this error because the selector's there but you haven't written any code for it.

The easiest way to double-check that this is not the case is to control-click the item so you can see all of the selectors that are associated with it. If there's anything in there that you don't want to be, get rid of it! Hope this helps...

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

I had the same problem just with switching the background images with reasonable sizes. I got better results with setting the ImageView to null before putting in a new picture.

ImageView ivBg = (ImageView) findViewById(R.id.main_backgroundImage);
ivBg.setImageDrawable(null);
ivBg.setImageDrawable(getResources().getDrawable(R.drawable.new_picture));

Spring MVC - HttpMediaTypeNotAcceptableException

As Alex hinted in one of the answers, you could use the ContentNegotiationManagerFactoryBean to set the default content-type to "application/json", but I felt that that approach was not for me.

What I was trying to do was to post a form to a method like this

@RequestMapping(value = "/post/to/me", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public @ResponseBody MyJsonPOJO handlePostForm(@Valid @ModelAttribute("form") ValidateMeForm form, BindingResult bindingResult) throws ApiException {

What I instead chose to do was to change the "Accept" header of the request from the browser to "application/json", thereby making SpringMVC find my method.

Using the (not yet finalized) Javascript Fetch API:

var form = new FormData();
form.append("myData", "data");

let fetchConfig = {
    method: "POST",
    body: form,
    headers: {"Accept": "application/json"}
};

fetch("/post/to/me", fetchConfig)
    .then(... // Javascript Promise API here

Et voilà! Now SpringMVC finds the method, validates the form, and lets you return a JSON POJO.

What is the difference between a "function" and a "procedure"?

Basic Differences

  • A Function must return a value but in Stored Procedures it is optional: a procedure can return 0 or n values.
  • Functions can have only input parameters for it, whereas procedures can have input/output parameters.
  • For a Function it is mandatory to take one input parameter, but a Stored Procedure may take 0 to n input parameters.
  • Functions can be called from a Procedure whereas Procedures cannot be called from a Function.

Advanced Differences

  • Exceptions can be handled by try-catch blocks in a Procedure, whereas a try-catch block cannot be used in a Function.
  • We can go for Transaction Management in a Procedure, whereas in a Function we can't.

In SQL:

  • A Procedure allows SELECT as well as DML (INSERT, UPDATE, DELETE) statements in it, whereas Function allows only SELECT statement in it.
  • Procedures can not be utilized in a SELECT statement, whereas Functions can be embedded in a SELECT statement.
  • Stored Procedures cannot be used in SQL statements anywhere in a WHERE (or a HAVING or a SELECT) block, whereas Functions can.
  • Functions that return tables can be treated as another Rowset. This can be used in a JOIN block with other tables.
  • Inline Functions can be thought of as views that take parameters and can be used in JOIN blocks and other Rowset operations.

How do you get a query string on Flask?

from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')

How to Merge Two Eloquent Collections?

The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following

$original = new Collection(['foo']);

$latest = new Collection(['bar']);

$merged = $original->merge($latest); // Contains foo and bar.

Applying the example to your code

$related = new Collection();

foreach ($question->tags as $tag)
{
    $related = $related->merge($tag->questions);
}

A html space is showing as %2520 instead of %20

The following code snippet resolved my issue. Thought this might be useful to others.

_x000D_
_x000D_
var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");
_x000D_
_x000D_
_x000D_

Rather using default encodeURIComponent my first line of code is converting all spaces into hyphens using regex pattern /\s\g and the following line just does the reverse, i.e. converts all hyphens back to spaces using another regex pattern /-/g. Here /g is actually responsible for finding all matching characters.

When I am sending this value to my Ajax call, it traverses as normal spaces or simply %20 and thus gets rid of double-encoding.

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

you can just do as you get that elements value

document.getElementById('numquest').value='';

Is there a way to add/remove several classes in one single instruction with classList?

The new spread operator makes it even easier to apply multiple CSS classes as array:

const list = ['first', 'second', 'third'];
element.classList.add(...list);

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

And yet another option: https://github.com/apptik/jus

  • It is modular like Volley, but more extended and documentation is improving, supporting different HTTP stacks and converters out of the box
  • It has a module to generate server API interface mappings like Retrofit
  • It also has JavaRx support

And many other handy features like markers, transformers, etc.

How to resize the jQuery DatePicker control

I change the following line in ui.theme.css:

.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 1.1em; }

to:

.ui-widget { font-family: Trebuchet MS, Tahoma, Verdana, Arial, sans-serif; font-size: 12px; }

Best way to remove an event handler in jQuery?

This can be done by using the unbind function.

$('#myimage').unbind('click');

You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones.

There are several strategies for changing event handlers, such as event namespaces. There are some pages about this in the online docs.

Look at this question (that's how I learned of unbind). There is some useful description of these strategies in the answers.

How to read bound hover callback functions in jquery

SQL Server error on update command - "A severe error occurred on the current command"

In my case, I was using System.Threading.CancellationTokenSource to cancel a SqlCommand but not handling the exception with catch (SqlException) { }

How do I schedule jobs in Jenkins?

*/5 * * * * means every 5 minutes

5 * * * * means the 5th minute of every hour

Save Screen (program) output to a file

There is a command line option for logging. The output is saved to screenlog.n file, where n is a number of the screen. From man pages of screen:

‘-L’ Tell screen to turn on automatic output logging for the windows.

Get source JARs from Maven repository

In eclipse - click on the project then:

enter image description here.

How do I download a binary file over HTTP?

if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile

require 'pull_tempfile'

PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
  CSV.foreach(tmp_file.path) do |row|
    # ....
  end
end

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

Can I have multiple Xcode versions installed?

It's easy to have multiple Xcode installs.

In the installer there's a pulldown for the location... you just need to pick a new location when you're installing the beta version.

These instructions from an Apple dev tools evangelist have the full details (Apple dev username/password required): https://devforums.apple.com/message/40847#40847

Then grab yourself a custom icon for the Beta version of XCode you're using, so you can tell them apart in the dock: http://iphonedevelopment.blogspot.com/2009/03/multiple-developer-tool-installs.html

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Forge's SHA-256 implementation is fast and reliable.

To run tests on several SHA-256 JavaScript implementations, go to http://brillout.github.io/test-javascript-hash-implementations/.

The results on my machine suggests forge to be the fastest implementation and also considerably faster than the Stanford Javascript Crypto Library (sjcl) mentioned in the accepted answer.

Forge is 256 KB big, but extracting the SHA-256 related code reduces the size to 4.5 KB, see https://github.com/brillout/forge-sha256

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

How do you deploy Angular apps?

To Deploy your application in IIS follow the below steps.

Step 1: Build your Angular application using command ng build --prod

Step 2: After build all files are stored in dist folder of your application path.

Step 3: Create a folder in C:\inetpub\wwwroot by name QRCode.

Step 4: Copy the contents of dist folder to C:\inetpub\wwwroot\QRCode folder.

Step 5: Open IIS Manager using command (Window + R) and type inetmgr click OK.

Step 6: Right click on Default Web Site and click on Add Application.

Step 7: Enter Alias name 'QRCode' and set the physical path to C:\inetpub\wwwroot\QRCode.

Step 8: Open index.html file and find the line href="\" and remove '\'.

Step 9: Now browse application in any browser.

You can also follow the video for better understanding.

Video url: https://youtu.be/F8EI-8XUNZc

Adding a column to an existing table in a Rails migration

When I've done this, rather than fiddling the original migration, I create a new one with just the add column in the up section and a drop column in the down section.

You can change the original and rerun it if you migrate down between, but in this case I think that's made a migration that won't work properly.

As currently posted, you're adding the column and then creating the table.

If you change the order it might work. Or, as you're modifying an existing migration, just add it to the create table instead of doing a separate add column.

How to apply a function to two columns of Pandas dataframe

A interesting question! my answer as below:

import pandas as pd

def sublst(row):
    return lst[row['J1']:row['J2']]

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(sublst,axis=1)
print df

Output:

  ID  J1  J2
0  1   0   1
1  2   2   4
2  3   3   5
  ID  J1  J2      J3
0  1   0   1     [a]
1  2   2   4  [c, d]
2  3   3   5  [d, e]

I changed the column name to ID,J1,J2,J3 to ensure ID < J1 < J2 < J3, so the column display in right sequence.

One more brief version:

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(lambda row:lst[row['J1']:row['J2']],axis=1)
print df

ORA-00060: deadlock detected while waiting for resource

You can get deadlocks on more than just row locks, e.g. see this. The scripts may be competing for other resources, such as index blocks.

I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like MOD(n,10), I'd use TRUNC(n/10) which mean that each slave worked on a contiguous set of data.

There are, of course, much better ways of splitting up a job for parallelism, e.g. DBMS_PARALLEL_EXECUTE.

Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?

C# binary literals

You can use 0b000001 since Visual Studio 2017 (C# 7.0)

CSS table td width - fixed, not flexible

Chrome 37. for non fixed table:

td {
    width: 30px;
    max-width: 30px;
    overflow: hidden;
}

first two important! else - its flow away!

How do you install Boost on MacOS?

In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:

sudo port install boost +universal

How do I set specific environment variables when debugging in Visual Studio?

You can set it at Property > Configuration Properties > Debugging > Environment enter image description here

Case insensitive regular expression without re.compile?

#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string. 
#'re.search' returns location of the where the match is found 
#'re.compile' creates a regex object that can be used for multiple matches

 >>> s = r'TeSt'   
 >>> print (re.match(s, r'test123', re.I))
 <_sre.SRE_Match object; span=(0, 4), match='test'>
 # OR
 >>> pattern = re.compile(s, re.I)
 >>> print(pattern.match(r'test123'))
 <_sre.SRE_Match object; span=(0, 4), match='test'>

Get a list of all functions and procedures in an Oracle database

SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')

The column STATUS tells you whether the object is VALID or INVALID. If it is invalid, you have to try a recompile, ORACLE can't tell you if it will work before.

Getting activity from context in android

From your Activity, just pass in this as the Context for your layout:

ProfileView pv = new ProfileView(this, null, temp, tempPd);

Afterwards you will have a Context in the layout, but you will know it is actually your Activity and you can cast it so that you have what you need:

Activity activity = (Activity) context;

How to convert List to Json in Java

Use GSON library for that. Here is the sample code

List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");

String json = new Gson().toJson(foo );

Here is the maven dependency for Gson

<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.2</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

Or you can directly download jar from here and put it in your class path

http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=

To send Json to client you can use spring or in simple servlet add this code

response.getWriter().write(json);

Java 8: Difference between two LocalDateTime in multiple units

TL;DR

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

and then use the methods period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart().


Expanded answer

I'll answer the original question, i.e. how to get the time difference between two LocalDateTimes in years, months, days, hours & minutes, such that the "sum" (see note below) of all the values for the different units equals the total temporal difference, and such that the value in each unit is smaller than the next bigger unit—i.e. minutes < 60, hours < 24, and so on.

Given two LocalDateTimes start and end, e.g.

LocalDateTime start = LocalDateTime.of(2019, 11, 29, 17, 15);
LocalDateTime end = LocalDateTime.of(2020, 11, 30, 18, 44);

we can represent the absolute timespan between the two with a Duration—perhaps using Duration.between(start, end). But the biggest unit we can extract out of a Duration is days (as a temporal unit equivalent to 24h)—see the note below for an explanation. To use larger units (months, years) we can represent this Duration with a pair of (Period, Duration), where the Period measures the difference up to a precision of days and the Duration represents the remainder:

Duration duration = Duration.between(start, end);
duration = duration.minusDays(duration.toDaysPart()); // essentially "duration (mod 1 day)"
Period period = Period.between(start.toLocalDate(), end.toLocalDate());

Now we can simply use the methods defined on Period and Duration to extract the individual units:

System.out.printf("%d years, %d months, %d days, %d hours, %d minutes, %d seconds",
        period.getYears(), period.getMonths(), period.getDays(), duration.toHoursPart(),
        duration.toMinutesPart(), duration.toSecondsPart());
1 years, 0 months, 1 days, 1 hours, 29 minutes, 0 seconds

or, using the default format:

System.out.println(period + " + " + duration);
P1Y1D + PT1H29M

Note on years, months & days

Note that, in java.time's conception, "units" like "month" or "year" don't represent a fixed, absolute temporal value—they're date- and calendar-dependent, as the following example illustrates:

LocalDateTime
        start1 = LocalDateTime.of(2020, 1, 1, 0, 0),
        end1 = LocalDateTime.of(2021, 1, 1, 0, 0),
        start2 = LocalDateTime.of(2021, 1, 1, 0, 0),
        end2 = LocalDateTime.of(2022, 1, 1, 0, 0);
System.out.println(Period.between(start1.toLocalDate(), end1.toLocalDate()));
System.out.println(Duration.between(start1, end1).toDays());
System.out.println(Period.between(start2.toLocalDate(), end2.toLocalDate()));
System.out.println(Duration.between(start2, end2).toDays());
P1Y
366
P1Y
365

Doctrine 2 ArrayCollection filter method

The Collection#filter method really does eager load all members. Filtering at the SQL level will be added in doctrine 2.3.

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Create a new Ruby on Rails application using MySQL instead of SQLite

database.yml

# MySQL. Versions 5.1.10 and up are supported.
#
# Install the MySQL driver
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem 'mysql2'
#
# And be sure to use new-style password hashing:
#   https://dev.mysql.com/doc/refman/5.7/en/password-hashing.html
#
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: localhost
  database: database_name
  username: username
  password: secret

development:
  <<: *default

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default

# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
#   DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
#   production:
#     url: <%= ENV['DATABASE_URL'] %>
#
production:
  <<: *default

Gemfile:

# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4', '< 0.6.0'

Is it fine to have foreign key as primary key?

Yes, a foreign key can be a primary key in the case of one to one relationship between those tables

Finding the position of the max element

Or, written in one line:

std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

The answers are provided here amazing, but if you are new in that and you don't realize full error then you may see at the end of that error net/http: TLS handshake timeout. message means that you have a slow internet connection. So it can be only that problem that's it. Toodles

how to convert 2d list to 2d numpy array?

just use following code

c = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix([[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]])

Then it will give you

you can check shape and dimension of matrix by using following code

c.shape

c.ndim

Is there a way to collapse all code blocks in Eclipse?

Right click on the +/- sign and click collapse all or expand all.

How can I exclude a directory from Visual Studio Code "Explore" tab?

In version 1.28 of Visual Studio Code "files.exclude" must be placed within a settings node.

Resulting in a workspace file that looks like:

{
    "settings": {
        "files.exclude": {
            "**/node_modules": true
        }
    }
}

How to generate gcc debug symbol outside the build target?

Compile with debug information:

gcc -g -o main main.c

Separate the debug information:

objcopy --only-keep-debug main main.debug

or

cp main main.debug
strip --only-keep-debug main.debug

Strip debug information from origin file:

objcopy --strip-debug main

or

strip --strip-debug --strip-unneeded main

debug by debuglink mode:

objcopy --add-gnu-debuglink main.debug main
gdb main

You can also use exec file and symbol file separatly:

gdb -s main.debug -e main

or

gdb
(gdb) exec-file main
(gdb) symbol-file main.debug

For details:

(gdb) help exec-file
(gdb) help symbol-file

Ref:
https://sourceware.org/gdb/onlinedocs/gdb/Files.html#Files https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html

R: Plotting a 3D surface from x, y, z

You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.

The variables "b" and "s" could be x or y.

require(lattice)

# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape


wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
    light.source = c(10,10,10), main = "Study 1",
    scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
    screen = list(z = 40, x = -75, y = 0))

PHP ini file_get_contents external url

Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

echo get_content('http://example.com');

How to convert date in to yyyy-MM-dd Format?

Use this.

java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);

you will get the output as

2012-12-01

Angular: conditional class with *ngClass

While I was creating a reactive form, I had to assign 2 types of class on the button. This is how I did it:

<button type="submit" class="btn" [ngClass]="(formGroup.valid)?'btn-info':''" 
[disabled]="!formGroup.valid">Sign in</button>

When the form is valid, button has btn and btn-class (from bootstrap), otherwise just btn class.

How to continue a Docker container which has exited

If you want to continue exactly one Docker container with a known name:

docker start  `docker ps -a -q --filter "name=elas"`

find files by extension, *.html under a folder in nodejs

The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with .html

var fs = require('fs');
var path = require('path');

var searchRecursive = function(dir, pattern) {
  // This is where we store pattern matches of all files inside the directory
  var results = [];

  // Read contents of directory
  fs.readdirSync(dir).forEach(function (dirInner) {
    // Obtain absolute path
    dirInner = path.resolve(dir, dirInner);

    // Get stats to determine if path is a directory or a file
    var stat = fs.statSync(dirInner);

    // If path is a directory, scan it and combine results
    if (stat.isDirectory()) {
      results = results.concat(searchRecursive(dirInner, pattern));
    }

    // If path is a file and ends with pattern then push it onto results
    if (stat.isFile() && dirInner.endsWith(pattern)) {
      results.push(dirInner);
    }
  });

  return results;
};

var files = searchRecursive('./', '.html'); // replace dir and pattern
                                                // as you seem fit

console.log(files);

Update date + one year in mysql

This post helped me today, but I had to experiment to do what I needed. Here is what I found.

Should you want to add more complex time periods, for example 1 year and 15 days, you can use

UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;

I found that using DATE_ADD doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now() rather than curdate().

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

Focusable EditText inside ListView

Sorry, answered my own question. It may not be the most correct or most elegant solution, but it works for me, and gives a pretty solid user experience. I looked into the code for ListView to see why the two behaviors are so different, and came across this from ListView.java:

    public void setItemsCanFocus(boolean itemsCanFocus) {
        mItemsCanFocus = itemsCanFocus;
        if (!itemsCanFocus) {
            setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        }
    }

So, when calling setItemsCanFocus(false), it's also setting descendant focusability such that no child can get focus. This explains why I couldn't just toggle mItemsCanFocus in the ListView's OnItemSelectedListener -- because the ListView was then blocking focus to all children.

What I have now:

<ListView
    android:id="@android:id/list" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent"
    android:descendantFocusability="beforeDescendants"
    />

I use beforeDescendants because the selector will only be drawn when the ListView itself (not a child) has focus, so the default behavior needs to be that the ListView takes focus first and draws selectors.

Then in the OnItemSelectedListener, since I know which header view I want to override the selector (would take more work to dynamically determine if any given position contains a focusable view), I can change descendant focusability, and set focus on the EditText. And when I navigate out of that header, change it back it again.

public void onItemSelected(AdapterView<?> listView, View view, int position, long id)
{
    if (position == 1)
    {
        // listView.setItemsCanFocus(true);

        // Use afterDescendants, because I don't want the ListView to steal focus
        listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        myEditText.requestFocus();
    }
    else
    {
        if (!listView.isFocused())
        {
            // listView.setItemsCanFocus(false);

            // Use beforeDescendants so that the EditText doesn't re-take focus
            listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            listView.requestFocus();
        }
    }
}

public void onNothingSelected(AdapterView<?> listView)
{
    // This happens when you start scrolling, so we need to prevent it from staying
    // in the afterDescendants mode if the EditText was focused 
    listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}

Note the commented-out setItemsCanFocus calls. With those calls, I got the correct behavior, but setItemsCanFocus(false) caused focus to jump from the EditText, to another widget outside of the ListView, back to the ListView and displayed the selector on the next selected item, and that jumping focus was distracting. Removing the ItemsCanFocus change, and just toggling descendant focusability got me the desired behavior. All items draw the selector as normal, but when getting to the row with the EditText, it focused on the text field instead. Then when continuing out of that EditText, it started drawing the selector again.

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

Check for false

Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.

if(!(borrar() === false))

or

if(borrar() === true)

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

You can use the following if you want to specify tricky formats:

df['date_col'] =  pd.to_datetime(df['date_col'], format='%d/%m/%Y')

More details on format here:

Java inner class and static nested class

The following is an example of static nested class and inner class:

OuterClass.java

public class OuterClass {
     private String someVariable = "Non Static";

     private static String anotherStaticVariable = "Static";  

     OuterClass(){

     }

     //Nested classes are static
     static class StaticNestedClass{
        private static String privateStaticNestedClassVariable = "Private Static Nested Class Variable"; 

        //can access private variables declared in the outer class
        public static void getPrivateVariableofOuterClass(){
            System.out.println(anotherStaticVariable);
        }
     }

     //non static
     class InnerClass{

         //can access private variables of outer class
         public String getPrivateNonStaticVariableOfOuterClass(){
             return someVariable;
         }
     }

     public static void accessStaticClass(){
         //can access any variable declared inside the Static Nested Class 
         //even if it private
         String var = OuterClass.StaticNestedClass.privateStaticNestedClassVariable; 
         System.out.println(var);
     }

}

OuterClassTest:

public class OuterClassTest {
    public static void main(String[] args) {

        //access the Static Nested Class
        OuterClass.StaticNestedClass.getPrivateVariableofOuterClass();

        //test the private variable declared inside the static nested class
        OuterClass.accessStaticClass();
        /*
         * Inner Class Test
         * */

        //Declaration

        //first instantiate the outer class
        OuterClass outerClass = new OuterClass();

        //then instantiate the inner class
        OuterClass.InnerClass innerClassExample =  outerClass. new InnerClass();

        //test the non static private variable
        System.out.println(innerClassExample.getPrivateNonStaticVariableOfOuterClass()); 

    }

}

Error "initializer element is not constant" when trying to initialize variable with const

Just for illustration by compare and contrast The code is from http://www.geeksforgeeks.org/g-fact-80/ /The code fails in gcc and passes in g++/

#include<stdio.h>
int initializer(void)
{
    return 50;
}

int main()
{
    int j;
    for (j=0;j<10;j++)
    {
        static int i = initializer();
        /*The variable i is only initialized to one*/
        printf(" value of i = %d ", i);
        i++;
    }
    return 0;
}

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

What is the Ruby <=> (spaceship) operator?

What is <=> ( The 'Spaceship' Operator )

According to the RFC that introduced the operator, $a <=> $b

 -  0 if $a == $b
 - -1 if $a < $b
 -  1 if $a > $b

 - Return 0 if values on either side are equal
 - Return 1 if value on the left is greater
 - Return -1 if the value on the right is greater

Example:

//Comparing Integers

echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1

//String Comparison

echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1

MORE:

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

If you used the Visual Studio 2012 ASP.NET Web Forms Application template then you would have gotten that reference. I'm assuming it's the one you would get via Nuget instead of the framework System.Data.Entity reference.

enter image description here

Check if a number is a perfect square

This can be solved using the decimal module to get arbitrary precision square roots and easy checks for "exactness":

import math
from decimal import localcontext, Context, Inexact

def is_perfect_square(x):
    # If you want to allow negative squares, then set x = abs(x) instead
    if x < 0:
        return False

    # Create localized, default context so flags and traps unset
    with localcontext(Context()) as ctx:
        # Set a precision sufficient to represent x exactly; `x or 1` avoids
        # math domain error for log10 when x is 0
        ctx.prec = math.ceil(math.log10(x or 1)) + 1  # Wrap ceil call in int() on Py2
        # Compute integer square root; don't even store result, just setting flags
        ctx.sqrt(x).to_integral_exact()
        # If previous line couldn't represent square root as exact int, sets Inexact flag
        return not ctx.flags[Inexact]

For demonstration with truly huge values:

# I just kept mashing the numpad for awhile :-)
>>> base = 100009991439393999999393939398348438492389402490289028439083249803434098349083490340934903498034098390834980349083490384903843908309390282930823940230932490340983098349032098324908324098339779438974879480379380439748093874970843479280329708324970832497804329783429874329873429870234987234978034297804329782349783249873249870234987034298703249780349783497832497823497823497803429780324
>>> sqr = base ** 2
>>> sqr ** 0.5  # Too large to use floating point math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float

>>> is_perfect_power(sqr)
True
>>> is_perfect_power(sqr-1)
False
>>> is_perfect_power(sqr+1)
False

If you increase the size of the value being tested, this eventually gets rather slow (takes close to a second for a 200,000 bit square), but for more moderate numbers (say, 20,000 bits), it's still faster than a human would notice for individual values (~33 ms on my machine). But since speed wasn't your primary concern, this is a good way to do it with Python's standard libraries.

Of course, it would be much faster to use gmpy2 and just test gmpy2.mpz(x).is_square(), but if third party packages aren't your thing, the above works quite well.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SQL Server by default uses the mdy date format and so the below works:

SELECT convert(datetime, '07/23/2009', 111)

and this does not work:

SELECT convert(datetime, '23/07/2009', 111)

I myself have been struggling to come up with a single query that can handle both date formats: mdy and dmy.

However, you should be ok with the third date format - ymd.

A regular expression to exclude a word/string

As you want to exclude both words, you need a conjuction:

^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$

Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

angular2: Error: TypeError: Cannot read property '...' of undefined

Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

How to select last two characters of a string

Slice can be used to find the substring. When we know the indexes we can use an alternative solution like index wise adder. Both are taking roughly the same time for execution.

_x000D_
_x000D_
const primitiveStringMember = "my name is Mate";

const objectStringMember = new String("my name is Mate");
console.log(typeof primitiveStringMember);//string
console.log(typeof objectStringMember);//object


/* However when we use . operator to string primitive type, JS will wrap up the string with object. That's why we can use the methods String object type for the primitive type string.
*/

//Slice method
const t0 = performance.now();
slicedString = primitiveStringMember.slice(-2);//te
const t1 = performance.now();
console.log(`Call to do slice took ${t1 - t0} milliseconds.`);


//index vise adder method
const t2 = performance.now();
length = primitiveStringMember.length
neededString = primitiveStringMember[length-2]+primitiveStringMember[length-1];//te
const t3 = performance.now();
console.log(`Call to do index adder took ${t3 - t2} milliseconds.`);
_x000D_
_x000D_
_x000D_

HTML tag inside JavaScript

<div id="demo"></div>

<script type="text/javascript">
    if(document.getElementById('number1').checked) {
        var demo = document.getElementById("demo");    
        demo.innerHtml='<h1>Hello member</h1>';
    } else {
        demo.innerHtml='';
    }
</script>

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

C# Encoding a text string with line breaks

Yes - it means you're using \n as the line break instead of \r\n. Notepad only understands the latter.

(Note that Environment.NewLine suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n, you should specify it explicitly.)

Difference between app.use and app.get in express.js

app.get is called when the HTTP method is set to GET, whereas app.use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

How to get first and last day of the current week in JavaScript

var dt = new Date()  //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));

This will be useful for any date scenario.

Cannot create Maven Project in eclipse

I am using Spring STS 3.8.3. I had a similar problem. I fixed it by using information from this thread And also by fixing some maven settings. click Spring Tool Suite -> Preferences -> Maven and uncheck the box that says "Do not automatically update dependencies from remote depositories" Also I checked the boxes that say "Download Artifact Sources" and "download Artifact javadoc".

Java String new line

What about %n using a formatter like String.format()?:

String s = String.format("I%nam%na%nboy");

As this answer says, its available from java 1.5 and is another way to System.getProperty("line.separator") or System.lineSeparator() and, like this two, is OS independent.

Determine number of pages in a PDF file

You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.

iTextSharp Example

You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
  class Program
{
    static void Main(string[] args)
      {
       // Right side of equation is location of YOUR pdf file
        string ppath = "C:\\aworking\\Hawkins.pdf";
        PdfReader pdfReader = new PdfReader(ppath);
        int numberOfPages = pdfReader.NumberOfPages;
        Console.WriteLine(numberOfPages);
        Console.ReadLine();
      }
   }
}

How do I add an active class to a Link from React Router?

Use React Hooks.

import React, { useState } from 'react';

export const Table = () => {

const [activeMenu, setActiveMenu] = useState('transaction');

return(
<>
 <Link className="flex-1 mr-2">
          <a
            id="transaction"
            className={
              activeMenu == 'transaction'
                ? 'text-center block border border-blue-500 rounded py-2 px-4 bg-blue-500 hover:bg-blue-700 text-white'
                : 'text-center block border border-white rounded hover:border-gray-200 text-blue-500 hover:bg-gray-200 py-2 px-4'
            }
            href="#"
            onClick={() => {
              setActiveMenu('transaction');
            }}>
            Recent Transactions
          </a>
        </Link>
        <Link className="flex-1 mr-2">
          <a
            id="account"
            className={
              activeMenu == 'account'
                ? 'text-center block border border-blue-500 rounded py-2 px-4 bg-blue-500 hover:bg-blue-700 text-white'
                : 'text-center block border border-white rounded hover:border-gray-200 text-blue-500 hover:bg-gray-200 py-2 px-4'
            }
            href="#"
            onClick={() => {
              setActiveMenu('account');
            }}>
            Account Statement
          </a>
        </LInk>

</>
)
}

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

Docker remove <none> TAG images

You may check if the filter 'dangling' is no more working

$ docker images -f “dangling=true” -q
Error response from daemon: Invalid filter 'dangling'

Use docker system prune to remove the dangling images

$ docker system prune
WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all dangling images
        - all dangling build cache
Are you sure you want to continue? [y/N]

You may use --force for not prompt for confirmation

$ docker system prune --force

asynchronous vs non-blocking

Blocking call: Control returns only when the call completes.

Non blocking call: Control returns immediately. Later OS somehow notifies the process that the call is complete.


Synchronous program: A program which uses Blocking calls. In order not to freeze during the call it must have 2 or more threads (that's why it's called Synchronous - threads are running synchronously).

Asynchronous program: A program which uses Non blocking calls. It can have only 1 thread and still remain interactive.

Undefined reference to main - collect2: ld returned 1 exit status

One possibility which has not been mentioned so far is that you might not be editing the file you think you are. i.e. your editor might have a different cwd than you had in mind.

Run 'more' on the file you're compiling to double check that it does indeed have the contents you hope it does. Hope that helps!

How to fill in form field, and submit, using javascript?

You can try something like this:

    <script type="text/javascript">
        function simulateLogin(userName)
        {
            var userNameField = document.getElementById("username");
            userNameField.value = userName;
            var goButton = document.getElementById("go");
            goButton.click();
        }

        simulateLogin("testUser");
</script>

Pandas/Python: Set value of one column based on value in another column

You can use pandas.DataFrame.mask to add virtually as many conditions as you need:

data = {'a': [1,2,3,4,5], 'b': [6,8,9,10,11]}

d = pd.DataFrame.from_dict(data, orient='columns')
c = {'c1': (2, 'Value1'), 'c2': (3, 'Value2'), 'c3': (5, d['b'])}

d['new'] = np.nan
for value in c.values():
    d['new'].mask(d['a'] == value[0], value[1], inplace=True)

d['new'] = d['new'].fillna('Else')
d

Output:

    a   b   new
0   1   6   Else
1   2   8   Value1
2   3   9   Value2
3   4   10  Else
4   5   11  11

WARNING: Can't verify CSRF token authenticity rails

Ugrading from an older app to rails 3.1, including the csrf meta tag is still not solving it. On the rubyonrails.org blog, they give some upgrade tips, and specifically this line of jquery which should go in the head section of your layout:

$(document).ajaxSend(function(e, xhr, options) {
 var token = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", token);
});

taken from this blog post: http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails.

In my case, the session was being reset upon each ajax request. Adding the above code solved that issue.

Xcode: failed to get the task for process

Change the profile for code signing. Select your project, go to Build Settings > Code Signing Identity. Switch to other developer profile.

How to use FormData for AJAX file upload?

View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
                $(document).on('change', ':file', function () {
                    var fileUpload = $(this).get(0);
                    var files = fileUpload.files;
                    var bid = 0;
                    if (files.length != 0) {
                        var data = new FormData();
                        for (var i = 0; i < files.length ; i++) {
                            data.append(files[i].name, files[i]);
                        }
                        $.ajax({
                            xhr: function () {
                                var xhr = $.ajaxSettings.xhr();
                                xhr.upload.onprogress = function (e) {
                                    console.log(Math.floor(e.loaded / e.total * 100) + '%');
                                };
                                return xhr;
                            },
                            contentType: false,
                            processData: false,
                            type: 'POST',
                            data: data,
                            url: '/ControllerX/' + bid,
                            success: function (response) {
                                location.href = 'xxx/Index/';
                            }
                        });
                    }
                });
            });
</Script>
Controller:
[HttpPost]
        public ActionResult ControllerX(string id)
        {
            var files = Request.Form.Files;
...

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

How can I read SMS messages from the device programmatically in Android?

Use Content Resolver ("content://sms/inbox") to read SMS which are in inbox.

// public static final String INBOX = "content://sms/inbox";
// public static final String SENT = "content://sms/sent";
// public static final String DRAFT = "content://sms/draft";
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);

if (cursor.moveToFirst()) { // must check the result to prevent exception
    do {
       String msgData = "";
       for(int idx=0;idx<cursor.getColumnCount();idx++)
       {
           msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
       }
       // use msgData
    } while (cursor.moveToNext());
} else {
   // empty box, no SMS
}

Please add READ_SMS permission.

I Hope it helps :)

How to run a PowerShell script without displaying a window?

I think that the best way to hide the console screen of the PowerShell when your are running a background scripts is this code ("Bluecakes" answer).

I add this code in the beginning of all my PowerShell scripts that I need to run in background.

# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Hide-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}
Hide-Console

If this answer was help you, please vote to "Bluecakes" in his answer in this post.

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

no sqljdbc_auth in java.library.path

1) Download the JDBC Driver here.


2) unzip the file and go to sqljdbc_version\fra\auth\x86 or \x64
3) copy the sqljdbc_auth.dll to C:\Program Files\Java\jre_Version\bin
4) Finally restart eclipse

How to re import an updated package while in Python Interpreter?

Basically reload as in allyourcode's asnwer. But it won't change underlying the code of already instantiated object or referenced functions. Extending from his answer:

#Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py

# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
>>> x = mymodule.x
>>> x()
version 1
>>> x is mymodule.x
True


# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py

# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
>>> x()
version 1
>>> x is mymodule.x
False

How are parameters sent in an HTTP POST request?

Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.

The POST request may semantically look like this:

POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

name    id
John    G12N
Sarah   J87M
Bob     N33Y

This approach logically combines QueryString and Body-Post using a single Content-Type which is a "parsing-instruction" for a web-server.

Please note: HTTP/1.1 is wrapped with the #32 (space) on the left and with #10 (Line feed) on the right.

javascript date + 7 days

Two problems here:

  1. seven_date is a number, not a date. 29 + 7 = 36
  2. getMonth returns a zero based index of the month. So adding one just gets you the current month number.

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

Generate .pem file used to set up Apple Push Notifications

There's much simpler solution today — pem. This tool makes life much easier.

For example, to generate or renew your push notification certificate just enter:

fastlane pem 

and it's done in under a minute. In case you need a sandbox certificate, enter:

fastlane pem --development

And that's pretty it.

Comparing Arrays of Objects in JavaScript

I tried JSON.stringify() and worked for me.

let array1 = [1,2,{value:'alpha'}] , array2 = [{value:'alpha'},'music',3,4];

JSON.stringify(array1) // "[1,2,{"value":"alpha"}]"

JSON.stringify(array2) // "[{"value":"alpha"},"music",3,4]"

JSON.stringify(array1) === JSON.stringify(array2); // false

How do I handle newlines in JSON?

According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:

A string is a sequence of Unicode code points wrapped with quotation marks (U+0022). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022), reverse solidus (U+005C), and the control characters U+0000 to U+001F. There are two-character escape sequence representations of some characters.

So you can't pass 0x0A or 0x0C codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000 to U+001F:

  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).

As most of programming languages uses \ for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):

jsonStr = "{ \"name\": \"Multi\\nline.\" }";

Difference between core and processor

A core is usually the basic computation unit of the CPU - it can run a single program context (or multiple ones if it supports hardware threads such as hyperthreading on Intel CPUs), maintaining the correct program state, registers, and correct execution order, and performing the operations through ALUs. For optimization purposes, a core can also hold on-core caches with copies of frequently used memory chunks.

A CPU may have one or more cores to perform tasks at a given time. These tasks are usually software processes and threads that the OS schedules. Note that the OS may have many threads to run, but the CPU can only run X such tasks at a given time, where X = number cores * number of hardware threads per core. The rest would have to wait for the OS to schedule them whether by preempting currently running tasks or any other means.

In addition to the one or many cores, the CPU will include some interconnect that connects the cores to the outside world, and usually also a large "last-level" shared cache. There are multiple other key elements required to make a CPU work, but their exact locations may differ according to design. You'll need a memory controller to talk to the memory, I/O controllers (display, PCIe, USB, etc..). In the past these elements were outside the CPU, in the complementary "chipset", but most modern design have integrated them into the CPU.

In addition the CPU may have an integrated GPU, and pretty much everything else the designer wanted to keep close for performance, power and manufacturing considerations. CPU design is mostly trending in to what's called system on chip (SoC).

This is a "classic" design, used by most modern general-purpose devices (client PC, servers, and also tablet and smartphones). You can find more elaborate designs, usually in the academy, where the computations is not done in basic "core-like" units.

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

How to build jars from IntelliJ properly?

Some of the other answers are useless because as soon as you re-import the IntelliJ IDEA project from the maven project, all changes will be lost.

The building of the jar needs to be triggered by a run/debug configuration, not by the project settings.

Jetbrains has a nice description of how you can accomplish this here:

https://www.jetbrains.com/help/idea/maven.html

Scroll down to the section called "Configuring triggers for Maven goals".

(The only disadvantage of their description is that their screenshots are in the default black-on-white color scheme instead of the super-awesome darcula theme. Ugh!)

So, basically, what you do is that you open the "Maven Projects" panel, you find the project of interest, (in your case, the project that builds your jar,) underneath it you find the maven goal that you want to execute, (usually the "package" goal creates jars,) you open up the context menu on it, (right-click on a Windows machine,) and there will be an "Execute before Run/Debug..." option that you can select and it will take you by the hand from there. Really easy.

How to display Base64 images in HTML?

This will show image of base 64 data:

<style>
.logo {
      width: 290px;
      height: 63px;
      background: url(data:image/png;base64,copy-paste-base64-data-here) no-repeat;
}
</style>

<div class="logo"></div>

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

Google Chrome Printing Page Breaks

Have that issue. So long time pass... Without side-fields of page it's break normal, but when fields appears, page and "page break space" will scale. So, with a normal field, within a document, it was shown incorrect. I fix it with set

    width:100%

and use

div.page
  {
    page-break-before: always;
    page-break-inside: avoid;
  }

Use it on first line.

How can I create an array/list of dictionaries in python?

I assume that motifWidth contains an integer.

In Python, lists do not change size unless you tell them to. Hence, Python throws an exception when you try to change an element that isn't there. I believe you want:

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

For what it's worth, when asking questions in the future, it would help if you included the stack trace showing the error that you're getting rather than just saying "it isn't working". That would help us directly figure out the cause of the problem, rather than trying to puzzle it out from your code.

Hope that helps!

How to convert an int to a hex string?

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

Disable Drag and Drop on HTML elements?

Question is old, but it's never too late to answer.

$(document).ready(function() {
  //prevent drag and drop
  const yourInput = document.getElementById('inputid');
  yourInput.ondrop = e => e.preventDefault();

  //prevent paste
  const Input = document.getElementById('inputid');
  Input.onpaste = e => e.preventDefault();
});

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

I adapted the MS-Technet VBScript for my needs. It dumps Wow6432Node as well as standard entries into "programms.txt" Use it at your own risk, no warranty!

Save as dump.vbs

From command line type: wscript dump.vbs

Const HKLM = &H80000002
Set objReg = GetObject("winmgmts://" & "." & "/root/default:StdRegProv")
Set objFSO = CreateObject("Scripting.FileSystemObject")

outFile="programms.txt"

Set objFile = objFSO.CreateTextFile(outFile,True)
writeList "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\", objReg, objFile
writeList "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\", objReg, objFile
objFile.Close 

Function writeList(strBaseKey, objReg, objFile) 
objReg.EnumKey HKLM, strBaseKey, arrSubKeys 
    For Each strSubKey In arrSubKeys
        intRet = objReg.GetStringValue(HKLM, strBaseKey & strSubKey, "DisplayName", strValue)
        If intRet <> 0 Then
            intRet = objReg.GetStringValue(HKLM, strBaseKey & strSubKey, "QuietDisplayName", strValue)
        End If
        objReg.GetStringValue HKLM, strBaseKey & strSubKey, "DisplayVersion", version
        objReg.GetStringValue HKLM, strBaseKey & strSubKey, "InstallDate", insDate 
        If (strValue <> "") and (intRet = 0) Then
            objFile.Write strValue & "," & version & "," & insDate & vbCrLf
        End If
    Next
End Function

The conversion of the varchar value overflowed an int column

Declare @phoneNumber int

select @phoneNumber=Isnull('08041159620',0);

Give error :

The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)

AS

Integer is defined as :

Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.

Solution

Declare @phoneNumber bigint

Reference

Tracking CPU and Memory usage per process

Download process monitor

  1. Start Process Monitor

  2. Set a filter if required

  3. Enter menu Options > Profiling Events

  4. Click "Generate thread prof?iling events", choose the frequency, and click OK.

  5. To see the collected historical data at any time, enter menu Tools > Process Activity Summary

Get the last three chars from any string - Java

Why not just String substr = word.substring(word.length() - 3)?

Update

Please make sure you check that the String is at least 3 characters long before calling substring():

if (word.length() == 3) {
  return word;
} else if (word.length() > 3) {
  return word.substring(word.length() - 3);
} else {
  // whatever is appropriate in this case
  throw new IllegalArgumentException("word has less than 3 characters!");
}

What is the difference between Bootstrap .container and .container-fluid classes?

Both .container and .container-fluid are responsive (i.e. they change the layout based on the screen width), but in different ways (I know, the naming doesn't make it sound that way).

Short Answer:

.container is jumpy / choppy resizing, and

.container-fluid is continuous / fine resizing at width: 100%.

From a functionality perspective:

.container-fluid continuously resizes as you change the width of your window/browser by any amount, leaving no extra empty space on the sides ever, unlike how .container does. (Hence the naming: "fluid" as opposed to "digital", "discrete", "chunked", or "quantized").

.container resizes in chunks at several certain widths. In other words, it will be different specific aka "fixed" widths different ranges of screen widths.

Semantics: "fixed width"

You can see how naming confusion can arise. Technically, we can say .container is "fixed width", but it is fixed only in the sense that it doesn't resize at every granular width. It's actually not "fixed" in the sense that it's always stays at a specific pixel width, since it actually can change size.

From a fundamental perspective:

.container-fluid has the CSS property width: 100%;, so it continually readjusts at every screen width granularity.

.container-fluid {
  width: 100%;
}

.container has something like "width = 800px" (or em, rem etc.), a specific pixel width value at different screen widths. This of course is what causes the element width to abruptly jump to a different width when the screen width crosses a screen width threshold. And that threshold is governed by CSS3 media queries, which allow you to apply different styles for different conditions, such as screen width ranges.

@media screen and (max-width: 400px){
  .container {
    width: 123px;
  }
}
@media screen and (min-width: 401px) and (max-width: 800px){

  .container {
    width: 456px;
  }
}
@media screen and (min-width: 801px){
  .container {
    width: 789px;
  }
}

Beyond

You can make any fixed widths element responsive via media queries, not just .container elements, since media queries is exactly how .container is implemented by bootstrap in the background (see JKillian's answer for the code).

Elegant ways to support equivalence ("equality") in Python classes

I think that the two terms you're looking for are equality (==) and identity (is). For example:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True       <-- a and b have values which are equal
>>> a is b
False      <-- a and b are not the same list object

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

simple way to display data in a .txt file on a webpage?

I find that if I try things that others say do not work, it's how I learn the most.

<p>&nbsp;</p>
<p>README.txt</p>
<p>&nbsp;</p>
<div id="list">
  <p><iframe src="README.txt" frameborder="0" height="400"
      width="95%"></iframe></p>
</div>

This worked for me. I used the yellow background-color that I set in the stylesheet.

#list  p {
    font: arial;
    font-size: 14px;
    background-color: yellow ;
}

Adding POST parameters before submit

If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:

var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});

$.post("api/comment", formData, function(data) {
  // request has finished, check for errors
  // and then for example redirect to another page
});

See .serializeArray() and $.post() documentation.

How to check if a file is a valid image file?

format = [".jpg",".png",".jpeg"]
 for (path,dirs,files) in os.walk(path):
     for file in files:
         if file.endswith(tuple(format)):
             print(path)
             print ("Valid",file)
         else:
             print(path)
             print("InValid",file)

Postgresql Select rows where column = array

   $array[0] = 1;
   $array[2] = 2;
   $arrayTxt = implode( ',', $array);
   $sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"

HTTP GET in VB.NET

Use the WebRequest class

This is to get an image:

Try
    Dim _WebRequest As System.Net.WebRequest = Nothing
    _WebRequest = System.Net.WebRequest.Create(http://api.hostip.info/?ip=68.180.206.184)
Catch ex As Exception
    Windows.Forms.MessageBox.Show(ex.Message)
    Exit Sub
End Try

Try
    _NormalImage = Image.FromStream(_WebRequest.GetResponse().GetResponseStream())
Catch ex As Exception
    Windows.Forms.MessageBox.Show(ex.Message)
    Exit Sub
End Try

AngularJS access scope from outside js function

The accepted answer is great. I wanted to look at what happens to the Angular scope in the context of ng-repeat. The thing is, Angular will create a sub-scope for each repeated item. When calling into a method defined on the original $scope, that retains its original value (due to javascript closure). However, the this refers the calling scope/object. This works out well, so long as you're clear on when $scope and this are the same and when they are different. hth

Here is a fiddle that illustrates the difference: https://jsfiddle.net/creitzel/oxsxjcyc/

Practical uses of git reset --soft?

I use it to amend more than just the last commit.

Let's say I made a mistake in commit A and then made commit B. Now I can only amend B. So I do git reset --soft HEAD^^, I correct and re-commit A and then re-commit B.

Of course, it's not very convenient for large commits… but you shouldn't do large commits anyway ;-)

Javascript can't find element by id?

Run the code either in onload event, either just before you close body tag. You try to find an element wich is not there at the moment you do it.

What is the best way to implement "remember me" for a website?

Improved Persistent Login Cookie Best Practice

You could use this strategy described here as best practice (2006) or an updated strategy described here (2015):

  1. When the user successfully logs in with Remember Me checked, a login cookie is issued in addition to the standard session management cookie.
  2. The login cookie contains a series identifier and a token. The series and token are unguessable random numbers from a suitably large space. Both are stored together in a database table, the token is hashed (sha256 is fine).
  3. When a non-logged-in user visits the site and presents a login cookie, the series identifier is looked up in the database.
    1. If the series identifier is present and the hash of the token matches the hash for that series identifier, the user is considered authenticated. A new token is generated, a new hash for the token is stored over the old record, and a new login cookie is issued to the user (it's okay to re-use the series identifier).
    2. If the series is present but the token does not match, a theft is assumed. The user receives a strongly worded warning and all of the user's remembered sessions are deleted.
    3. If the username and series are not present, the login cookie is ignored.

This approach provides defense-in-depth. If someone manages to leak the database table, it does not give an attacker an open door for impersonating users.

How can I get a list of users from active directory?

If you are new to Active Directory, I suggest you should understand how Active Directory stores data first.

Active Directory is actually a LDAP server. Objects stored in LDAP server are stored hierarchically. It's very similar to you store your files in your file system. That's why it got the name Directory server and Active Directory

The containers and objects on Active Directory can be specified by a distinguished name. The distinguished name is like this CN=SomeName,CN=SomeDirectory,DC=yourdomain,DC=com. Like a traditional relational database, you can run query against a LDAP server. It's called LDAP query.

There are a number of ways to run a LDAP query in .NET. You can use DirectorySearcher from System.DirectoryServices or SearchRequest from System.DirectoryServices.Protocol.

For your question, since you are asking to find user principal object specifically, I think the most intuitive way is to use PrincipalSearcher from System.DirectoryServices.AccountManagement. You can easily find a lot of different examples from google. Here is a sample that is doing exactly what you are asking for.

using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
            Console.WriteLine();
        }
    }
}
Console.ReadLine();

Note that on the AD user object, there are a number of attributes. In particular, givenName will give you the First Name and sn will give you the Last Name. About the user name. I think you meant the user logon name. Note that there are two logon names on AD user object. One is samAccountName, which is also known as pre-Windows 2000 user logon name. userPrincipalName is generally used after Windows 2000.

hasOwnProperty in JavaScript

hasOwnProperty() is a nice property to validate object keys. Example:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

If a DOM Element is removed, are its listeners also removed from memory?

regarding jQuery:

the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Reference: http://api.jquery.com/remove/

jQuery v1.8.2 .remove() source code:

remove: function( selector, keepData ) {
    var elem,
        i = 0;

    for ( ; (elem = this[i]) != null; i++ ) {
        if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
            if ( !keepData && elem.nodeType === 1 ) {
                jQuery.cleanData( elem.getElementsByTagName("*") );
                jQuery.cleanData( [ elem ] );
            }

            if ( elem.parentNode ) {
                elem.parentNode.removeChild( elem );
            }
        }
    }

    return this;
}

apparently jQuery uses node.removeChild()

According to this : https://developer.mozilla.org/en-US/docs/DOM/Node.removeChild ,

The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.

ie event listeners might get removed, but node still exists in memory.

How to erase the file contents of text file in Python?

You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

If you are not using https in api calls, Please add this key "App Uses Non-Exempt Encryption" in your info.plist and set it to "NO"

Using 'sudo apt-get install build-essentials'

In my case, simply "dropping the s" was not the problem (although it is of course a step in the right direction to use the correct package name).

I had to first update the package manager indexes like this:

sudo apt-get update

Then after that the installation worked fine:

sudo apt-get install build-essential

How to unzip a file using the command line?

As other have alluded, 7-zip is great.

Note: I am going to zip and then unzip a file. Unzip is at the bottom.

My contribution:

Get the

7-Zip Command Line Version

Current URL

http://www.7-zip.org/download.html

The syntax?

You can put the following into a .bat file

"C:\Program Files\7-Zip\7z.exe" a MySuperCoolZipFile.zip "C:\MyFiles\*.jpg" -pmypassword -r -w"C:\MyFiles\" -mem=AES256

I've shown a few options.

-r is recursive. Usually what you want with zip functionality.

a is for "archive". That's the name of the output zip file.

-p is for a password (optional)

-w is a the source directory. This will nest your files correctly in the zip file, without extra folder information.

-mem is the encryption strength.

There are others. But the above will get you running.

NOTE: Adding a password will make the zip file unfriendly when it comes to viewing the file through Windows Explorer. The client may need their own copy of 7-zip (or winzip or other) to view the contents of the file.

EDIT::::::::::::(just extra stuff).

There is a "command line" version which is probably better suited for this: http://www.7-zip.org/download.html

(current (at time of writing) direct link) http://sourceforge.net/projects/sevenzip/files/7-Zip/9.20/7za920.zip/download

So the zip command would be (with the command line version of the 7 zip tool).

"C:\WhereIUnzippedCommandLineStuff\7za.exe" a MySuperCoolZipFile.zip "C:\MyFiles\*.jpg" -pmypassword -r -w"C:\MyFiles\" -mem=AES256

Now the unzip portion: (to unzip the file you just created)

"C:\WhereIUnzippedCommandLineStuff\7zipCommandLine\7za.exe" e MySuperCoolZipFile.zip "*.*" -oC:\SomeOtherFolder\MyUnzippedFolder -pmypassword -y -r

As an alternative to the "e" argument, there is a x argument.

  e: Extract files from archive (without using directory names)
  x: eXtract files with full paths

Documentation here:

http://sevenzip.sourceforge.jp/chm/cmdline/commands/extract.htm

How to sort an associative array by its values in Javascript?

Just so it's out there and someone is looking for tuple based sorts. This will compare the first element of the object in array, than the second element and so on. i.e in the example below, it will compare first by "a", then by "b" and so on.

let arr = [
    {a:1, b:2, c:3},
    {a:3, b:5, c:1},
    {a:2, b:3, c:9},
    {a:2, b:5, c:9},
    {a:2, b:3, c:10}    
]

function getSortedScore(obj) {
    var keys = []; 
    for(var key in obj[0]) keys.push(key);
    return obj.sort(function(a,b){
        for (var i in keys) {
            let k = keys[i];
            if (a[k]-b[k] > 0) return -1;
            else if (a[k]-b[k] < 0) return 1;
            else continue;
        };
    });
}

console.log(getSortedScore(arr))

OUPUTS

 [ { a: 3, b: 5, c: 1 },
  { a: 2, b: 5, c: 9 },
  { a: 2, b: 3, c: 10 },
  { a: 2, b: 3, c: 9 },
  { a: 1, b: 2, c: 3 } ]

Assign a variable inside a Block to a variable outside a Block

yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

How can I set a proxy server for gem?

When setting http_proxy and https_proxy, you are also probably going to need no_proxy for URLs on the same side of the proxy. https://msdn.microsoft.com/en-us/library/hh272656(v=vs.120).aspx

Can I access constants in settings.py from templates in Django?

I improved chrisdew's answer (to create your own tag) a little bit.

First, create the file yourapp/templatetags/value_from_settings.py in which you define your own new tag value_from_settings:

from django.template import TemplateSyntaxError, Variable, Node, Variable, Library
from yourapp import settings

register = Library()
# I found some tricks in URLNode and url from defaulttags.py:
# https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py
@register.tag
def value_from_settings(parser, token):
  bits = token.split_contents()
  if len(bits) < 2:
    raise TemplateSyntaxError("'%s' takes at least one " \
      "argument (settings constant to retrieve)" % bits[0])
  settingsvar = bits[1]
  settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
  asvar = None
  bits = bits[2:]
  if len(bits) >= 2 and bits[-2] == 'as':
    asvar = bits[-1]
    bits = bits[:-2]
  if len(bits):
    raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
      "the arguments '%s'" % ", ".join(bits))
  return ValueFromSettings(settingsvar, asvar)

class ValueFromSettings(Node):
  def __init__(self, settingsvar, asvar):
    self.arg = Variable(settingsvar)
    self.asvar = asvar
  def render(self, context):
    ret_val = getattr(settings,str(self.arg))
    if self.asvar:
      context[self.asvar] = ret_val
      return ''
    else:
      return ret_val

You can use this tag in your Template via:

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" %}

or via

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" as my_fqdn %}

The advantage of the as ... notation is that this makes it easy to use in blocktrans blocks via a simple {{my_fqdn}}.

StringIO in Python3

try this

from StringIO import StringIO

x="1 3\n 4.5 8"

numpy.genfromtxt(StringIO(x))

C# ListView Column Width Auto

I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.

private void ResizeListViewColumns(ListView lv)
{
    foreach(ColumnHeader column in lv.Columns)
    {
        column.Width = -2;
    }
}

The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView.

How do I increase the contrast of an image in Python OpenCV

img = cv2.imread("/x2.jpeg")

image = cv2.resize(img, (1800, 1800))

alpha=1.5
beta=20

new_image=cv2.addWeighted(image,alpha,np.zeros(image.shape, image.dtype),0,beta)

cv2.imshow("new",new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Convert Data URI to File then append to FormData

Firefox has canvas.toBlob() and canvas.mozGetAsFile() methods.

But other browsers do not.

We can get dataurl from canvas and then convert dataurl to blob object.

Here is my dataURLtoBlob() function. It's very short.

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

Use this function with FormData to handle your canvas or dataurl.

For example:

var dataurl = canvas.toDataURL('image/jpeg',0.8);
var blob = dataURLtoBlob(dataurl);
var fd = new FormData();
fd.append("myFile", blob, "thumb.jpg");

Also, you can create a HTMLCanvasElement.prototype.toBlob method for non gecko engine browser.

if(!HTMLCanvasElement.prototype.toBlob){
    HTMLCanvasElement.prototype.toBlob = function(callback, type, encoderOptions){
        var dataurl = this.toDataURL(type, encoderOptions);
        var bstr = atob(dataurl.split(',')[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        var blob = new Blob([u8arr], {type: type});
        callback.call(this, blob);
    };
}

Now canvas.toBlob() works for all modern browsers not only Firefox. For example:

canvas.toBlob(
    function(blob){
        var fd = new FormData();
        fd.append("myFile", blob, "thumb.jpg");
        //continue do something...
    },
    'image/jpeg',
    0.8
);

How do you get the index of the current iteration of a foreach loop?

I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.

string[] names = { "one", "two", "three" };
var oddOrEvenByName = names
    .Select((name, index) => new KeyValuePair<string, int>(name, index % 2))
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.

ImportError: No module named model_selection

do you have sklearn? if not, do the following:

sudo pip install sklearn

After installing sklearn

from sklearn.model_selection import train_test_split

works fine

Splitting strings in PHP and get last part

This code will do that

<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>

ASP.Net MVC: Calling a method from a view

You should not call a controller from the view.

Add a property to your view model, set it in the controller, and use it in the view.

Here is an example:

MyViewModel.cs:

public class MyViewModel
{   ...
    public bool ShowAdmin { get; set; }
}

MyController.cs:

public ViewResult GetAdminMenu()
    {
        MyViewModelmodel = new MyViewModel();            

        model.ShowAdmin = userHasPermission("Admin"); 

        return View(model);
    }

MyView.cshtml:

@model MyProj.ViewModels.MyViewModel


@if (@Model.ShowAdmin)
{
   <!-- admin links here-->
}

..\Views\Shared\ _Layout.cshtml:

    @using MyProj.ViewModels.Common;
....
    <div>    
        @Html.Action("GetAdminMenu", "Layout")
    </div>

Understanding the set() function

After reading the other answers, I still had trouble understanding why the set comes out un-ordered.

Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...

load scripts asynchronously

I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.

Here is an example of loading jquery:

Modernizr.load([
  {
    load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
    complete: function () {
      if ( !window.jQuery ) {
            Modernizr.load('js/libs/jquery-1.6.1.min.js');
      }
    }
  },
  {
    // This will wait for the fallback to load and
    // execute if it needs to.
    load: 'needs-jQuery.js'
  }
]);

Detect URLs in text with JavaScript

Here is what I ended up using as my regex:

var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

This doesn't include trailing punctuation in the URL. Crescent's function works like a charm :) so:

function linkify(text) {
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + url + '</a>';
    });
}

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

Adding the correct doctype declaration and avoiding the XML prolog should be enough to avoid quirks mode.

How can I multiply and divide using only bit shifting and adding?

This should work for multiplication:

.data

.text
.globl  main

main:

# $4 * $5 = $2

    addi $4, $0, 0x9
    addi $5, $0, 0x6

    add  $2, $0, $0 # initialize product to zero

Loop:   
    beq  $5, $0, Exit # if multiplier is 0,terminate loop
    andi $3, $5, 1 # mask out the 0th bit in multiplier
    beq  $3, $0, Shift # if the bit is 0, skip add
    addu $2, $2, $4 # add (shifted) multiplicand to product

Shift: 
    sll $4, $4, 1 # shift up the multiplicand 1 bit
    srl $5, $5, 1 # shift down the multiplier 1 bit
    j Loop # go for next  

Exit: #


EXIT: 
li $v0,10
syscall

Decreasing height of bootstrap 3.0 navbar

Wanted to added my 2 pence and a thank you to James Poulose for his original answer it was the only one that worked for my particular project (MVC 5 with the latest version of Bootstrap 3).

This is mostly aimed at beginners, for clarity and to make future edits easier I suggest you add a section at the bottom of your CSS file for your project for example I like to do this:

/* Bootstrap overrides */

.some-class-here {
}

Taking James Poulose's answer above I did this:

/* Bootstrap overrides */   
.navbar-nav > li > a { padding-top: 8px !important; padding-bottom: 5px !important; }
.navbar { min-height: 32px !important; }
.navbar-brand { padding-top: 8px; padding-bottom: 10px; padding-left: 10px; }

I changed the padding-top values to push the text down on my navbar element. You can pretty much override any Bootstrap element like this and its a good way of making changes without screwing up the Boostrap base classes because the last thing you want to do is make a change in there and then lose it when you updated Bootstrap!

Finally for even more separation I like to split up my CSS files and use @import declarations to import your sub-files into one main CSS File for easy management for example:

@import url('css/mysubcssfile.css');

note: if you're pulling in multiple files you need to make sure they load in the right order.

Hope this helps someone.

Detect and exclude outliers in Pandas data frame

For each of your dataframe column, you could get quantile with:

q = df["col"].quantile(0.99)

and then filter with:

df[df["col"] < q]

If one need to remove lower and upper outliers, combine condition with an AND statement:

q_low = df["col"].quantile(0.01)
q_hi  = df["col"].quantile(0.99)

df_filtered = df[(df["col"] < q_hi) & (df["col"] > q_low)]

Git diff against a stash

To see the most recent stash:

git stash show -p

To see an arbitrary stash:

git stash show -p stash@{1}

Also, I use git diff to compare the stash with any branch.

You can use:

git diff stash@{0} master

To see all changes compared to branch master.


Or You can use:

git diff --name-only stash@{0} master

To easy find only changed file names.

Could not find a version that satisfies the requirement <package>

Just a reminder to whom google this error and come here.

Let's say I get this error:

$ python3 example.py
Traceback (most recent call last):
  File "example.py", line 7, in <module>
    import aalib
ModuleNotFoundError: No module named 'aalib'

Since it mentions aalib, I was thought to try aalib:

$ python3.8 -m pip install aalib
ERROR: Could not find a version that satisfies the requirement aalib (from versions: none)
ERROR: No matching distribution found for aalib

But it actually wrong package name, ensure pip search(service disabled at the time of writing), or google, or search on pypi site to get the accurate package name:

enter image description here

Then install successfully:

$ python3.8 -m pip install python-aalib
Collecting python-aalib
  Downloading python-aalib-0.3.2.tar.gz (14 kB)
...

As pip --help stated:

$ python3.8 -m pip --help
...
  -v, --verbose               Give more output. Option is additive, and can be used up to 3 times.

To have a systematic way to figure out the root causes instead of rely on luck, you can append -vvv option of pip command to see details, e.g.:

$ python3.8 -u -m pip install aalib -vvv
User install by explicit request
Created temporary directory: /tmp/pip-ephem-wheel-cache-b3ghm9eb
Created temporary directory: /tmp/pip-req-tracker-ygwnj94r
Initialized build tracking at /tmp/pip-req-tracker-ygwnj94r
Created build tracker: /tmp/pip-req-tracker-ygwnj94r
Entered build tracker: /tmp/pip-req-tracker-ygwnj94r
Created temporary directory: /tmp/pip-install-jfurrdbb
1 location(s) to search for versions of aalib:
* https://pypi.org/simple/aalib/
Fetching project page and analyzing links: https://pypi.org/simple/aalib/
Getting page https://pypi.org/simple/aalib/
Found index url https://pypi.org/simple
Getting credentials from keyring for https://pypi.org/simple
Getting credentials from keyring for pypi.org
Looking up "https://pypi.org/simple/aalib/" in the cache
Request header has "max_age" as 0, cache bypassed
Starting new HTTPS connection (1): pypi.org:443
https://pypi.org:443 "GET /simple/aalib/ HTTP/1.1" 404 13
[hole] Status code 404 not in (200, 203, 300, 301)
Could not fetch URL https://pypi.org/simple/aalib/: 404 Client Error: Not Found for url: https://pypi.org/simple/aalib/ - skipping
Given no hashes to check 0 links for project 'aalib': discarding no candidates
ERROR: Could not find a version that satisfies the requirement aalib (from versions: none)
Cleaning up...
Removed build tracker: '/tmp/pip-req-tracker-ygwnj94r'
ERROR: No matching distribution found for aalib
Exception information:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/base_command.py", line 186, in _main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/install.py", line 357, in run
    resolver.resolve(requirement_set)
  File "/usr/lib/python3/dist-packages/pip/_internal/legacy_resolve.py", line 177, in resolve
    discovered_reqs.extend(self._resolve_one(requirement_set, req))
  File "/usr/lib/python3/dist-packages/pip/_internal/legacy_resolve.py", line 333, in _resolve_one
    abstract_dist = self._get_abstract_dist_for(req_to_install)
  File "/usr/lib/python3/dist-packages/pip/_internal/legacy_resolve.py", line 281, in _get_abstract_dist_for
    req.populate_link(self.finder, upgrade_allowed, require_hashes)
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_install.py", line 249, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python3/dist-packages/pip/_internal/index/package_finder.py", line 926, in find_requirement
    raise DistributionNotFound(
pip._internal.exceptions.DistributionNotFound: No matching distribution found for aalib

From above log, there is pretty obvious the URL https://pypi.org/simple/aalib/ 404 not found. Then you can guess the possible reasons which cause that 404, i.e. wrong package name. Another thing is I can modify relevant python files of pip modules to further debug with above log. To edit .whl file, you can use wheel command to unpack and pack.

Add table row in jQuery

As i have also got a way too add row at last or any specific place so i think i should also share this:

First find out the length or rows:

var r=$("#content_table").length;

and then use below code to add your row:

$("#table_id").eq(r-1).after(row_html);

Add new value to an existing array in JavaScript

This has nothing to do with jQuery, just JavaScript in general.

To create an array in JavaScript:

var a = [];

Or:

var a = ['value1', 'value2', 'value3'];

To append values on the end of existing array:

a.push('value4');

To create a new array, you should really use [] instead of new Array() for the following reasons:

  • new Array(1, 2) is equivalent to [1, 2], but new Array(1) is not equivalent to [1]. Rather the latter is closer to [undefined], since a single integer argument to the Array constructor indicates the desired array length.
  • Array, just like any other built-in JavaScript class, is not a keyword. Therefore, someone could easily define Array in your code to do something other than construct an array.

How to NodeJS require inside TypeScript file?

Typescript will always complain when it is unable to find a symbol. The compiler comes together with a set of default definitions for window, document and such specified in a file called lib.d.ts. If I do a grep for require in this file I can find no definition of a function require. Hence, we have to tell the compiler ourselves that this function will exist at runtime using the declare syntax:

declare function require(name:string);
var sampleModule = require('modulename');

On my system, this compiles just fine.

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

Make sure you're calling super() as the first thing in your constructor.

You should set this for setAuthorState method

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  constructor(props) {
    super(props);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
  } 

  handleAuthorChange(event) {
    let {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Another alternative based on arrow function:

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  handleAuthorChange = (event) => {
    const {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Rounding a variable to two decimal places C#

Console.WriteLine(decimal.Round(pay,2));

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How to find a number in a string using JavaScript?

I like @jesterjunk answer, however, a number is not always just digits. Consider those valid numbers: "123.5, 123,567.789, 12233234+E12"

So I just updated the regular expression:

var regex = /[\d|,|.|e|E|\+]+/g;

var string = "you can enter maximum 5,123.6 choices";
var matches = string.match(regex);  // creates array from matches

document.write(matches); //5,123.6

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Rails - controller action name to string

In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]

Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

How to add /usr/local/bin in $PATH on Mac

I've had the same problem with you.

cd to ../etc/ then use ls to make sure your "paths" file is in , vim paths, add "/usr/local/bin" at the end of the file.

Pass variables from servlet to jsp

This is an servlet code which contain a string variable a. the value for a is getting from an html page with form. then set the variable into the request object. then pass it to jsp using forward and requestdispatcher methods.

String a=req.getParameter("username");
req.setAttribute("name", a);
RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
rd.forward(req, resp);

in jsp follow these steps shown below in the program

<%String name=(String)request.getAttribute("name");
out.print("your name"+name);%>

How to remove the default arrow icon from a dropdown list (select element)?

Try this it works for me,

_x000D_
_x000D_
<style>_x000D_
    select{_x000D_
        border: 0 !important;  /*Removes border*/_x000D_
        -webkit-appearance: none;_x000D_
        -moz-appearance: none;_x000D_
        appearance: none;_x000D_
        text-overflow:'';_x000D_
        text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
        text-overflow: "";  /*Removes default arrow from firefox*/_x000D_
    }_x000D_
    select::-ms-expand {_x000D_
        display: none;_x000D_
    }_x000D_
    .select-wrapper_x000D_
    {_x000D_
        padding-left:0px;_x000D_
        overflow:hidden;_x000D_
    }_x000D_
</style>_x000D_
    _x000D_
<div class="select-wrapper">_x000D_
     <select> ... </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can not hide but using overflow hidden you can actually make it disappear.

Encode URL in JavaScript?

Nothing worked for me. All I was seeing was the HTML of the login page, coming back to the client side with code 200. (302 at first but the same Ajax request loading login page inside another Ajax request, which was supposed to be a redirect rather than loading plain text of the login page).

In the login controller, I added this line:

Response.Headers["land"] = "login";

And in the global Ajax handler, I did this:

$(function () {
    var $document = $(document);
    $document.ajaxSuccess(function (e, response, request) {
        var land = response.getResponseHeader('land');
        var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
        if(land) {
            if (land.toString() === 'login') {
                window.location = redrUrl;
            }
        }
    });
});

Now I don't have any issue, and it works like a charm.

Java : Convert formatted xml file to one line string

Run it through an XSLT identity transform with <xsl:output indent="no"> and <xsl:strip-space elements="*"/>

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="no" />
    <xsl:strip-space elements="*"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

It will remove any of the non-significant whitespace and produce the expected output that you posted.

How to get $(this) selected option in jQuery?

You can use find to look for the selected option that is a descendant of the node(s) pointed to by the current jQuery object:

var cur_value = $(this).find('option:selected').text();

Since this is likely an immediate child, I would actually suggest using .children instead:

var cur_value = $(this).children('option:selected').text();

Enabling/Disabling Microsoft Virtual WiFi Miniport

You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it. After that, you start your cmd with admin privileges, then try:

netsh wlan start hostednetwork

How to split a string into a list?

shlex has a .split() function. It differs from str.split() in that it does not preserve quotes and treats a quoted phrase as a single word:

>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']

NB: it works well for Unix-like command line strings. It doesn't work for natural-language processing.

href around input type submit

Place the link location in the action="" of a wrapping form tag.

Your first link would be:

<form action="1.html">
    <input type="submit" class="button_active" value="1">
</form>

Get the index of the object inside an array, matching a condition

Georg have already mentioned ES6 have Array.findIndex for this. And some other answers are workaround for ES5 using Array.some method.

One more elegant approach can be

var index;
for(index = yourArray.length; index-- > 0 && yourArray[index].prop2 !== "yutu";);

At the same time I will like to emphasize, Array.some may be implemented with binary or other efficient searching technique. So, it might perform better over for loop in some browser.

Set transparent background using ImageMagick and commandline prompt

Using ImageMagick, this is very similar to hackerb9 code and result, but is a little simpler command line. It does assume that the top left pixel is the background color. I just flood fill the background with transparency, then select the alpha channel and blur it and remove half of the blurred area using -level 50x100%. Then turn back on all the channels and flatten it against the brown color. The -blur 0x1 -level 50x100% acts to antialias the boundaries of the alpha channel transparency. You can adjust the fuzz value, blur amount and the -level 50% value to change the degree of antialiasing.

convert logo: -fuzz 25% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x1 -level 50x100% +channel -background saddlebrown -flatten result.jpg

enter image description here

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I was getting the same pathspec error on git-bash. I used Tortoise git on windows to switch/checkout the branch.

ArrayList insertion and retrieval order

Yes, ArrayList is an ordered collection and it maintains the insertion order.

Check the code below and run it:

public class ListExample {

    public static void main(String[] args) {
        List<String> myList = new ArrayList<String>();
        myList.add("one");
        myList.add("two");
        myList.add("three");
        myList.add("four");
        myList.add("five");
    
        System.out.println("Inserted in 'order': ");
        printList(myList);
        System.out.println("\n");
        System.out.println("Inserted out of 'order': ");

        // Clear the list
        myList.clear();
    
        myList.add("four");
        myList.add("five");
        myList.add("one");
        myList.add("two");
        myList.add("three");
    
        printList(myList);
    }

    private static void printList(List<String> myList) {
        for (String string : myList) {
            System.out.println(string);
        }
    }
}

Produces the following output:

Inserted in 'order': 
one
two
three
four
five


Inserted out of 'order': 
four
five
one
two
three

For detailed information, please refer to documentation: List (Java Platform SE7)

How to get local server host and port in Spring Boot?

One solution mentioned in a reply by @M. Deinum is one that I've used in a number of Akka apps:

object Localhost {

  /**
   * @return String for the local hostname
   */
  def hostname(): String = InetAddress.getLocalHost.getHostName

  /**
   * @return String for the host IP address
   */
  def ip(): String = InetAddress.getLocalHost.getHostAddress

}

I've used this method when building a callback URL for Oozie REST so that Oozie could callback to my REST service and it's worked like a charm

Setting paper size in FPDF

/*$mpdf = new mPDF('',    // mode - default ''
 '',    // format - A4, for example, default ''
 0,     // font size - default 0
 '',    // default font family
 15,    // margin_left
 15,    // margin right
 16,     // margin top
 16,    // margin bottom
 9,     // margin header
 9,     // margin footer
 'L');  // L - landscape, P - portrait*/

How to select data where a field has a min value in MySQL?

This is how I would do it (assuming I understand the question)

SELECT * FROM pieces ORDER BY price ASC LIMIT 1

If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.

Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

While many are taking the approach to stop/disable IIS, it may be helpful to know that you can simply modify the XAMPP port, which has been answered here. This is the route I had to take as I need both running.

CSS Display an Image Resized and Cropped

What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.

It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)

Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

    <video controls>
      <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
      <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
      <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
      <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
    </video>

We can add an external HLS js script in web application.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Your title</title>
      
    
      <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
      <script src="https://unpkg.com/video.js/dist/video.js"></script>
      <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
       
    </head>
    <body>
      <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
      data-setup='{}'>
        <source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
      </video>
      
    <script>
    var player = videojs('my_video_1');
    player.play();
    </script>
      
    </body>
    </html>

Jquery Date picker Default Date

While the defaultDate does not set the widget. What is needed is something like:

$(".datepicker").datepicker({
    showButtonPanel: true,
    numberOfMonths: 2

});

$(".datepicker[value='']").datepicker("setDate", "-0d"); 

Javascript: How to check if a string is empty?

I check length.

if (str.length == 0) {
}

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

Path.Combine for URLs?

Path.Combine("Http://MyUrl.com/", "/Images/Image.jpg").Replace("\\", "/")

C# int to byte[]

The other way is to use BinaryPrimitives like so

byte[] intBytes = BitConverter.GetBytes(123); int actual = BinaryPrimitives.ReadInt32LittleEndian(intBytes);

MySQL - SELECT all columns WHERE one column is DISTINCT

If what your asking is to only show rows that have 1 link for them then you can use the following:

SELECT * FROM posted WHERE link NOT IN 
(SELECT link FROM posted GROUP BY link HAVING COUNT(LINK) > 1)

Again this is assuming that you want to cut out anything that has a duplicate link.

Python != operation vs "is not"

First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question".

Definitions

Object identity: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another.

>>> button = Button()
>>> cancel = button
>>> close = button
>>> dismiss = button
>>> print(cancel is close)
True

In this case, cancel, close, and dismiss all refer to the same object in memory. You only created one Button object, and all three variables refer to this one object. We say that cancel, close, and dismiss all refer to identical objects; that is, they refer to one single object.

Object equality: When you compare two objects, you usually don't care that it refers to the exact same object in memory. With object equality, you can define your own rules for how two objects compare. When you write if a == b:, you are essentially saying if a.__eq__(b):. This lets you define a __eq__ method on a so that you can use your own comparison logic.

Rationale for equality comparisons

Rationale: Two objects have the exact same data, but are not identical. (They are not the same object in memory.) Example: Strings

>>> greeting = "It's a beautiful day in the neighbourhood."
>>> a = unicode(greeting)
>>> b = unicode(greeting)
>>> a is b
False
>>> a == b
True

Note: I use unicode strings here because Python is smart enough to reuse regular strings without creating new ones in memory.

Here, I have two unicode strings, a and b. They have the exact same content, but they are not the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the unicode object has implemented the __eq__ method.

class unicode(object):
    # ...

    def __eq__(self, other):
        if len(self) != len(other):
            return False

        for i, j in zip(self, other):
            if i != j:
                return False

        return True

Note: __eq__ on unicode is definitely implemented more efficiently than this.

Rationale: Two objects have different data, but are considered the same object if some key data is the same. Example: Most types of model data

>>> import datetime
>>> a = Monitor()
>>> a.make = "Dell"
>>> a.model = "E770s"
>>> a.owner = "Bob Jones"
>>> a.warranty_expiration = datetime.date(2030, 12, 31)
>>> b = Monitor()
>>> b.make = "Dell"
>>> b.model = "E770s"
>>> b.owner = "Sam Johnson"
>>> b.warranty_expiration = datetime.date(2005, 8, 22)
>>> a is b
False
>>> a == b
True

Here, I have two Dell monitors, a and b. They have the same make and model. However, they neither have the same data nor are the same object in memory. However, when we compare them, we want them to compare equal. What's happening here is that the Monitor object implemented the __eq__ method.

class Monitor(object):
    # ...

    def __eq__(self, other):
        return self.make == other.make and self.model == other.model

Answering your question

When comparing to None, always use is not. None is a singleton in Python - there is only ever one instance of it in memory.

By comparing identity, this can be performed very quickly. Python checks whether the object you're referring to has the same memory address as the global None object - a very, very fast comparison of two numbers.

By comparing equality, Python has to look up whether your object has an __eq__ method. If it does not, it examines each superclass looking for an __eq__ method. If it finds one, Python calls it. This is especially bad if the __eq__ method is slow and doesn't immediately return when it notices that the other object is None.

Did you not implement __eq__? Then Python will probably find the __eq__ method on object and use that instead - which just checks for object identity anyway.

When comparing most other things in Python, you will be using !=.

How would I run an async Task<T> method synchronously?

    private int GetSync()
    {
        try
        {
            ManualResetEvent mre = new ManualResetEvent(false);
            int result = null;

            Parallel.Invoke(async () =>
            {
                result = await SomeCalcAsync(5+5);
                mre.Set();
            });

            mre.WaitOne();
            return result;
        }
        catch (Exception)
        {
            return null;
        }
    }

What is the difference between HTML tags <div> and <span>?

It's plain and simple.

  • use of span does not affect the layout because it's inline(in line (one should not confuse because things could be wrapped))
  • use of div affects the layout, the content inside appears in the new line(block element), when the element you wanna add has no special semantic meaning and you want it to appear in new line use <div>.

How to get a list of installed Jenkins plugins with name and version pair

If you're working in a docker environment and want to output the plugin list in a plugins.txt format in order to pass that to the install_scripts.sh use these scripts in the http://{jenkins}/script console:

  1. This version is useful for getting specific package version
Jenkins.instance.pluginManager.plugins.each{
  plugin -> 
    println ("${plugin.getShortName()}:${plugin.getVersion()}")
}
  1. If you only want the plugin with the latest version you can use this (thanks @KymikoLoco for the tip)
Jenkins.instance.pluginManager.plugins.each{
  plugin -> 
    println ("${plugin.getShortName()}:latest")
}

JavaScript and Threads

If you can't or don't want to use any AJAX stuff, use an iframe or ten! ;) You can have processes running in iframes in parallel with the master page without worrying about cross browser comparable issues or syntax issues with dot net AJAX etc, and you can call the master page's JavaScript (including the JavaScript that it has imported) from an iframe.

E.g, in a parent iframe, to call egFunction() in the parent document once the iframe content has loaded (that's the asynchronous part)

parent.egFunction();

Dynamically generate the iframes too so the main html code is free from them if you want.