Programs & Examples On #Traffic simulation

Center a position:fixed element

I used vw (viewport width) and vh (viewport height). viewport is your entire screen. 100vw is your screens total width and 100vh is total height.

.class_name{
    width: 50vw;
    height: 50vh;
    border: 1px solid red;
    position: fixed;
    left: 25vw;top: 25vh;   
}

Postgres ERROR: could not open file for reading: Permission denied

chmod a+rX /users/darchcruise/ /users/darchcruise/desktop /users/darchcruise/desktop/items_ordered.csv

This will change access rights for your folder. Note that everyone will be able to read your file. You can't use chown being a user without administrative rights. Also consider learning umask to ease creation of shared files.

Angular : Manual redirect to route

You may have enough correct answers for your question but in case your IDE gives you the warning

Promise returned from navigate is ignored

you may either ignore that warning or use this.router.navigate(['/your-path']).then().

How to get Toolbar from fragment?

Maybe you have to try getActivity().getSupportActionBar().setTitle() if you are using support_v7.

How do I remove diacritics (accents) from a string in .NET?

Popping this Library here if you haven't already considered it. Looks like there are a full range of unit tests with it.

https://github.com/thomasgalliker/Diacritics.NET

assigning column names to a pandas series

You can also use the .to_frame() method.

If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name argument of .to_frame() will name the column.

x = x.to_frame('count')

If you want them both as columns, you can reset the index:

x = x.to_frame('count').reset_index()

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

Sqlite convert string to date

convert a string into date little issue think with indexing mmm 3,3 but works added a month on to the date string

SELECT substr('12Jan20',1,2) as dday,
date(substr('12Jan20',6,7) ||'00-' || case substr('12Jan20',3,3) when 'Jan' then '01'
when 'Feb' then '02'
when 'Mar' then '03'
when 'Apr' then '04'
when 'May' then '05' 
when 'Jun' then '06'
when 'Jul' then '07'
when 'Aug' then '08'
when 'Sep' then '09'
when 'Oct' then '10'
when 'Nov' then '11'
when 'Dec' then '12' end  || '-'||substr('12Jan20',1,2), '+1 month') as tt

Generate random 5 characters string

I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:

function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
    $letters = str_split($abc);
    $str = "";
    for ($i=0; $i<=$len; $i++) {
        $str .= $letters[rand(0, count($letters)-1)];
    };
    return $str;
};

You can use this function like this

randstr(20)     // returns a random 20 letter string
                // Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"

Get name of current class?

Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.

I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:

class InputAssigningMetaclass(type):
    def __new__(cls, name, bases, attrs):
        cls.input = get_input(name)
        return super(MyType, cls).__new__(cls, name, bases, newattrs)

class MyBaseFoo(object):
    __metaclass__ = InputAssigningMetaclass

class foo(MyBaseFoo):
    # etc, no need to create 'input'

class foo2(MyBaseFoo):
    # etc, no need to create 'input'

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Is there a user account entry in the DB for root@localhost? In MySQL you can set different user account permissions by host. There could be several different accounts with the same name combined with the host they are connecting from. The most common are [email protected] and root@localhost. These can have different passwords and permissions. Make sure root@localhost exist and has the settings you expect.

I am willing to bet, based on your explanation, that this is the problem. Connecting from another PC uses a different account than root@localhost and the command line I think connects using [email protected].

How to sort an array of objects by multiple fields?

homes.sort(function(a,b) { return a.city - b.city } );
homes.sort(function(a,b){
    if (a.city==b.city){
        return parseFloat(b.price) - parseFloat(a.price);
    } else {
        return 0;
    }
});

Given the lat/long coordinates, how can we find out the city/country?

Please check the below answer. It works for me

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){

        initialize(position.coords.latitude,position.coords.longitude);
    }); 
}

function initialize(lat,lng) {
    //directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    //directionsService = new google.maps.DirectionsService();
    var latlng = new google.maps.LatLng(lat, lng);

    //alert(latlng);
    getLocation(latlng);
}

function getLocation(latlng){

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                    alert("location is::"+loc);
                }
            }
        });

}

function getCountry(results)
{
    for (var i = 0; i < results[0].address_components.length; i++)
    {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}

How to disable SSL certificate checking with Spring RestTemplate?

Disabling certificate checking is the wrong solution, and radically insecure.

The correct solution is to import the self-signed certificate into your truststore. An even more correct solution is to get the certificate signed by a CA.

If this is 'only for testing' it is still necessary to test the production configuration. Testing something else isn't a test at all, it's just a waste of time.

Best way to test for a variable's existence in PHP; isset() is clearly broken

I don't agree with your reasoning about NULL, and saying that you need to change your mindset about NULL is just weird.

I think isset() was not designed correctly, isset() should tell you if the variable has been set and it should not be concerned with the actual value of the variable.

What if you are checking values returned from a database and one of the columns have a NULL value, you still want to know if it exists even if the value is NULL...nope dont trust isset() here.

likewise

$a = array ('test' => 1, 'hello' => NULL);

var_dump(isset($a['test']));   // TRUE
var_dump(isset($a['foo']));    // FALSE
var_dump(isset($a['hello']));  // FALSE

isset() should have been designed to work like this:

if(isset($var) && $var===NULL){....

this way we leave it up to the programmer to check types and not leave it up to isset() to assume its not there because the value is NULL - its just stupid design

"Exception has been thrown by the target of an invocation" error (mscorlib)

Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014

enter image description here

The reason was backward compatibility

So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.

Problem Solve!!

int to string in MySQL

You could use CONCAT, and the numeric argument of it is converted to its equivalent binary string form.

select t2.* 
from t1 join t2 
on t2.url=CONCAT('site.com/path/%', t1.id, '%/more') where t1.id > 9000

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

Git workflow and rebase vs merge questions

I have one question after reading your explanation: Could it be that you never did a

git checkout master
git pull origin
git checkout my_new_feature

before doing the 'git rebase/merge master' in your feature branch?

Because your master branch won't update automatically from your friend's repository. You have to do that with the git pull origin. I.e. maybe you would always rebase from a never-changing local master branch? And then come push time, you are pushing in a repository which has (local) commits you never saw and thus the push fails.

Convert XML to JSON (and back) using Javascript

I would personally recommend this tool. It is an XML to JSON converter.

It is very lightweight and is in pure JavaScript. It needs no dependencies. You can simply add the functions to your code and use it as you wish.

It also takes the XML attributes into considerations.

var xml = ‘<person id=”1234” age=”30”><name>John Doe</name></person>’;
var json = xml2json(xml); 

console.log(json); 
// prints ‘{“person”: {“id”: “1234”, “age”: “30”, “name”: “John Doe”}}’

Here's an online demo!

How to use a variable inside a regular expression?

From python 3.6 on you can also use Literal String Interpolation, "f-strings". In your particular case the solution would be:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

EDIT:

Since there have been some questions in the comment on how to deal with special characters I'd like to extend my answer:

raw strings ('r'):

One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:

In short:

Let's say instead of finding a word boundary \b after TEXTO you want to match the string \boundary. The you have to write:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

This only works because we are using a raw-string (the regex is preceded by 'r'), otherwise we must write "\\\\boundary" in the regex (four backslashes). Additionally, without '\r', \b' would not converted to a word boundary anymore but to a backspace!

re.escape:

Basically puts a backspace in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

NOTE: For any version >= python 3.7: !, ", %, ', ,, /, :, ;, <, =, >, @, and ` are not escaped. Only special characters with meaning in a regex are still escaped. _ is not escaped since Python 3.3.(s. here)

Curly braces:

If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let's say you want to match TEXTO followed by exactly 2 digits:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

Download image with JavaScript

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

Import JSON file in React

there are multiple ways to do this without using any third-party code or libraries (the recommended way).

1st STATIC WAY: create a .json file then import it in your react component example

my file name is "example.json"

{"example" : "my text"}

the example key inside the example.json can be anything just keep in mind to use double quotes to prevent future issues.

How to import in react component

import myJson from "jsonlocation";

and you can use it anywhere like this

myJson.example

now there are a few things to consider. With this method, you are forced to declare your import at the top of the page and cannot dynamically import anything.

Now, what about if we want to dynamically import the JSON data? example a multi-language support website?

2 DYNAMIC WAY

1st declare your JSON file exactly like my example above

but this time we are importing the data differently.

let language = require('./en.json');

this can access the same way.

but wait where is the dynamic load?

here is how to load the JSON dynamically

let language = require(`./${variable}.json`);

now make sure all your JSON files are within the same directory

here you can use the JSON the same way as the first example

myJson.example

what changed? the way we import because it is the only thing we really need.

I hope this helps.

Can't type in React input text field

i'm also facing that problem now solved.Give the onChange to the searchTool. then that problem will solve for you.

How can I search an array in VB.NET?

This would do the trick, returning the values at indeces 0, 2 and 3.

Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

Get visible items in RecyclerView

Addendum:

The proposed functions findLast...Position() do not work correctly in a scenario with a collapsing toolbar while the toolbar is expanded.

It seems that the recycler view has a fixed height, and while the toolbar is expanded, the recycler is moved down, partially out of the screen. As a consequence the results of the proposed functions are too high. Example: The last visible item is told to be #9, but in fact item #7 is the last one that is on screen.

This behaviour is also the reason why my view often failed to scroll to the correct position, i.e. scrollToPosition() did not work correctly (I finally collapsed the toolbar programmatically).

can you host a private repository for your organization to use with npm?

Forgive me if I don't understand your question well, but here's my answer:

You can create a private npm module and use npm's normal commands to install it. Most node.js users use git as their repository, but you can use whatever repository works for you.

  1. In your project, you'll want the skeleton of an NPM package. Most node modules have git repositories where you can look at how they integrate with NPM (the package.json file, I believe is part of this and NPM's website shows you how to make a npm package)
  2. Use something akin to Make to make and tarball your package to be available from the internet or your network to stage it for npm install downloads.
  3. Once your package is made, then use

    npm install *tarball_url*

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

How does DateTime.Now.Ticks exactly work?

to convert the current datetime to file name to save files you can use

DateTime.Now.ToFileTime();

this should resolve your objective

DateTime group by date and hour

SELECT [activity_dt], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [activity_dt]), '20010101') as [activity_dt]
    FROM table) abc
 GROUP BY [activity_dt]

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, this happens when I try to save an object in hibernate or other orm-mapping with null property which can not be null in database table. This happens when you try to save an object, but the save action doesn't comply with the contraints of the table.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

In your Activity.java import android.support.v7.widget.Toolbar instead of android.widget.Toolbar:

import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;


public class rutaActivity extends AppCompactActivity {

private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ruta);

    getSupportActionBar().hide();//Ocultar ActivityBar anterior

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar); //NO PROBLEM !!!!

Update:

If you are using androidx, replace

import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;

with newer imports

import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;

Calculate the date yesterday in JavaScript

d.setHours(0,0,0,0);

will do the trick

How to count down in for loop?

If you google. "Count down for loop python" you get these, which are pretty accurate.

how to loop down in python list (countdown)
Loop backwards using indices in Python?

I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.

git switch branch without discarding local changes

  • git stash to save your uncommited changes
  • git stash list to list your saved uncommited stashes
  • git stash apply stash@{x} where x can be 0,1,2..no of stashes that you have made

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I faced the same issue although i added [System.Web.Mvc.AllowHtml] to the concerning property as described in some answers.

In my case, i have an UnhandledExceptionFilter class that accesses the Request object before MVC validation takes place (and therefore AllowHtml has not effect) and this access raises a [HttpRequestValidationException] A potentially dangerous Request.Form value was detected from the client.

This means, accessing certain properties of a Request object implicitly fires validation (in my case its the Params property).

A solution to prevent validation is documented on MSDN

To disable request validation for a specific field in a request (for example, for an input element or query string value), call the Request.Unvalidated method when you get the item, as shown in the following example

Therefore, if you have code like this

var lParams = aRequestContext.HttpContext.Request.Params;
if (lParams.Count > 0)
{
  ...

change it to

var lUnvalidatedRequest = aRequestContext.HttpContext.Request.Unvalidated;

var lForm = lUnvalidatedRequest.Form;
if (lForm.Count > 0)
{
  ...

or just use the Form property which does not seem to fire validation

var lForm = aRequestContext.HttpContext.Request.Form;
if (lForm.Count > 0)
{
  ...

Comment out HTML and PHP together

Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:

<?php /*
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
*/ ?>


With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.


Just one note: you cannot nest C-style comments... which means the comment will end at the first */ encountered.

What is a callback?

Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.

An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.

C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.

How to copy file from one location to another location?

Files.exists()

Files.createDirectory()

Files.copy()

Overwriting Existing Files: Files.move()

Files.delete()

Files.walkFileTree() enter link description here

Update GCC on OSX

The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:

$ brew tap SynthiNet/synthinet
$ brew install gcc47

Found it on a post here.

Confirmation before closing of tab/browser

I read comments on answer set as Okay. Most of the user are asking that the button and some links click should be allowed. Here one more line is added to the existing code that will work.

<script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {

      return "Did you save your stuff?"
    }
  }
  function unhook() {
    hook=false;
  }

Call unhook() onClick for button and links which you want to allow. E.g.

<a href="#" onClick="unhook()">This link will allow navigation</a>

How to run only one unit test class using Gradle

In my case, my eclipse java compiler warnings were set too high, and eclipse was not recognizing my class as valid for execution. Updating my compiler settings fixed the problem. You can read more about it here: annotation-nonnull-cannot-be-resolved

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.

i.e:

datetime.Value

but check to see if it has a value first!

if (datetime.HasValue)
{
   // work with datetime.Value
}

VB.NET: how to prevent user input in a ComboBox

Seeing a user banging away at a control that overrides her decisions is a sad sight. Set the control's Enabled property to False. If you don't like that then change its Items property so only one item is selectable.

How to remove leading zeros using C#

It really depends on how long the NVARCHAR is, as a few of the above (especially the ones that convert through IntXX) methods will not work for:

String s = "005780327584329067506780657065786378061754654532164953264952469215462934562914562194562149516249516294563219437859043758430587066748932647329814687194673219673294677438907385032758065763278963247982360675680570678407806473296472036454612945621946";

Something like this would

String s ="0000058757843950000120465875468465874567456745674000004000".TrimStart(new Char[] { '0' } );
// s = "58757843950000120465875468465874567456745674000004000"

How to delete file from public folder in laravel 5.1

You could use PHP's unlink() method just as @Khan suggested.

But if you want to do it the Laravel way, use the File::delete() method instead.

// Delete a single file

File::delete($filename);

// Delete multiple files

File::delete($file1, $file2, $file3);

// Delete an array of files

$files = array($file1, $file2);
File::delete($files);

And don't forget to add at the top:

use Illuminate\Support\Facades\File; 

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

JS regex: replace all digits in string

You need to add the "global" flag to your regex:

s.replace(new RegExp("[0-9]", "g"), "X")

or, perhaps prettier, using the built-in literal regexp syntax:

.replace(/[0-9]/g, "X")

How to draw a line in android

You can make a drawable like circle, line, rectangle etc through shapes in xml as follow:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="line" >

    <solid android:color="#00000000" />

    <stroke
        android:width="2dp"
        android:color="#808080" />

</shape>

Maven dependency for Servlet 3.0 API?

Place this dependency, and dont forget to select : Include dependencies with "provided" scope

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>

How to get last inserted row ID from WordPress database?

Something like this should do it too :

$last = $wpdb->get_row("SHOW TABLE STATUS LIKE 'table_name'");
$lastid = $last->Auto_increment;

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

ValueError: invalid literal for int () with base 10

Please test this function (split()) on a simple file. I was facing the same issue and found that it was because split() was not written properly (exception handling).

Access PHP variable in JavaScript

I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>

And then in your JavaScript:

var size_of_widget = document.getElementById("metadata-size-of-widget").title;

How to convert a String to a Date using SimpleDateFormat?

You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,

mm stands for minutes, use MM as it is for Months

DD is wrong, it should be dd which represents Days

Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011 ),

    String date = "08/16/2011"; //input date as String

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern

    Date myDate = simpleDateFormat.parse(date); // returns date object 

    System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011

How to detect when keyboard is shown and hidden

Swift - 4

override func viewWillAppear(_ animated: Bool) {
   super.viewWillAppear(animated)
   addKeyBoardListener()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self) //remove observer
}

func addKeyBoardListener() {
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
}

@objc func keyboardWillShow(_ notification: Notification) {

}

@objc func keyboardWillHide(_ notification: Notification) {

}

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Getting each individual digit from a whole integer

You use the modulo operator:

while(score)
{
    printf("%d\n", score % 10);
    score /= 10;
}

Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Check whether your config string is okay:

Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999

I just had this issue today, and in my case it was because there was an invisible character in the jpda config parameter.

To be precise, I had dos line endings in my setenv.sh file on tomcat, causing a carriage-return character right after 'dt_socket'

vuetify center items into v-flex

v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.

So, you should override it with display: flex in your HTML or CSS to make it work with justify-content.

Seeding the random number generator in Javascript

NOTE: Despite (or rather, because of) succinctness and apparent elegance, this algorithm is by no means a high-quality one in terms of randomness. Look for e.g. those listed in this answer for better results.

(Originally adapted from a clever idea presented in a comment to another answer.)

var seed = 1;
function random() {
    var x = Math.sin(seed++) * 10000;
    return x - Math.floor(x);
}

You can set seed to be any number, just avoid zero (or any multiple of Math.PI).

The elegance of this solution, in my opinion, comes from the lack of any "magic" numbers (besides 10000, which represents about the minimum amount of digits you must throw away to avoid odd patterns - see results with values 10, 100, 1000). Brevity is also nice.

It's a bit slower than Math.random() (by a factor of 2 or 3), but I believe it's about as fast as any other solution written in JavaScript.

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

How to Generate unique file names in C#

If the readability of the file name isn't important, then the GUID, as suggested by many will do. However, I find that looking into a directory with 1000 GUID file names is very daunting to sort through. So I usually use a combination of a static string which gives the file name some context information, a timestamp, and GUID.

For example:

public string GenerateFileName(string context)
{
    return context + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N");
}

filename1 = GenerateFileName("MeasurementData");
filename2 = GenerateFileName("Image");

This way, when I sort by filename, it will automatically group the files by the context string and sort by timestamp.

Note that the filename limit in windows is 255 characters.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won't work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
             ^
SyntaxError: invalid syntax

Removing cordova plugins from the project

This is somewhat related and might help others, I had a corrupt version of some of my plugins so I was able to just delete the entire contents of the plugins folder. Note, all references are still in the package.json and config.xml files to the plugins. So then when I removed and added the Android platform, it re-installed the uncorrupted versions of the plugins and fixed my problem.

Foreign key referring to primary keys across multiple tables?

Assuming you must have two tables for the two employee types for some reason, I'll extend on vmarquez's answer:

Schema:

employees_ce (id, name)
employees_sn (id, name)
deductions (id, parentId, parentType, name)

Data in deductions:

deductions table
id      parentId      parentType      name
1       1             ce              gold
2       1             sn              silver
3       2             sn              wood
...

This would allow you to have deductions point to any other table in your schema. This kind of relation isn't supported by database-level constraints, IIRC so you'll have to make sure your App manages the constraint properly (which makes it more cumbersome if you have several different Apps/services hitting the same database).

number of values in a list greater than a certain number

Different way of counting by using bisect module:

>>> from bisect import bisect
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> j.sort()
>>> b = 5
>>> index = bisect(j,b) #Find that index value
>>> print len(j)-index
3

Taking multiple inputs from user in python

The best way to practice by using a single liner,
Syntax:

list(map(inputType, input("Enter").split(",")))

Taking multiple integer inputs:

   list(map(int, input('Enter: ').split(',')))

enter image description here

Taking multiple Float inputs:

list(map(float, input('Enter: ').split(',')))

enter image description here

Taking multiple String inputs:

list(map(str, input('Enter: ').split(',')))

enter image description here

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

Use header to modify the HTTP header:

header('Content-Type: text/html; charset=utf-8');

Note to call this function before any output has been sent to the client. Otherwise the header has been sent too and you obviously can’t change it any more. You can check that with headers_sent. See the manual page of header for more information.

How to fix libeay32.dll was not found error

I encountered the same problem when I tried to install curl in my 32 bit win 7 machine. As answered by Buravchik it is indeed dependency of SSL and installing openssl fixed it. Just a point to take care is that while installing openssl you will get a prompt to ask where do you wish to put the dependent DLLS. Make sure to put it in windows system directory as other programs like curl and wget will also be needing it.

enter image description here

How to ignore a property in class if null, using json.net

To expound slightly on GlennG's very helpful answer (translating the syntax from C# to VB.Net is not always "obvious") you can also decorate individual class properties to manage how null values are handled. If you do this don't use the global JsonSerializerSettings from GlennG's suggestion, otherwise it will override the individual decorations. This comes in handy if you want a null item to appear in the JSON so the consumer doesn't have to do any special handling. If, for example, the consumer needs to know an array of optional items is normally available, but is currently empty... The decoration in the property declaration looks like this:

<JsonPropertyAttribute("MyProperty", DefaultValueHandling:=NullValueHandling.Include)> Public Property MyProperty As New List(of String)

For those properties you don't want to have appear at all in the JSON change :=NullValueHandling.Include to :=NullValueHandling.Ignore. By the way - I've found that you can decorate a property for both XML and JSON serialization just fine (just put them right next to each other). This gives me the option to call the XML serializer in dotnet or the NewtonSoft serializer at will - both work side-by-side and my customers have the option to work with XML or JSON. This is slick as snot on a doorknob since I have customers that require both!

Append a dictionary to a dictionary

There is the .update() method :)

update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.

Don't understand why UnboundLocalError occurs (closure)

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they're declared global with the global keyword).

A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can't modify the binding in the enclosing environment.

In your case you are trying to treat counter as a local variable rather than a bound value. Note that this code, which binds the value of x assigned in the enclosing environment, works fine:

>>> x = 1

>>> def f():
>>>  return x

>>> f()
1

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

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
        }
    }
    catch (WebException ex) {
        // Log exception and throw as for GET example above
    }
}

I use code like this in automated tests of our web service.

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

The AngularJS documentation on directives is pretty well written for what the symbols mean.

To be clear, you cannot just have

scope: '@'

in a directive definition. You must have properties for which those bindings apply, as in:

scope: {
    myProperty: '@'
}

I strongly suggest you read the documentation and the tutorials on the site. There is much more information you need to know about isolated scopes and other topics.

Here is a direct quote from the above-linked page, regarding the values of scope:

The scope property can be true, an object or a falsy value:

  • falsy: No scope will be created for the directive. The directive will use its parent's scope.

  • true: A new child scope that prototypically inherits from its parent will be created for the directive's element. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.

  • {...} (an object hash): A new "isolate" scope is created for the directive's element. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

Retrieved 2017-02-13 from https://code.angularjs.org/1.4.11/docs/api/ng/service/$compile#-scope-, licensed as CC-by-SA 3.0

How to append to a file in Node?

I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)

  fs.open('log.txt', 'a', function(err, log) {
    if (err) throw err;
    fs.writeFile(log, 'Hello Node', function (err) {
      if (err) throw err;
      fs.close(log, function(err) {
        if (err) throw err;
        console.log('It\'s saved!');
      });
    });
  });

Multiprocessing vs Threading Python

Process may have multiple threads. These threads may share memory and are the units of execution within a process.

Processes run on the CPU, so threads are residing under each process. Processes are individual entities which run independently. If you want to share data or state between each process, you may use a memory-storage tool such as Cache(redis, memcache), Files, or a Database.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

Here are shortcuts for the IPython Notebook.

Ctrl-m i interrupts the kernel. (that is, the sole letter i after Ctrl-m)

According to this answer, I twice works as well.

PHP - how to create a newline character?

Strings between double quotes "" interpolate, meaning they convert escaped characters to printable characters.

Strings between single quotes '' are literal, meaning they are treated exactly as the characters are typed in.

You can have both on the same line:

echo '$clientid $lastname ' . "\r\n";
echo "$clientid $lastname \r\n";

outputs:

$clientid $lastname
1 John Doe

<hr> tag in Twitter Bootstrap not functioning correctly?

By default, the hr element in Twitter Bootstrap CSS file has a top and bottom margin of 18px. That's what creates a gap. If you want the gap to be smaller you'll need to adjust margin property of the hr element.

In your example, do something like this:

.container hr {
margin: 2px 0;
}

How to decompile to java files intellij idea

You could use one of these (you can both use them online or download them, there is some info about each of them) : http://www.javadecompilers.com/

The one IntelliJ IDEA uses is fernflower, but it can't handle recent things - like String/Enum switches, generics (didn't test this one personally, only read about it), ... I just tried cfr from the above website and the result was the same as with the built-in decompiler (except for the Enum switch I had in my class).

HashMap get/put complexity

I'm not sure the default hashcode is the address - I read the OpenJDK source for hashcode generation a while ago, and I remember it being something a bit more complicated. Still not something that guarantees a good distribution, perhaps. However, that is to some extent moot, as few classes you'd use as keys in a hashmap use the default hashcode - they supply their own implementations, which ought to be good.

On top of that, what you may not know (again, this is based in reading source - it's not guaranteed) is that HashMap stirs the hash before using it, to mix entropy from throughout the word into the bottom bits, which is where it's needed for all but the hugest hashmaps. That helps deal with hashes that specifically don't do that themselves, although i can't think of any common cases where you'd see that.

Finally, what happens when the table is overloaded is that it degenerates into a set of parallel linked lists - performance becomes O(n). Specifically, the number of links traversed will on average be half the load factor.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:

<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>

Convert string to JSON array

It's a very simple way to convert:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;


class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Integer getCredits() {
    return credits;
}

public void setCredits(Integer credits) {
    this.credits = credits;
}

public String getTwitter_username() {
    return twitter_username;
}

public void setTwitter_username(String twitter_username) {
    this.twitter_username = twitter_username;
}

@Override
public String toString() {
    return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}

}

/*
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"[email protected]","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"[email protected]"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"[email protected]"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"[email protected]"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
    Gson gson = new Gson();
    try {
        BufferedReader br = new BufferedReader(new FileReader(
                "C:\\Temp\\jsonFileArr.json"));
        JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonElement str = jsonArray.get(i);
            Usuario obj = gson.fromJson(str, Usuario.class);
            System.out.println(obj);
            System.out.println(str);
            System.out.println("-------");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Get the distance between two geo points

a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)

c = 2 · atan2( va, v(1-a) )

distance = R · c

where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);

note that angles need to be in radians to pass to trig functions!

fun distanceInMeter(firstLocation: Location, secondLocation: Location): Double {
    val earthRadius = 6371000.0
    val deltaLatitudeDegree = (firstLocation.latitude - secondLocation.latitude) * Math.PI / 180f
    val deltaLongitudeDegree = (firstLocation.longitude - secondLocation.longitude) * Math.PI / 180f
    val a = sin(deltaLatitudeDegree / 2).pow(2) +
            cos(firstLocation.latitude * Math.PI / 180f) * cos(secondLocation.latitude * Math.PI / 180f) *
            sin(deltaLongitudeDegree / 2).pow(2)
    val c = 2f * atan2(sqrt(a), sqrt(1 - a))
    return earthRadius * c
}


data class Location(val latitude: Double, val longitude: Double)

Sort columns of a dataframe by column name

test = data.frame(C=c(0,2,4, 7, 8), A=c(4,2,4, 7, 8), B=c(1, 3, 8,3,2))

Using the simple following function replacement can be performed (but only if data frame does not have many columns):

test <- test[, c("A", "B", "C")]

for others:

test <- test[, c("B", "A", "C")]

Global Git ignore

  1. Create a .gitignore file in your home directory
touch ~/.gitignore
  1. Add files to it (folders aren't recognised)

Example

# these work
*.gz
*.tmproj
*.7z

# these won't as they are folders
.vscode/
build/

# but you can do this
.vscode/*
build/*
  1. Check if a git already has a global gitignore
git config --get core.excludesfile
  1. Tell git where the file is
git config --global core.excludesfile '~/.gitignore'

Voila!!

Corrupted Access .accdb file: "Unrecognized Database Format"

Well, I have tried something I hope it helps ..

They changed the schema a little bit ..

Use the following :

1- Change the AccessDataSource to SQLDataSource in the toolbox.

2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)

3- Next -> Next -> Test Query -> Finish.

Worked for me.

Remove All Event Listeners of Specific Type

You could alternatively overwrite the 'yourElement.addEventListener()' method and use the '.apply()' method to execute the listener like normal, but intercepting the function in the process. Like:

<script type="text/javascript">

    var args = [];
    var orginalAddEvent = yourElement.addEventListener;

    yourElement.addEventListener = function() {
        //console.log(arguments);
        args[args.length] = arguments[0];
        args[args.length] = arguments[1];
        orginalAddEvent.apply(this, arguments);
    };

    function removeListeners() {
        for(var n=0;n<args.length;n+=2) {
            yourElement.removeEventListener(args[n], args[n+1]);
        }
    }

    removeListeners();

</script>

This script must be run on page load or it might not intercept all event listeners.

Make sure to remove the 'removeListeners()' call before using.

How to capture no file for fs.readFileSync()?

Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:

const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);

const readContentFile = async (filePath) => {
  // Eureka, you are using good code practices here!
  const content = await readFileAsync(path.join(__dirname, filePath), {
    encoding: 'utf8'
  })
  return content;
}

Later can use this async function with try/catch from any other function:

const anyOtherFun = async () => {
  try {
    const fileContent = await readContentFile('my-file.txt');
  } catch (err) {
    // Here you get the error when the file was not found,
    // but you also get any other error
  }
}

Happy Coding!

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

How to extend an existing JavaScript array with another array, without creating a new array

Use Array.extend instead of Array.push for > 150,000 records.

if (!Array.prototype.extend) {
  Array.prototype.extend = function(arr) {
    if (!Array.isArray(arr)) {
      return this;
    }

    for (let record of arr) {
      this.push(record);
    }

    return this;
  };
}

use jQuery's find() on JSON object

You can use JSONPath

Doing something like this:

results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")

Note that JSONPath returns an array of results

(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Try sorting index after concatenating them

result=pd.concat([df1,df2]).sort_index()

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

VB.NET - How to move to next item a For Each Loop?

What about:

If Not I = x Then

  ' Do something '

End If

' Move to next item '

How do I set GIT_SSL_NO_VERIFY for specific repos only?

If you are on a Windows machine and have the Git installed, you can try the below steps:

  1. Go to the folder of Git installation, ex: C:\Program Files (x86)\Git\etc
  2. Edit the file: gitconfig
  3. Under the [http] section, add the line: sslVerify = false

    [http]
      sslVerify = false
    

Upload Image using POST form data in Python-requests

Use this snippet

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)

Convert UTC/GMT time to local time

This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!

CreatedDate.ToUniversalTime().ToLocalTime();

Java - How to find the redirected url of a url?

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );

Stop absolutely positioned div from overlapping text

You should set z-index to absolutely positioned div that is greater than to relative div.

Something like that

<div style="position: relative; width:600px; z-index: 10;">
    <p>Content of unknown length</p>
    <div>Content of unknown height</div>
    <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px; z-index: 20;"></div>
</div>

z-index sets layers positioning in depth of page.

Or you may use floating to show all text of unkown length. But in this case you could not absolutely position your div

<div style="position: relative; width:600px;">
  <div class="btn" style="float: right; width: 200px; height: 100px;"></div>
  <p>Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length</p>
  <div>Content of unknown height</div>
  <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>
</div>?

Pass Javascript Variable to PHP POST

Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.

How can I clear an HTML file input with JavaScript?

I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

all the credit goes to Chris Coyier.

_x000D_
_x000D_
// Referneces_x000D_
var control = $("#control"),_x000D_
    clearBn = $("#clear");_x000D_
_x000D_
// Setup the clear functionality_x000D_
clearBn.on("click", function(){_x000D_
    control.replaceWith( control.val('').clone( true ) );_x000D_
});_x000D_
_x000D_
// Some bound handlers to preserve when cloning_x000D_
control.on({_x000D_
    change: function(){ console.log( "Changed" ) },_x000D_
     focus: function(){ console.log(  "Focus"  ) }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="control">_x000D_
<br><br>_x000D_
<a href="#" id="clear">Clear</a>
_x000D_
_x000D_
_x000D_

C#: how to get first char of a string?

You can use LINQ

char c = mystring.FirstOrDefault()

It will be equal to '\0' if the string is empty.

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Probably, you need to insert schema identifier here:

in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");

Authenticated HTTP proxy with Java

Try this runner I wrote. It could be helpful.

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

public class ProxyAuthHelper {

    public static void main(String[] args) throws Exception {
        String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
        if (tmp == null) {
            System.out.println("Proxy username: ");
            tmp = new Scanner(System.in).nextLine();
        }
        final String userName = tmp;

        tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
        if (tmp == null) {
            System.out.println("Proxy password: ");
            tmp = new Scanner(System.in).nextLine();
        }
        final char[] password = tmp.toCharArray();

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                System.out.println("\n--------------\nProxy auth: " + userName);
                return new PasswordAuthentication (userName, password);
            }

         });

        Class<?> clazz = Class.forName(args[0]);
        Method method = clazz.getMethod("main", String[].class);
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, newArgs.length);
        method.invoke(null, new Object[]{newArgs});
    }

}

How to get the integer value of day of week

If you want to set first day of the week to Monday with integer value 1 and Sunday with integer value 7

int day = ((int)DateTime.Now.DayOfWeek == 0) ? 7 : (int)DateTime.Now.DayOfWeek;

how to run two commands in sudo?

If you would like to handle quotes:

sudo -s -- <<EOF
id
pwd
echo "Done."
EOF

How can one check to see if a remote file exists using PHP?

PHP's inbuilt functions may not work for checking URL if allow_url_fopen setting is set to off for security reasons. Curl is a better option as we would not need to change our code at later stage. Below is the code I used to verify a valid URL:

$url = str_replace(' ', '%20', $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
curl_close($ch);
if($httpcode>=200 && $httpcode<300){  return true; } else { return false; } 

Kindly note the CURLOPT_SSL_VERIFYPEER option which also verify the URL's starting with HTTPS.

How to display a database table on to the table in the JSP page

Tracking ID Track
    <br>
    <%String id = request.getParameter("track_id");%>
       <%if (id.length() == 0) {%>
    <b><h1>Please Enter Tracking ID</h1></b>
    <% } else {%>
    <div class="container">
        <table border="1" class="table" >
            <thead>
                <tr class="warning" >
                    <td ><h4>Track ID</h4></td>
                    <td><h4>Source</h4></td>
                    <td><h4>Destination</h4></td>
                    <td><h4>Current Status</h4></td>

                </tr>
            </thead>
            <%
                try {
                    connection = DriverManager.getConnection(connectionUrl + database, userid, password);
                    statement = connection.createStatement();
                    String sql = "select * from track where track_id="+ id;
                    resultSet = statement.executeQuery(sql);
                    while (resultSet.next()) {
            %>
            <tr class="info">
                <td><%=resultSet.getString("track_id")%></td>
                <td><%=resultSet.getString("source")%></td>
                <td><%=resultSet.getString("destination")%></td>
                <td><%=resultSet.getString("status")%></td>
            </tr>
            <%
                    }
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            %>
        </table>

        <%}%>
</body>

Removing viewcontrollers from navigation stack

I wrote an extension with method which removes all controllers between root and top, unless specified otherwise.

extension UINavigationController {
func removeControllers(between start: UIViewController?, end: UIViewController?) {
    guard viewControllers.count > 1 else { return }
    let startIndex: Int
    if let start = start {
        guard let index = viewControllers.index(of: start) else {
            return
        }
        startIndex = index
    } else {
        startIndex = 0
    }

    let endIndex: Int
    if let end = end {
        guard let index = viewControllers.index(of: end) else {
            return
        }
        endIndex = index
    } else {
        endIndex = viewControllers.count - 1
    }
    let range = startIndex + 1 ..< endIndex
    viewControllers.removeSubrange(range)
}

}

If you want to use range (for example: 2 to 5) you can just use

    let range = 2 ..< 5
    viewControllers.removeSubrange(range)

Tested on iOS 12.2, Swift 5

MySQL Workbench Edit Table Data is read only

MySQL will run in Read-Only mode when you fetch by joining two tables and columns from two tables are included in the result. Then you can't update the values directly.

javax.servlet.ServletException cannot be resolved to a type in spring web app

<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.2-b02</version>
    <scope>provided</scope>
</dependency>

worked for me.

javascript close current window

In JavaScript, we can close a window only if it is opened by using window.open method:

window.open('https://www.google.com');
window.close();

But to close a window which has not been opened using window.open(), you must

  1. Open any other URL or a blank page in the same tab
  2. Close this newly opened tab (this will work because it was opened by window.open())
window.open("", "_self");
window.close();

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

PHP script to loop through all of the files in a directory?

you can do this as well

$path = "/public";

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach ($objects as $name => $object) {
  if ('.' === $object) continue;
  if ('..' === $object) continue;

str_replace('/public/', '/', $object->getPathname());

// for example : /public/admin/image.png => /admin/image.png

Converting Pandas dataframe into Spark dataframe error

I have tried this with your data and it is working :

%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()

Update my gradle dependencies in eclipse

First, please check you have include eclipse gradle plugin. apply plugin : 'eclipse' Then go to your project directory in Terminal. Type gradle clean and then gradle eclipse. Then go to project in eclipse and refresh the project.

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

Android : change button text and background color

Since API level 21 you can use :

android:backgroundTint="@android:color/white"

you only have to add this in your xml

Query to convert from datetime to date mysql

syntax of date_format:

SELECT date_format(date_born, '%m/%d/%Y' ) as my_date FROM date_tbl

    '%W %D %M %Y %T'    -> Wednesday 5th May 2004 23:56:25
    '%a %b %e %Y %H:%i' -> Wed May 5 2004 23:56
    '%m/%d/%Y %T'       -> 05/05/2004 23:56:25
    '%d/%m/%Y'          -> 05/05/2004
    '%m-%d-%y'          -> 04-08-13

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

jQuery - select the associated label element of a input field

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

Convert int to a bit array in .NET

int value = 3;

var array = Convert.ToString(value, 2).PadLeft(8, '0').ToArray();

How to store a dataframe using Pandas

If I understand correctly, you're already using pandas.read_csv() but would like to speed up the development process so that you don't have to load the file in every time you edit your script, is that right? I have a few recommendations:

  1. you could load in only part of the CSV file using pandas.read_csv(..., nrows=1000) to only load the top bit of the table, while you're doing the development

  2. use ipython for an interactive session, such that you keep the pandas table in memory as you edit and reload your script.

  3. convert the csv to an HDF5 table

  4. updated use DataFrame.to_feather() and pd.read_feather() to store data in the R-compatible feather binary format that is super fast (in my hands, slightly faster than pandas.to_pickle() on numeric data and much faster on string data).

You might also be interested in this answer on stackoverflow.

How to convert a multipart file to File?

small correction on @PetrosTsialiamanis post , new File( multipart.getOriginalFilename()) this will create file in server location where sometime you will face write permission issues for the user, its not always possible to give write permission to every user who perform action. System.getProperty("java.io.tmpdir") will create temp directory where your file will be created properly. This way you are creating temp folder, where file gets created , later on you can delete file or temp folder.

public  static File multipartToFile(MultipartFile multipart, String fileName) throws IllegalStateException, IOException {
    File convFile = new File(System.getProperty("java.io.tmpdir")+"/"+fileName);
    multipart.transferTo(convFile);
    return convFile;
}

put this method in ur common utility and use it like for eg. Utility.multipartToFile(...)

Email validation using jQuery

Javascript Email Validation in MVC/ASP.NET

The problem I came across while using Fabian's answer, is implementing it in an MVC view because of the Razor @ symbol. You have to include an additional @ symbol to escape it, like so: @@

To Avoid Razor In MVC

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

I didn't see it elsewhere on this page, so I thought it might be helpful.

EDIT

Here's a link from Microsoft describing it's usage.
I just tested the code above and got the following js:

function validateEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
  return regex.test(email);
}

Which is doing exactly what it's supposed to do.

How to get current timestamp in milliseconds since 1970 just the way Java gets

Since C++11 you can use std::chrono:

  • get current system time: std::chrono::system_clock::now()
  • get time since epoch: .time_since_epoch()
  • translate the underlying unit to milliseconds: duration_cast<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#include <chrono>
#include <cstdint>
#include <iostream>

uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}

int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

In my case I have change the Target name in my Podfile So it's create the same Error for me.

Solution

Just go project-> Build Phase->Link Binary with libraries Remove the old FrameWorks by click on minus button(-) And clean and Run again. It's work me.

enter image description here

Remove Unwanted .framework.

Different class for the last element in ng-repeat

The answer given by Fabian Perez worked for me, with a little change

Edited html is here:

<div ng-repeat="file in files" ng-class="!$last ? 'other' : 'class-for-last'"> {{file.name}} </div>

How to log Apache CXF Soap Request and Soap Response using Log4j?

When configuring log4j.properties, putting org.apache.cxf logging level to INFO is enough to see the plain SOAP messages:

log4j.logger.org.apache.cxf=INFO

DEBUG is too verbose.

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

How do I get a list of all subdomains of a domain?

robotex tools which are free will let you do this but they make you enter the ip of the domain first:

  1. find out the ip (there's a good ff plugin which does this but I can't post the link cos this is my first post here!)
  2. do an ip search on robotex: http://www.robtex.com/ip/
  3. in the results page that follows click on the domain you're interested in>
  4. you are taken to a page that lists all subdomains + a load of other information such as mail server info

How to run a script as root on Mac OS X?

In order for sudo to work the way everyone suggest, you need to be in the admin group.

UITextView that expands to text using auto layout

I've found it's not entirely uncommon in situations where you may still need isScrollEnabled set to true to allow a reasonable UI interaction. A simple case for this is when you want to allow an auto expanding text view but still limit it's maximum height to something reasonable in a UITableView.

Here's a subclass of UITextView I've come up with that allows auto expansion with auto layout but that you could still constrain to a maximum height and which will manage whether the view is scrollable depending on the height. By default the view will expand indefinitely if you have your constraints setup that way.

import UIKit

class FlexibleTextView: UITextView {
    // limit the height of expansion per intrinsicContentSize
    var maxHeight: CGFloat = 0.0
    private let placeholderTextView: UITextView = {
        let tv = UITextView()

        tv.translatesAutoresizingMaskIntoConstraints = false
        tv.backgroundColor = .clear
        tv.isScrollEnabled = false
        tv.textColor = .disabledTextColor
        tv.isUserInteractionEnabled = false
        return tv
    }()
    var placeholder: String? {
        get {
            return placeholderTextView.text
        }
        set {
            placeholderTextView.text = newValue
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        isScrollEnabled = false
        autoresizingMask = [.flexibleWidth, .flexibleHeight]
        NotificationCenter.default.addObserver(self, selector: #selector(UITextInputDelegate.textDidChange(_:)), name: Notification.Name.UITextViewTextDidChange, object: self)
        placeholderTextView.font = font
        addSubview(placeholderTextView)

        NSLayoutConstraint.activate([
            placeholderTextView.leadingAnchor.constraint(equalTo: leadingAnchor),
            placeholderTextView.trailingAnchor.constraint(equalTo: trailingAnchor),
            placeholderTextView.topAnchor.constraint(equalTo: topAnchor),
            placeholderTextView.bottomAnchor.constraint(equalTo: bottomAnchor),
        ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override var text: String! {
        didSet {
            invalidateIntrinsicContentSize()
            placeholderTextView.isHidden = !text.isEmpty
        }
    }

    override var font: UIFont? {
        didSet {
            placeholderTextView.font = font
            invalidateIntrinsicContentSize()
        }
    }

    override var contentInset: UIEdgeInsets {
        didSet {
            placeholderTextView.contentInset = contentInset
        }
    }

    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize

        if size.height == UIViewNoIntrinsicMetric {
            // force layout
            layoutManager.glyphRange(for: textContainer)
            size.height = layoutManager.usedRect(for: textContainer).height + textContainerInset.top + textContainerInset.bottom
        }

        if maxHeight > 0.0 && size.height > maxHeight {
            size.height = maxHeight

            if !isScrollEnabled {
                isScrollEnabled = true
            }
        } else if isScrollEnabled {
            isScrollEnabled = false
        }

        return size
    }

    @objc private func textDidChange(_ note: Notification) {
        // needed incase isScrollEnabled is set to true which stops automatically calling invalidateIntrinsicContentSize()
        invalidateIntrinsicContentSize()
        placeholderTextView.isHidden = !text.isEmpty
    }
}

As a bonus there's support for including placeholder text similar to UILabel.

DataSet panel (Report Data) in SSRS designer is gone

With a .rdl, .rdlc or similar file selected, you can either:

  • Click View -> Report Data or...
  • Use the keyboard shortcut CTRL + ALT + D

Example

Type definition in object literal in TypeScript

Update 2019-05-15 (Improved Code Pattern as Alternative)

After many years of using const and benefiting from more functional code, I would recommend against using the below in most cases. (When building objects, forcing the type system into a specific type instead of letting it infer types is often an indication that something is wrong).

Instead I would recommend using const variables as much as possible and then compose the object as the final step:

const id = GetId();
const hasStarted = true;
...
const hasFinished = false;
...
return {hasStarted, hasFinished, id};
  • This will properly type everything without any need for explicit typing.
  • There is no need to retype the field names.
  • This leads to the cleanest code from my experience.
  • This allows the compiler to provide more state verification (for example, if you return in multiple locations, the compiler will ensure the same type of object is always returned - which encourages you to declare the whole return value at each position - giving a perfectly clear intention of that value).

Addition 2020-02-26

If you do actually need a type that you can be lazily initialized: Mark it is a nullable union type (null or Type). The type system will prevent you from using it without first ensuring it has a value.

In tsconfig.json, make sure you enable strict null checks:

"strictNullChecks": true

Then use this pattern and allow the type system to protect you from accidental null/undefined access:



const state = {
    instance: null as null | ApiService,
    // OR
    // instance: undefined as undefined | ApiService,

};

const useApi = () => {
    // If I try to use it here, the type system requires a safe way to access it

    // Simple lazy-initialization 
    const api = state?.instance ?? (state.instance = new ApiService());
    api.fun();

    // Also here are some ways to only access it if it has value:

    // The 'right' way: Typescript 3.7 required
    state.instance?.fun();

    // Or the old way: If you are stuck before Typescript 3.7
    state.instance && state.instance.fun();

    // Or the long winded way because the above just feels weird
    if (state.instance) { state.instance.fun(); }

    // Or the I came from C and can't check for nulls like they are booleans way
    if (state.instance != null) { state.instance.fun(); }

    // Or the I came from C and can't check for nulls like they are booleans 
    // AND I was told to always use triple === in javascript even with null checks way
    if (state.instance !== null && state.instance !== undefined) { state.instance.fun(); }
};

class ApiService {
    fun() {
        // Do something useful here
    }
}

Do not do the below in 99% of cases:

Update 2016-02-10 - To Handle TSX (Thanks @Josh)

Use the as operator for TSX.

var obj = {
    property: null as string
};

A longer example:

var call = {
    hasStarted: null as boolean,
    hasFinished: null as boolean,
    id: null as number,
};

Original Answer

Use the cast operator to make this succinct (by casting null to the desired type).

var obj = {
    property: <string> null
};

A longer example:

var call = {
    hasStarted: <boolean> null,
    hasFinished: <boolean> null,
    id: <number> null,
};

This is much better than having two parts (one to declare types, the second to declare defaults):

var callVerbose: {
    hasStarted: boolean;
    hasFinished: boolean;
    id: number;
} = {
    hasStarted: null,
    hasFinished: null,
    id: null,
};

How can I find all the subsets of a set, with exactly n elements?

itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.

import itertools
def findsubsets(S,m):
    return set(itertools.combinations(S, m))

S: The set for which you want to find subsets
m: The number of elements in the subset

Creating a Zoom Effect on an image on hover using CSS?

Here you go.

Demo

http://jsfiddle.net/27Syr/4/

HTML

<div id="menu">

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="blog" src="http://s18.postimg.org/il7hbk7i1/image.png" alt="">
        </a>
    </div>

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="blog" src="http://s18.postimg.org/4st2fxgqh/image.png" alt="">
        </a>
    </div>

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="projects" src="http://s18.postimg.org/sxtrxn115/image.png" alt="">
        </a>
    </div>

    <div class="fader">
        <div class="text">
            <p>Yay!</p>
        </div>
        <a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
            <img class ="blog" src="http://s18.postimg.org/5xn4lb37d/image.png" alt="">
        </a>
    </div>

</div>

CSS

#menu {
    text-align: center; }


.fader {
    /* Giving equal sizes to each element */
    width:    250px;
    height:   375px;

    /* Positioning elements in lines */
    display:  inline-block;

    /* This is necessary for position:absolute to work as desired */
    position: relative;

    /* Preventing zoomed images to grow outside their elements */
    overflow: hidden; }


    .fader img {
        /* Stretching the images to fill whole elements */
        width:       100%;
        height:      100%;

        /* Preventing blank space below the image */
        line-height: 0;

        /* A one-second transition was to disturbing for me */
        -webkit-transition: all 0.3s ease;
        -moz-transition:    all 0.3s ease;
        -o-transition:      all 0.3s ease;
        -ms-transition:     all 0.3s ease;
        transition:         all 0.3s ease; }

        .fader img:hover {
            /* Making images appear bigger and transparent on mouseover */
            opacity: 0.5;
            width:   120%;
            height:  120%; }

    .fader .text {
        /* Placing text behind images */
        z-index: -10;     

        /* Positioning text top-left conrner in the middle of elements */
        position: absolute;
        top:      50%;
        left:     50%; }

        .fader .text p {
            /* Positioning text contents 50% left and top relative
               to text container's top left corner */
            margin-top:  -50%; 
            margin-left: -50%; }

Suggestion

Instead of .fader { inline-block; } consider using some grid system. Based on your technology of preference, you can go Foundation, Susy, Masonry or their alternatives.

stdlib and colored output in C

Dealing with colour sequences can get messy and different systems might use different Colour Sequence Indicators.

I would suggest you try using ncurses. Other than colour, ncurses can do many other neat things with console UI.

How do you resize a form to fit its content automatically?

I used this code and it works just fine

const int margin = 5;
        Rectangle rect = new Rectangle(
            Screen.PrimaryScreen.WorkingArea.X + margin,
            Screen.PrimaryScreen.WorkingArea.Y + margin,
            Screen.PrimaryScreen.WorkingArea.Width - 2 * margin,
            Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7));
        this.Bounds = rect;

Setting a log file name to include current date in Log4j

I have created an appender that will do that. http://stauffer.james.googlepages.com/DateFormatFileAppender.java

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.txt file.  */

package sps.log.log4j;

import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * DateFormatFileAppender is a log4j Appender and extends 
 * {@link FileAppender} so each log is 
 * named based on a date format defined in the File property.
 *
 * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'
 * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log
 * @author James Stauffer
 */
public class DateFormatFileAppender extends FileAppender {

  /**
   * The default constructor does nothing.
   */
  public DateFormatFileAppender() {
  }

  /**
   * Instantiate a <code>DailyRollingFileAppender</code> and open the
   * file designated by <code>filename</code>. The opened filename will
   * become the ouput destination for this appender.
   */
  public DateFormatFileAppender (Layout layout, String filename) throws IOException {
    super(layout, filename, true);
  }

  private String fileBackup;//Saves the file pattern
  private boolean separate = false;

  public void setFile(String file) {
    super.setFile(file);
    this.fileBackup = getFile();
  }

  /**
   * If true each LoggingEvent causes that file to close and open.
   * This is useful when the file is a pattern that would often
   * produce a different filename.
   */
  public void setSeparate(boolean separate) {
    this.separate = separate;
  }

  protected void subAppend(LoggingEvent event) {
    if(separate) {
        try {//First reset the file so each new log gets a new file.
            setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());
        } catch(IOException e) {
            LogLog.error("Unable to reset fileName.");
        }
    }
    super.subAppend(event);
  }


  public
  synchronized
  void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
    String actualFileName = sdf.format(new Date());
    makeDirs(actualFileName);
    super.setFile(actualFileName, append, bufferedIO, bufferSize);
  }

  /**
   * Ensures that all of the directories for the given path exist.
   * Anything after the last / or \ is assumed to be a filename.
   */
  private void makeDirs (String path) {
    int indexSlash = path.lastIndexOf("/");
    int indexBackSlash = path.lastIndexOf("\\");
    int index = Math.max(indexSlash, indexBackSlash);
    if(index > 0) {
        String dirs = path.substring(0, index);
//        LogLog.debug("Making " + dirs);
        File dir = new File(dirs);
        if(!dir.exists()) {
            boolean success = dir.mkdirs();
            if(!success) {
                LogLog.error("Unable to create directories for " + dirs);
            }
        }
    }
  }

}

How to convert a Hibernate proxy to a real entity object

I found a solution to deproxy a class using standard Java and JPA API. Tested with hibernate, but does not require hibernate as a dependency and should work with all JPA providers.

Onle one requirement - its necessary to modify parent class (Address) and add a simple helper method.

General idea: add helper method to parent class which returns itself. when method called on proxy, it will forward the call to real instance and return this real instance.

Implementation is a little bit more complex, as hibernate recognizes that proxied class returns itself and still returns proxy instead of real instance. Workaround is to wrap returned instance into a simple wrapper class, which has different class type than the real instance.

In code:

class Address {
   public AddressWrapper getWrappedSelf() {
       return new AddressWrapper(this);
   }
...
}

class AddressWrapper {
    private Address wrappedAddress;
...
}

To cast Address proxy to real subclass, use following:

Address address = dao.getSomeAddress(...);
Address deproxiedAddress = address.getWrappedSelf().getWrappedAddress();
if (deproxiedAddress instanceof WorkAddress) {
WorkAddress workAddress = (WorkAddress)deproxiedAddress;
}

Trigger an event on `click` and `enter`

$('#usersSearch').keyup(function() { // handle keyup event on search input field

    var key = e.which || e.keyCode;  // store browser agnostic keycode

    if(key == 13) 
        $(this).closest('form').submit(); // submit parent form
}

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

Android Calling JavaScript functions in WebView

public void run(final String scriptSrc) { 
        webView.post(new Runnable() {
            @Override
            public void run() { 
                webView.loadUrl("javascript:" + scriptSrc); 
            }
        }); 
    }

how to make a countdown timer in java

You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.

How to change checkbox's border style in CSS?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style> _x000D_
_x000D_
.abc123_x000D_
{_x000D_
 -webkit-appearance:none;_x000D_
    width: 14px;_x000D_
    height: 14px;_x000D_
    display: inline-block;_x000D_
    background: #FFFFFF;_x000D_
 border: 1px solid rgba(220,220,225,1);_x000D_
}_x000D_
.abc123:after {_x000D_
  content: "";_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  top: -3px;_x000D_
  left: 4px;_x000D_
  width: 3px;_x000D_
  height: 5px;_x000D_
  border-bottom: 1px solid #fff;_x000D_
  border-right: 1px solid #fff;_x000D_
  -webkit-transform: rotate(45deg);_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked   {_x000D_
    background: #327DFF;_x000D_
    outline: none;_x000D_
    border: 1px solid rgba(50,125,255,1);_x000D_
}_x000D_
input:focus,input:active {_x000D_
 outline: none;_x000D_
}_x000D_
_x000D_
input:hover {_x000D_
   border: 1px solid rgba(50,125,255,1);_x000D_
}_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input class="abc123" type="checkbox"></input>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Selenium using Python - Geckodriver executable needs to be in PATH

If you want to add the driver paths on Windows 10:

  1. Right click on the "This PC" icon and select "Properties"

    Enter image description here

  2. Click on “Advanced System Settings”

  3. Click on “Environment Variables” at the bottom of the screen

  4. In the “User Variables” section highlight “Path” and click “Edit”

  5. Add the paths to your variables by clicking “New” and typing in the path for the driver you are adding and hitting enter.

  6. Once you done entering in the path, click “OK”

  7. Keep clicking “OK” until you have closed out all the screens

Convert utf8-characters to iso-88591 and back in PHP

I used:

function utf8_to_html ($data) {
    return preg_replace(
        array (
            '/ä/',
            '/ö/',
            '/ü/',
            '/é/',
            '/à/',
            '/è/'
        ),
        array (
            '&auml;',
            '&ouml;',
            '&uuml;',
            '&eacute;',
            '&agrave;',
            '&egrave;'
        ),
        $data 
    );
}

SwiftUI - How do I change the background color of a View?

For List:

All SwiftUI's Lists are backed by a UITableViewin iOS. so you need to change the background color of the tableView. But since Color and UIColor values are slightly different, you can get rid of the UIColor.

struct ContentView : View {
    init(){
        UITableView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        List {
            Section(header: Text("First Section")) {
                Text("First Cell")
            }
            Section(header: Text("Second Section")) {
                Text("First Cell")
            }
        }
        .background(Color.yellow)
    }
}

Now you can use Any background (including all Colors) you want


Also First look at this result:

View hierarchy

As you can see, you can set the color of each element in the View hierarchy like this:

struct ContentView: View {
    
    init(){
        UINavigationBar.appearance().backgroundColor = .green 
        //For other NavigationBar changes, look here:(https://stackoverflow.com/a/57509555/5623035)
    }

    var body: some View {
        ZStack {
            Color.yellow
            NavigationView {
                ZStack {
                    Color.blue
                    Text("Some text")
                }
            }.background(Color.red)
        }
    }
}

And the first one is window:

window.backgroundColor = .magenta

The very common issue is we can not remove the background color of SwiftUI's HostingViewController (yet), so we can't see some of the views like navigationView through the views hierarchy. You should wait for the API or try to fake those views (not recommended).

MongoDB via Mongoose JS - What is findByID?

As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

.htaccess not working apache

By default, Apache prohibits using an .htaccess file to apply rewrite rules, so

Step 1 — Enabling mod_rewrite (if not Enabled) First, we need to activate mod_rewrite. It's available but not enabled with a clean Apache 2 installation.

$ sudo a2enmod rewrite

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we'll use to define rewrite rules for redirects.

Step 2 — Setting Up .htaccess Open the default Apache configuration file using nano or your favorite text editor.

$ sudo nano /etc/apache2/sites-available/000-default.conf

Inside that file, you will find a block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented.

/etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>

    . . . 
</VirtualHost>

Save and close the file. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

Done. Your .htacess should work. This link may actually help somebody https://www.digitalocean.com/community/tutorials/how-to-rewrite-urls-with-mod_rewrite-for-apache-on-ubuntu-16-04

How to provide a mysql database connection in single file in nodejs

var mysql = require('mysql');

var pool  = mysql.createPool({
    host     : 'yourip',
    port    : 'yourport',
    user     : 'dbusername',
    password : 'dbpwd',
    database : 'database schema name',
    dateStrings: true,
    multipleStatements: true
});


// TODO - if any pool issues need to try this link for connection management
// https://stackoverflow.com/questions/18496540/node-js-mysql-connection-pooling

module.exports = function(qry, qrytype, msg, callback) {

if(qrytype != 'S') {
    console.log(qry);
}

pool.getConnection(function(err, connection) {
    if(err) {
        if(connection)
            connection.release();
        throw err;
    } 

    // Use the connection
    connection.query(qry, function (err, results, fields) {
        connection.release();

        if(err) {
            callback('E#connection.query-Error occurred.#'+ err.sqlMessage);    
            return;         
        }

        if(qrytype==='S') {
            //for Select statement
            // setTimeout(function() {
                callback(results);      
            // }, 500);
        } else if(qrytype==='N'){
            let resarr = results[results.length-1];
            let newid= '';
            if(resarr.length)               
                newid = resarr[0]['@eid'];
            callback(msg + newid);
        } else if(qrytype==='U'){
            //let ret = 'I#' + entity + ' updated#Updated rows count: ' + results[1].changedRows;
            callback(msg);                      
        } else if(qrytype==='D'){
            //let resarr = results[1].affectedRows;
            callback(msg);
        }
    });

    connection.on('error', function (err) {
        connection.release();
        callback('E#connection.on-Error occurred.#'+ err.sqlMessage);   
        return;         
    });
});

}

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

CSS: borders between table columns only

Take a table with class name column-bordered-table then add this below css.This will work with bootstrap table too

.column-bordered-table thead td {
    border-left: 1px solid #c3c3c3;
    border-right: 1px solid #c3c3c3;
}

.column-bordered-table td {
    border-left: 1px solid #c3c3c3;
    border-right: 1px solid #c3c3c3;
}

.column-bordered-table tfoot tr {
    border-top: 1px solid #c3c3c3;
    border-bottom: 1px solid #c3c3c3;
}

see the output below
N:B You have to add table header backgorund color as per you requirement

enter image description here

Python sum() function with list parameter

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The name sum doesn't point to the function anymore now, it points to an integer.

Solution: Don't call your variable sum, call it total or something similar.

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

make sure you check Environment variables versions of java , it could be just the difference between the versions of JAVA_HOME (JDK path) and JRE_HOME (JRE path) , that cause the problem

How can I create a self-signed cert for localhost?

If you are using Visual Studio, there is an easy way to setup and enable SSL using IIS Express explained here

What is the easiest way to get the current day of the week in Android?

If you want to define the date string in strings.xml. You can do like below.
Calendar.DAY_OF_WEEK return value from 1 -> 7 <=> Calendar.SUNDAY -> Calendar.SATURDAY

strings.xml

<string-array name="title_day_of_week">
    <item>?</item> <!-- sunday -->
    <item>?</item> <!-- monday -->
    <item>?</item>
    <item>?</item>
    <item>?</item>
    <item>?</item>
    <item>?</item> <!-- saturday -->
</string-array>

DateExtension.kt

fun String.getDayOfWeek(context: Context, format: String): String {
    val date = SimpleDateFormat(format, Locale.getDefault()).parse(this)
    return date?.getDayOfWeek(context) ?: "unknown"
}

fun Date.getDayOfWeek(context: Context): String {
    val c = Calendar.getInstance().apply { time = this@getDayOfWeek }
    return context.resources.getStringArray(R.array.title_day_of_week)[c[Calendar.DAY_OF_WEEK] - 1]
}

Using

// get current day
val currentDay = Date().getDayOfWeek(context)

// get specific day
val dayString = "2021-1-4"
val day = dayString.getDayOfWeek(context, "yyyy-MM-dd")

Make Adobe fonts work with CSS3 @font-face in IE9

I tried the ttfpatch tool and it didn't work form me. Internet Exploder 9 and 10 still complained.

I found this nice Git gist and it solved my issues. https://gist.github.com/stefanmaric/a5043c0998d9fc35483d

Just copy and paste the code in your css.

Math functions in AngularJS bindings

Better option is to use :

{{(100*score/questionCounter) || 0 | number:0}}

It sets default value of equation to 0 in the case when values are not initialized.

How do I change the color of radio buttons?

Well to create extra elements we can use :after, :before (so we don’t have to change the HTML that much). Then for radio buttons and checkboxes we can use :checked. There are a few other pseudo elements we can use as well (such as :hover). Using a mixture of these we can create some pretty cool custom forms. check this

How to create a CPU spike with a bash command

Here is a program that you can download Here

Install easily on your Linux system

./configure
make
make install

and launch it in a simple command line

stress -c 40

to stress all your CPUs (however you have) with 40 threads each running a complex sqrt computation on a ramdomly generated numbers.

You can even define the timeout of the program

stress -c 40 -timeout 10s

unlike the proposed solution with the dd command, which deals essentially with IO and therefore doesn't really overload your system because working with data.

The stress program really overloads the system because dealing with computation.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

This often happens when your SQL is bad (implicit type conversions etc.).

Turn on hibernate SQL logging by adding the following lines to your log4j properties file:

logs the SQL statements

log4j.logger.org.hibernate.SQL=debug

Logs the JDBC parameters passed to a query

log4j.logger.org.hibernate.type=trace

Before failing you will see the last SQL statement attempted in your log, copy and paste this SQL into an external SQL client and run it.

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object, like:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv 'PATH\scans.csv'

How to create a multi line body in C# System.Net.Mail.MailMessage

Sometimes you don't want to create a html e-mail. I solved the problem this way :

Replace \n by \t\n

The tab will not be shown, but the newline will work.

Uses of Action delegate in C#

For an example of how Action<> is used.

Console.WriteLine has a signature that satisifies Action<string>.

    static void Main(string[] args)
    {
        string[] words = "This is as easy as it looks".Split(' ');

        // Passing WriteLine as the action
        Array.ForEach(words, Console.WriteLine);         
    }

Hope this helps

Update Eclipse with Android development tools v. 23

Google response:

This is a packaging bug. The entire proguard file is missing. We'll have an update asap, but until then just copy it over from a previous version of the tools:

and copy over the following files:

  • tools/hprof-conv
  • tools/support/annotations.jar
  • tools/proguard

So at the end if you started from a new ADT copy by hand the files :)

Edit: with the latest ADT release, the bundle should now work with auto-update, so install these new versions:

Don't try to upgrade from previous version because it doesn’t work at all. If you have got problems with zipalign, it's now under build-tools and no more under tools/ so you can do a symbolic link or just copy it into the expected folder.

The way to check a HDFS directory's size?

hdfs dfs -count <dir>

info from man page:

-count [-q] [-h] [-v] [-t [<storage type>]] [-u] <path> ... :
  Count the number of directories, files and bytes under the paths
  that match the specified file pattern.  The output columns are:
  DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME
  or, with the -q option:
  QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA
        DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME

Pointer vs. Reference

My rule of thumb is:

Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.

Use references otherwise.

Min/Max-value validators in asp.net mvc

Here is how I would write a validator for MaxValue

public class MaxValueAttribute : ValidationAttribute
    {
        private readonly int _maxValue;

        public MaxValueAttribute(int maxValue)
        {
            _maxValue = maxValue;
        }

        public override bool IsValid(object value)
        {
            return (int) value <= _maxValue;
        }
    }

The MinValue Attribute should be fairly the same

Perform curl request in javascript?

Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like

$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});

The callback parameter will be filled in automatically by the browser, so don't worry.

On the server side ('validate.php') you would have something like this

<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>

Security of REST authentication schemes

If you require the hash of the body as one of the parameters in the URL and that URL is signed via a private key, then a man-in-the-middle attack would only be able to replace the body with content that would generate the same hash. Easy to do with MD5 hash values now at least and when SHA-1 is broken, well, you get the picture.

To secure the body from tampering, you would need to require a signature of the body, which a man-in-the-middle attack would be less likely to be able to break since they wouldn't know the private key that generates the signature.

Find size of object instance in bytes in c#

Simplest way is: int size = *((int*)type.TypeHandle.Value + 1)

I know this is implementation detail but GC relies on it and it needs to be as close to start of the methodtable for efficiency plus taking into consideration how GC code complex is nobody will dare to change it in future. In fact it works for every minor/major versions of .net framework+.net core. (Currently unable to test for 1.0)
If you want more reliable way, emit a struct in a dynamic assembly with [StructLayout(LayoutKind.Auto)] with exact same fields in same order, take its size with sizeof IL instruction. You may want to emit a static method within struct which simply returns this value. Then add 2*IntPtr.Size for object header. This should give you exact value.
But if your class derives from another class, you need to find each size of base class seperatly and add them + 2*Inptr.Size again for header. You can do this by getting fields with BindingFlags.DeclaredOnly flag.
Arrays and strings just adds that size its length * element size. For cumulative size of aggreagate objects you need to implement more sophisticated solution which involves visiting every field and inspect its contents.

Combine multiple Collections into a single logical Collection?

Here is my solution for that:

EDIT - changed code a little bit

public static <E> Iterable<E> concat(final Iterable<? extends E> list1, Iterable<? extends E> list2)
{
    return new Iterable<E>()
    {
        public Iterator<E> iterator()
        {
            return new Iterator<E>()
            {
                protected Iterator<? extends E> listIterator = list1.iterator();
                protected Boolean checkedHasNext;
                protected E nextValue;
                private boolean startTheSecond;

                public void theNext()
                {
                    if (listIterator.hasNext())
                    {
                        checkedHasNext = true;
                        nextValue = listIterator.next();
                    }
                    else if (startTheSecond)
                        checkedHasNext = false;
                    else
                    {
                        startTheSecond = true;
                        listIterator = list2.iterator();
                        theNext();
                    }
                }

                public boolean hasNext()
                {
                    if (checkedHasNext == null)
                        theNext();
                    return checkedHasNext;
                }

                public E next()
                {
                    if (!hasNext())
                        throw new NoSuchElementException();
                    checkedHasNext = null;
                    return nextValue;

                }

                public void remove()
                {
                    listIterator.remove();
                }
            };
        }
    };
}

GROUP BY and COUNT in PostgreSQL

WITH uniq AS (
        SELECT DISTINCT posts.id as post_id
        FROM posts
        JOIN votes ON votes.post_id = posts.id
        -- GROUP BY not needed anymore
        -- GROUP BY posts.id
        )
SELECT COUNT(*)
FROM uniq;

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

How to fix "The ConnectionString property has not been initialized"

Simply in Code Behind Page use:-

SqlConnection con = new SqlConnection("Data Source = DellPC; Initial Catalog = Account; user = sa; password = admin");

It Should Work Just Fine

How do I capture response of form.submit

The non-jQuery vanilla Javascript way, extracted from 12me21's comment:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php"); 
xhr.onload = function(event){ 
    alert("Success, server responded with: " + event.target.response); // raw response
}; 
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm")); 
xhr.send(formData);

For POST's the default content type is "application/x-www-form-urlencoded" which matches what we're sending in the above snippet. If you want to send "other stuff" or tweak it somehow see here for some nitty gritty details.

What is the easiest way to get current GMT time in Unix timestamp format?

I like this method:

import datetime, time

dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)

The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.

IIS7 Permissions Overview - ApplicationPoolIdentity

Giving access to the IIS AppPool\YourAppPoolName user may be not enough with IIS default configurations.

In my case, I still had the error HTTP Error 401.3 - Unauthorized after adding the AppPool user and it was fixed only after adding permissions to the IUSR user.

This is necessary because, by default, Anonymous access is done using the IUSR. You can set another specific user, the Application Pool or continue using the IUSR, but don't forget to set the appropriate permissions.

authentication tab

Credits to this answer: HTTP Error 401.3 - Unauthorized

Evaluating a mathematical expression in a string

Pyparsing can be used to parse mathematical expressions. In particular, fourFn.py shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse.

from __future__ import division
from pyparsing import (Literal, CaselessLiteral, Word, Combine, Group, Optional,
                       ZeroOrMore, Forward, nums, alphas, oneOf)
import math
import operator

__author__ = 'Paul McGuire'
__version__ = '$Revision: 0.0 $'
__date__ = '$Date: 2009-03-20 $'
__source__ = '''http://pyparsing.wikispaces.com/file/view/fourFn.py
http://pyparsing.wikispaces.com/message/view/home/15549426
'''
__note__ = '''
All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
more easily in other places.
'''


class NumericStringParser(object):
    '''
    Most of this code comes from the fourFn.py pyparsing example

    '''

    def pushFirst(self, strg, loc, toks):
        self.exprStack.append(toks[0])

    def pushUMinus(self, strg, loc, toks):
        if toks and toks[0] == '-':
            self.exprStack.append('unary -')

    def __init__(self):
        """
        expop   :: '^'
        multop  :: '*' | '/'
        addop   :: '+' | '-'
        integer :: ['+' | '-'] '0'..'9'+
        atom    :: PI | E | real | fn '(' expr ')' | '(' expr ')'
        factor  :: atom [ expop factor ]*
        term    :: factor [ multop factor ]*
        expr    :: term [ addop term ]*
        """
        point = Literal(".")
        e = CaselessLiteral("E")
        fnumber = Combine(Word("+-" + nums, nums) +
                          Optional(point + Optional(Word(nums))) +
                          Optional(e + Word("+-" + nums, nums)))
        ident = Word(alphas, alphas + nums + "_$")
        plus = Literal("+")
        minus = Literal("-")
        mult = Literal("*")
        div = Literal("/")
        lpar = Literal("(").suppress()
        rpar = Literal(")").suppress()
        addop = plus | minus
        multop = mult | div
        expop = Literal("^")
        pi = CaselessLiteral("PI")
        expr = Forward()
        atom = ((Optional(oneOf("- +")) +
                 (ident + lpar + expr + rpar | pi | e | fnumber).setParseAction(self.pushFirst))
                | Optional(oneOf("- +")) + Group(lpar + expr + rpar)
                ).setParseAction(self.pushUMinus)
        # by defining exponentiation as "atom [ ^ factor ]..." instead of
        # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
        # that is, 2^3^2 = 2^(3^2), not (2^3)^2.
        factor = Forward()
        factor << atom + \
            ZeroOrMore((expop + factor).setParseAction(self.pushFirst))
        term = factor + \
            ZeroOrMore((multop + factor).setParseAction(self.pushFirst))
        expr << term + \
            ZeroOrMore((addop + term).setParseAction(self.pushFirst))
        # addop_term = ( addop + term ).setParseAction( self.pushFirst )
        # general_term = term + ZeroOrMore( addop_term ) | OneOrMore( addop_term)
        # expr <<  general_term
        self.bnf = expr
        # map operator symbols to corresponding arithmetic operations
        epsilon = 1e-12
        self.opn = {"+": operator.add,
                    "-": operator.sub,
                    "*": operator.mul,
                    "/": operator.truediv,
                    "^": operator.pow}
        self.fn = {"sin": math.sin,
                   "cos": math.cos,
                   "tan": math.tan,
                   "exp": math.exp,
                   "abs": abs,
                   "trunc": lambda a: int(a),
                   "round": round,
                   "sgn": lambda a: abs(a) > epsilon and cmp(a, 0) or 0}

    def evaluateStack(self, s):
        op = s.pop()
        if op == 'unary -':
            return -self.evaluateStack(s)
        if op in "+-*/^":
            op2 = self.evaluateStack(s)
            op1 = self.evaluateStack(s)
            return self.opn[op](op1, op2)
        elif op == "PI":
            return math.pi  # 3.1415926535
        elif op == "E":
            return math.e  # 2.718281828
        elif op in self.fn:
            return self.fn[op](self.evaluateStack(s))
        elif op[0].isalpha():
            return 0
        else:
            return float(op)

    def eval(self, num_string, parseAll=True):
        self.exprStack = []
        results = self.bnf.parseString(num_string, parseAll)
        val = self.evaluateStack(self.exprStack[:])
        return val

You can use it like this

nsp = NumericStringParser()
result = nsp.eval('2^4')
print(result)
# 16.0

result = nsp.eval('exp(2^4)')
print(result)
# 8886110.520507872

LIKE operator in LINQ

You can also use the EF function tested in .net5

public async Task<IEnumerable<District>> SearchDistrict(string query, int stateId)
        {
            return await _dbContext
                .Districts
                .Include(s => s.State)
                .Where(s => s.StateId == stateId && EF.Functions.Like(s.Name, "$%{query}%"))
                .AsNoTracking()
                .ToListAsync();
        }

Code coverage for Jest built on top of Jasmine

When using Jest 21.2.1, I can see code coverage at the command line and create a coverage directory by passing --coverage to the Jest script. Below are some examples:

I tend to install Jest locally, in which case the command might look like this:

npx jest --coverage

I assume (though haven't confirmed), that this would also work if I installed Jest globally:

jest --coverage

The very sparse docs are here

When I navigated into the coverage/lcov-report directory I found an index.html file that could be loaded into a browser. It included the information printed at the command line, plus additional information and some graphical output.

Get current time in milliseconds in Python?

After some testing in Python 3.8+ I noticed that those options give the exact same result, at least in Windows 10.

import time

# Option 1
unix_time_ms_1 = int(time.time_ns() / 1000000)
# Option 2
unix_time_ms_2 = int(time.time() * 1000)

Feel free to use the one you like better and I do not see any need for a more complicated solution then this.

Android: Cancel Async Task

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the activity. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

Create a List that contain each Line of a File

Assuming you also want to strip whitespace at beginning and end of each line, you can map the string strip function to the list returned by readlines:

map(str.strip, open('filename').readlines())

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

Get type name without full namespace

make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;