Programs & Examples On #Session hijacking

Session hijacking is a type of network security attack that relies on "guessing" the ISNs of TCP packets and taking control over communication. The attacker intercepts and retransmits messages such as the communication is still on. The attack is performed using a program which appears as a service to the client and as a client to the server.

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddle for you to play around.

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

What does $1 mean in Perl?

I would suspect that there can be as many as 2**32 -1 numbered match variables, on a 32-bit compiled Perl binary.

Redirect to external URI from ASP.NET MVC controller

Using JavaScript

 public ActionResult Index()
 {
    return Content("<script>window.location = 'http://www.example.com';</script>");
 }

Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.

Hope this helps.

How to set scope property with ng-init?

Try this Code

var app = angular.module('myapp', []);
  app.controller('testController', function ($scope, $http) {
       $scope.init = function(){           
       alert($scope.testInput);
   };});

_x000D_
_x000D_
<body ng-app="myapp">_x000D_
      <div ng-controller='testController' data-ng-init="testInput='value'; init();" class="col-sm-9 col-lg-9" >_x000D_
      </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Convert date to YYYYMM format

SELECT LEFT(CONVERT(varchar, GetDate(),112),6)

Using css transform property in jQuery

$(".oSlider-rotate").slider({
     min: 10,
     max: 74,
     step: .01,
     value: 24,
     slide: function(e,ui){
                 $('.user-text').css('transform', 'scale(' + ui.value + ')')

            }                
  });

This will solve the issue

How to disable the ability to select in a DataGridView?

This worked for me like a charm:

row.DataGridView.Enabled = false;

row.DefaultCellStyle.BackColor = Color.LightGray;

row.DefaultCellStyle.ForeColor = Color.DarkGray;

(where row = DataGridView.NewRow(appropriate overloads);)

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

TL;DR

You are missing the @Id entity property, and that's why Hibernate is throwing that exception.

Entity identifiers

Any JPA entity must have an identifier property, that is marked with the Id annotation.

There are two types of identifiers:

  • assigned
  • auto-generated

Assigned identifiers

An assigned identifier looks as follows:

@Id
private Long id;

Notice that we are using a wrapper (e.g., Long, Integer) instead of a primitive type (e.g., long, int). Using a wrapper type is a better choice when using Hibernate because, by checking if the id is null or not, Hibernate can better determine if an entity is transient (it does not have an associated table row) or detached (it has an associated table row, but it's not managed by the current Persistence Context).

The assigned identifier must be set manually by the application prior to calling persist:

Post post = new Post();
post.setId(1L);

entityManager.persist(post);

Auto-generated identifiers

An auto-generated identifier requires the @GeneratedValue annotation besides the @Id:

@Id
@GeneratedValue
private int id;

There are 3 strategies Hibernate can use to auto-generate the entity identifier:

  • IDENTITY
  • SEQUENCE
  • TABLE

The IDENTITY strategy is to be avoided if the underlying database supports sequences (e.g., Oracle, PostgreSQL, MariaDB since 10.3, SQL Server since 2012). The only major database that does not support sequences is MySQL.

The problem with IDENTITY is that automatic Hibernate batch inserts are disabled for this strategy.

The SEQUENCE strategy is the best choice unless you are using MySQL. For the SEQUENCE strategy, you also want to use the pooled optimizer to reduce the number of database roundtrips when persisting multiple entities in the same Persistence Context.

The TABLE generator is a terrible choice because it does not scale. For portability, you are better off using SEQUENCE by default and switch to IDENTITY for MySQL only.

Get table column names in MySQL?

I needed column names as a flat array, while the other answers returned associative arrays, so I used:

$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';

/**
* Get the column names for a mysql table
**/

function get_column_names($con, $table) {
  $sql = 'DESCRIBE '.$table;
  $result = mysqli_query($con, $sql);

  $rows = array();
  while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row['Field'];
  }

  return $rows;
}

$col_names = function get_column_names($con, $table);

$col_names now equals:

(
    [0] => name
    [1] => parent
    [2] => number
    [3] => chart_id
    [4] => type
    [5] => id
)

Check whether $_POST-value is empty

If the form was successfully submitted, $_POST['userName'] should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()

if (isset($_POST['submit'])) {
    if (empty($_POST['userName'])) {
        $username = 'Anonymous';
    } else { 
        $username = $_POST['userName'];
    }
}

How to use npm with node.exe?

I've just installed 64 bit Node.js v0.12.0 for Windows 8.1 from here. It's about 8MB and since it's an MSI you just double click to launch. It will automatically set up your environment paths etc.

Then to get the command line it's just [Win-Key]+[S] for search and then enter "node.js" as your search phrase.

Choose the Node.js Command Prompt entry NOT the Node.js entry.

Both will given you a command prompt but only the former will actually work. npm is built into that download so then just npm -whatever at prompt.

How do I get rid of an element's offset using CSS?

Setting the top and left properties to negative values might not be a good workaround if your problem is simply that you're in quirks mode. This can happen if the page is missing a <!DOCTYPE> declaration, causing it to be rendered in quirks mode in IE8. In IE8 Developer Tools, make sure that "Quirks Mode" is not selected under "Document Mode". If it is selected, you may need to add the appropriate <!DOCTYPE> declaration.

How to set adaptive learning rate for GradientDescentOptimizer?

First of all, tf.train.GradientDescentOptimizer is designed to use a constant learning rate for all variables in all steps. TensorFlow also provides out-of-the-box adaptive optimizers including the tf.train.AdagradOptimizer and the tf.train.AdamOptimizer, and these can be used as drop-in replacements.

However, if you want to control the learning rate with otherwise-vanilla gradient descent, you can take advantage of the fact that the learning_rate argument to the tf.train.GradientDescentOptimizer constructor can be a Tensor object. This allows you to compute a different value for the learning rate in each step, for example:

learning_rate = tf.placeholder(tf.float32, shape=[])
# ...
train_step = tf.train.GradientDescentOptimizer(
    learning_rate=learning_rate).minimize(mse)

sess = tf.Session()

# Feed different values for learning rate to each training step.
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.1})
sess.run(train_step, feed_dict={learning_rate: 0.01})
sess.run(train_step, feed_dict={learning_rate: 0.01})

Alternatively, you could create a scalar tf.Variable that holds the learning rate, and assign it each time you want to change the learning rate.

Add MIME mapping in web.config for IIS Express

Thanks for this post. I got this worked for using mustache templates in my asp.net mvc project I used the following, and it worked for me.

<system.webServer>   
  <staticContent>
   <mimeMap fileExtension=".mustache" mimeType="text/html"/>
  </staticContent>
</system.WebServer>

Comparing object properties in c#

If performance doesn't matter, you could serialize them and compare the results:

var serializer = new XmlSerializer(typeof(TheObjectType));
StringWriter serialized1 = new StringWriter(), serialized2 = new StringWriter();
serializer.Serialize(serialized1, obj1);
serializer.Serialize(serialized2, obj2);
bool areEqual = serialized1.ToString() == serialized2.ToString();

Descending order by date filter in AngularJs

And a code example:

<div ng-app>
    <div ng-controller="FooController">
        <ul ng-repeat="item in items | orderBy:'num':true">
            <li>{{item.num}} :: {{item.desc}}</li>
        </ul>
    </div>
</div>

And the JavaScript:

function FooController($scope) {
    $scope.items = [
        {desc: 'a', num: 1},
        {desc: 'b', num: 2},
        {desc: 'c', num: 3},
    ];
}

Will give you:

3 :: c
2 :: b
1 :: a

On JSFiddle: http://jsfiddle.net/agjqN/

Fastest way to convert JavaScript NodeList to Array?

The results will completely depend on the browser, to give an objective verdict, we have to make some performance tests, here are some results, you can run them here:

Chrome 6:

Firefox 3.6:

Firefox 4.0b2:

Safari 5:

IE9 Platform Preview 3:

Android Studio Rendering Problems : The following classes could not be found

You have to do two things:

  • be sure to have imported right appcompat-v7 library in your project structure -> dependencies
  • change the theme in the preview window to not an AppCompat theme. Try with Holo.light or Holo.dark for example.

How to view query error in PDO PHP

I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

I find it useful, because when I didn't know about env, before I started to write script I was doing this:

type nodejs > scriptname.js #or any other environment

and then I was modifying that line in the file into shebang.
I was doing this, because I didn't always remember where is nodejs on my computer -- /usr/bin/ or /bin/, so for me env is very useful. Maybe there are details with this, but this is my reason

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

According to the GCC page for C++11:

To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

Did you compile with -std=gnu++0x ?

"Line contains NULL byte" in CSV reader (Python)

I'm guessing you have a NUL byte in input.csv. You can test that with

if '\0' in open('input.csv').read():
    print "you have null bytes in your input file"
else:
    print "you don't"

if you do,

reader = csv.reader(x.replace('\0', '') for x in mycsv)

may get you around that. Or it may indicate you have utf16 or something 'interesting' in the .csv file.

Cannot make a static reference to the non-static method

This question is not new and existing answers give some good theoretical background. I just want to add a more pragmatic answer.

getText is a method of the Context abstract class and in order to call it, one needs an instance of it's subclass (Activity, Service, Application or other). The problem is, that the public static final variables are initialized before any instance of Context is created.

There are several ways to solve this:

  1. Make the variable a member variable (field) of the Activity or other subclass of Context by removing the static modifier and placing it within the class body;
  2. Keep it static and delay the initialization to a later point (e.g. in the onCreate method);
  3. Make it a local variable in the place of actual usage.

Nginx: Permission denied for nginx on Ubuntu

just because you don't have the right to acess the file , use

chmod -R 755 /var/log/nginx;

or you can change to sudo then it

Calling an API from SQL Server stored procedure

I worked so much, I hope my effort might help you out.

Just paste this into your SSMS and press F5:

Declare @Object as Int;
DECLARE @hr  int
Declare @json as table(Json_Table nvarchar(max))

Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
                 'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json), N'$.elements')
WITH (   
      [type] nvarchar(max) N'$.type'   ,
      [id]   nvarchar(max) N'$.id',
      [lat]   nvarchar(max) N'$.lat',
      [lon]   nvarchar(max) N'$.lon',
      [amenity]   nvarchar(max) N'$.tags.amenity',
      [name]   nvarchar(max) N'$.tags.name'     
)
EXEC sp_OADestroy @Object

This query will give you 3 results:

1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)

2. Put the JSON into a string (which is what we want)

3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)

enter image description here

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

Read Content from Files which are inside Zip file

My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:

The wrapper class:

public class ZippedFileInputStream extends InputStream {

    private ZipInputStream is;

    public ZippedFileInputStream(ZipInputStream is){
        this.is = is;
    }

    @Override
    public int read() throws IOException {
        return is.read();
    }

    @Override
    public void close() throws IOException {
        is.closeEntry();
    }

}

The use of it:

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));

    while((entry = zipInputStream.getNextEntry())!= null) {

     ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);

     //... perform whatever logic you want here with ZippedFileInputStream 

     // note that this will only close the current entry stream and not the ZipInputStream
     archivedFileInputStream.close();

    }
    zipInputStream.close();

One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.

How to insert text with single quotation sql server 2005

You asked how to escape an Apostrophe character (') in SQL Server. All the answers above do an excellent job of explaining that.

However, depending on the situation, the Right single quotation mark character (’) might be appropriate.

(No escape characters needed)

-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John’s')

• Apostrophe (U+0027)

Ascii Apostrophe on Wikipedia

• Right single quotation mark (U+2019)

Unicode Right single quotation on Wikipedia

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

Accessing elements by type in javascript

var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
    var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
    for (;i<l;i++) {
        if (elems[i].type.toLowerCase() === "text") {
            ret.push(elems[i]);
        }
    }

    return ret;
}());

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

You can enable NuGet packages and update you dlls. so that it work. or you can update the package manually by going through the package manager in your vs if u know which version you require for your solution.

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

Stan0 intial idea is not a good idea. There can be multiple files with the same name. Very error prone implementation. Stan0's second idea is the correct way.

When you first upload the file to google drive store its id (in SharedPreferences is probably easiest) for later use

ie.

file= mDrive.files().insert(body).execute();      //initial insert of file to google drive

whereverYouWantToStoreIt= file.getId(); //now you have the guaranteed unique id 
                                        //of the file just inserted. Store it and use it 
                                        //whenever you need to fetch this file

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

Why does it work in Chrome and not Firefox?

The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS requests returning a status of 401 still send the subsequent request.

Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.

How can I get the OPTIONS request to send and respond consistently?

Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.

"No such file or directory" but it exists

I faced this error when I was trying to build Selenium source on Ubuntu. The simple shell script with correct shebang was not able to run even after I had all pre-requisites covered.

file file-name # helped me in understanding that CRLF ending were present in the file.

I opened the file in Vim and I could see that just because I once edited this file on a Windows machine, it was in DOS format. I converted the file to Unix format with below command:

dos2unix filename # actually helped me and things were fine.

I hope that we should take care whenever we edit files across platforms we should take care for the file formats as well.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

String dt = Date.Now.ToString("yyyy-MM-dd");

Now you got this for dt, 2010-09-09

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

How to delete an SVN project from SVN repository

In the case where you simply want to delete a project from the head revision, so that it no longer shows up in your repo when you run svn list file:///path/to/repo/ just run:

svn delete file:///path/to/repo/project 

However, if you need to delete all record of it in the repo, use another method.

What is REST call and how to send a REST call?

REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET or POST, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)

With REST, you might instead PUT /profiles/cHao and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.

http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

How can I get the current contents of an element in webdriver

My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))


element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()

Convert comma separated string of ints to int array

If you don't want to have the current error handling behaviour, it's really easy:

return text.Split(',').Select(x => int.Parse(x));

Otherwise, I'd use an extra helper method (as seen this morning!):

public static int? TryParseInt32(string text)
{
    int value;
    return int.TryParse(text, out value) ? value : (int?) null;
}

and:

return text.Split(',').Select<string, int?>(TryParseInt32)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or if you don't want to use the method group conversion:

return text.Split(',').Select(t => t.TryParseInt32(t)
                      .Where(x => x.HasValue)
                      .Select(x => x.Value);

or in query expression form:

return from t in text.Split(',')
       select TryParseInt32(t) into x
       where x.HasValue
       select x.Value;

How do I Validate the File Type of a File Upload?

From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:

<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>

A Generic error occurred in GDI+ in Bitmap.Save method

    // Once finished with the bitmap objects, we deallocate them.
    originalBMP.Dispose();

    bannerBMP.Dispose();
    oGraphics.Dispose();

This is a programming style that you'll regret sooner or later. Sooner is knocking on the door, you forgot one. You are not disposing newBitmap. Which keeps a lock on the file until the garbage collector runs. If it doesn't run then the second time you try to save to the same file you'll get the klaboom. GDI+ exceptions are too miserable to give a good diagnostic so serious head-scratching ensues. Beyond the thousands of googlable posts that mention this mistake.

Always favor using the using statement. Which never forgets to dispose an object, even if the code throws an exception.

using (var newBitmap = new Bitmap(thumbBMP)) {
    newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
}

Albeit that it is very unclear why you even create a new bitmap, saving thumbBMP should already be good enough. Anyhoo, give the rest of your disposable objects the same using love.

How can I check if a directory exists?

You may also use access in combination with opendir to determine if the directory exists, and, if the name exists, but is not a directory. For example:

/* test that dir exists (1 success, -1 does not exist, -2 not dir) */
int
xis_dir (const char *d)
{
    DIR *dirptr;

    if (access ( d, F_OK ) != -1 ) {
        // file exists
        if ((dirptr = opendir (d)) != NULL) {
            closedir (dirptr); /* d exists and is a directory */
        } else {
            return -2; /* d exists but is not a directory */
        }
    } else {
        return -1;     /* d does not exist */
    }

    return 1;
}

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

Find size of object instance in bytes in c#

Use Son Of Strike which has a command ObjSize.

Note that actual memory consumed is always larger than ObjSize reports due to a synkblk which resides directly before the object data.

Read more about both here MSDN Magazine Issue 2005 May - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects.

How to split a string in Haskell?

split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s

E.g.

split ';' "a;bb;ccc;;d"
> ["a","bb","ccc","","d"]

A single trailing delimiter will be dropped:

split ';' "a;bb;ccc;;d;"
> ["a","bb","ccc","","d"]

How do you give iframe 100% height

The problem with iframes not getting 100% height is not because they're unwieldy. The problem is that for them to get 100% height they need their parents to have 100% height. If one of the iframe's parents is not 100% tall the iframe won't be able to go beyond that parent's height.

So the best possible solution would be:

html, body, iframe { height: 100%; }

…given the iframe is directly under body. If the iframe has a parent between itself and the body, the iframe will still get the height of its parent. One must explicitly set the height of every parent to 100% as well (if that's what one wants).

Tested in:

Chrome 30, Firefox 24, Safari 6.0.5, Opera 16, IE 7, 8, 9 and 10

PS: I don't mean to be picky but the solution marked as correct doesn't work on Firefox 24 at the time of this writing, but worked on Chrome 30. Haven't tested on other browsers though. I came across the error on Firefox because the page I was testing had very little content... It could be it's my meager markup or the CSS reset altering the output, but if I experienced this error I guess the accepted answer doesn't work in every situation.

Update 2021

@Zeni suggested this in 2015:

iframe { height: 100vh }

...and indeed it does the trick!

Careful with positioning as it can potentially break the effect. Test thoroughly, you might not need positioning depending of what you're trying to achieve.

How to delete a cookie using jQuery?

it is the problem of misunderstand of cookie. Browsers recognize cookie values for not just keys also compare the options path & domain. So Browsers recognize different value which cookie values that key is 'name' with server setting option(path='/'; domain='mydomain.com') and key is 'name' with no option.

How to click a link whose href has a certain substring in Selenium?

With the help of xpath locator also, you can achieve the same.

Your statement would be:

driver.findElement(By.xpath(".//a[contains(@href,'long')]")).click();

And for clicking all the links contains long in the URL, you can use:-

List<WebElement> linksList = driver.findElements(By.xpath(".//a[contains(@href,'long')]"));

for (WebElement webElement : linksList){
         webElement.click();
}

Differences between socket.io and websockets

https://socket.io/docs/#What-Socket-IO-is-not (with my emphasis)

What Socket.IO is not

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the packet id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server either. Please see the protocol specification here.

// WARNING: the client will NOT be able to connect!
const client = io('ws://echo.websocket.org');

How to use BeanUtils.copyProperties?

There are two BeanUtils.copyProperties(parameter1, parameter2) in Java.

One is

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

Another is

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

Pay attention to the opposite position of parameters.

Trigger event when user scroll to specific element - with jQuery

Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.

Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.

function elementInView(el) {
  // The vertical distance between the top of the page and the top of the element.
  var elementOffset = $(el).offset().top;
  // The height of the element, including padding and borders.
  var elementOuterHeight = $(el).outerHeight();
  // Height of the window without margins, padding, borders.
  var windowHeight = $(window).height();
  // The vertical distance between the top of the page and the top of the viewport.
  var scrollOffset = $(this).scrollTop();

  if (elementOuterHeight < windowHeight) {
    // Element is smaller than viewport.
    if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
      // Element is completely inside viewport, reveal the element!
      return true;
    }
  } else {
    // Element is larger than the viewport, handle visibility differently.
    // Consider it visible as soon as it's top half has filled the viewport.
    if (scrollOffset > elementOffset) {
      // The top of the viewport has touched the top of the element, reveal the element!
      return true;
    }
  }
  return false;
}

Loop through columns and add string lengths as new columns

With dplyr and stringr you can use mutate_all:

> df %>% mutate_all(funs(length = str_length(.)))

     col1     col2 col1_length col2_length
1     abc adf qqwe           3           8
2    abcd        d           4           1
3       a        e           1           1
4 abcdefg        f           7           1

How to import/include a CSS file using PHP code and not HTML code?

<?php
  define('CSSPATH', 'template/css/'); //define css path
  $cssItem = 'style.css'; //css item to display
?>    
<html>
<head>
 <title>Including css</title>
  <link rel="stylesheet" href="<?php echo (CSSPATH . "$cssItem"); ?>" type="text/css">
</head>
<body>
...
...
</body>
</html>

YOUR CSS ITEM IS INCLUDED

Difference between "include" and "require" in php

In case of Include Program will not terminate and display warning on browser,On the other hand Require program will terminate and display fatal error in case of file not found.

How do I fix twitter-bootstrap on IE?

Not sure if it will fix your particular issue but worth sharing anyway.

I had issues with twitter boot strap in IE. No rounded corners. Navigation menu not collapsing. Spans not sitting in correct location, even some images not displaying.

Strangely, site works okay in IE when run through visual studio debugger, its once deployed to a server that the problem occurs.

Try using IE developer tools (F12 is keyboard shortcut) Check your browser mode and document mode. (its at the top along side the menu bar)

Problem happened for me as document was IE7 and browser was IE10 compatibility. I added a http header in IIS: Name X-UA-Compatible Value IE=EmulateIE9

Now the page loads as document - IE9 standards, browser IE10 compatibility and all the previous issues are resolved.

Hope this helps.

-tessi

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

You need just to follow those steps:

  1. Right Click on your project: Run (As) -> Maven clean
  2. Right Click on your project: Run (As) -> Maven install

After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it. it really works

Removing duplicates from a SQL query (not just "use distinct")

You need to tell the query what value to pick for the other columns, MIN or MAX seem like suitable choices.

 SELECT
   U.NAME, MIN(P.PIC_ID)
 FROM
   USERS U,
   PICTURES P,
   POSTINGS P1
 WHERE
   U.EMAIL_ID = P1.EMAIL_ID AND
   P1.PIC_ID = P.PIC_ID AND
   P.CAPTION LIKE '%car%'
 GROUP BY
   U.NAME;

Convert JSON format to CSV format for MS Excel

Using Python will be one easy way to achieve what you want.

I found one using Google.

"convert from json to csv using python" is an example.

How do you get centered content using Twitter Bootstrap?

My preferred method for centering blocks of information while maintaining responsiveness (mobile compatibility) is to place two empty span1 divs before and after the content you wish to center.

<div class="row-fluid">

    <div class="span1">
    </div>

        <div class="span10">
          <div class="hero-unit">
            <h1>Reading Resources</h1>
            <p>Read here...</p>
          </div>
        </div><!--/span-->

    <div class="span1">
    </div>

</div><!--/row-->

How to select the first row for each group in MySQL?

I based my answer on the title of your post only, as I don't know C# and didn't understand the given query. But in MySQL I suggest you try subselects. First get a set of primary keys of interesting columns then select data from those rows:

SELECT somecolumn, anothercolumn 
  FROM sometable 
 WHERE id IN (
               SELECT min(id) 
                 FROM sometable 
                GROUP BY somecolumn
             );

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

How do I adb pull ALL files of a folder present in SD Card

Directory pull is available on new android tools. ( I don't know from which version it was added, but its working on latest ADT 21.1 )

adb pull /sdcard/Robotium-Screenshots
pull: building file list...
pull: /sdcard/Robotium-Screenshots/090313-110415.jpg -> ./090313-110415.jpg
pull: /sdcard/Robotium-Screenshots/090313-110412.jpg -> ./090313-110412.jpg
pull: /sdcard/Robotium-Screenshots/090313-110408.jpg -> ./090313-110408.jpg
pull: /sdcard/Robotium-Screenshots/090313-110406.jpg -> ./090313-110406.jpg
pull: /sdcard/Robotium-Screenshots/090313-110404.jpg -> ./090313-110404.jpg
5 files pulled. 0 files skipped.
61 KB/s (338736 bytes in 5.409s)

UILabel is not auto-shrinking text to fit label size

minimumFontSize is deprecated in iOS 6.

So use minimumScaleFactor instead of minmimumFontSize.

lbl.adjustsFontSizeToFitWidth = YES
lbl.minimumScaleFactor = 0.5

Swift 5

lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5

When should I really use noexcept?

noexcept can dramatically improve performance of some operations. This does not happen at the level of generating machine code by the compiler, but by selecting the most effective algorithm: as others mentioned, you do this selection using function std::move_if_noexcept. For instance, the growth of std::vector (e.g., when we call reserve) must provide a strong exception-safety guarantee. If it knows that T's move constructor doesn't throw, it can just move every element. Otherwise it must copy all Ts. This has been described in detail in this post.

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

Array Size (Length) in C#

With the Length property.

int[] foo = new int[10];
int n = foo.Length; // n == 10

CRC32 C or C++ implementation

Use the Boost C++ libraries. There is a CRC included there and the license is good.

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How to Implement DOM Data Binding in JavaScript

I have gone through some basic javascript example using onkeypress and onchange event handlers for making binding view to our js and js to view

Here example plunker http://plnkr.co/edit/7hSOIFRTvqLAvdZT4Bcc?p=preview

<!DOCTYPE html>
<html>
<body>

    <p>Two way binding data.</p>

    <p>Binding data from  view to JS</p>

    <input type="text" onkeypress="myFunction()" id="myinput">
    <p id="myid"></p>
    <p>Binding data from  js to view</p>
    <input type="text" id="myid2" onkeypress="myFunction1()" oninput="myFunction1()">
    <p id="myid3" onkeypress="myFunction1()" id="myinput" oninput="myFunction1()"></p>

    <script>

        document.getElementById('myid2').value="myvalue from script";
        document.getElementById('myid3').innerHTML="myvalue from script";
        function myFunction() {
            document.getElementById('myid').innerHTML=document.getElementById('myinput').value;
        }
        document.getElementById("myinput").onchange=function(){

            myFunction();

        }
        document.getElementById("myinput").oninput=function(){

            myFunction();

        }

        function myFunction1() {

            document.getElementById('myid3').innerHTML=document.getElementById('myid2').value;
        }
    </script>

</body>
</html>

How can I get the last 7 characters of a PHP string?

umh.. like that?

$newstring = substr($dynamicstring, -7);

Oracle query to identify columns having special characters

You can use regular expressions for this, so I think this is what you want:

select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')

How to Test Facebook Connect Locally

I suggest creating a test app (for dev environment only) on https://developers.facebook.com/apps and set: Website with Facebook Login property to your localhost:[port] settings.
this option will work fine with no need to change hosts.
remember to change the appId back to your production app once you go live.

Edit - in the latest fb version you'll find it under the settings tab. enter image description here

Resolve Git merge conflicts in favor of their changes during a pull

VS Code (integrated Git) IDE Users:

If you want to accept all the incoming changes in the conflict file then do the following steps.

1. Go to command palette - Ctrl + Shift + P
2. Select the option - Merge Conflict: Accept All Incoming

Similarly you can do for other options like Accept All Both, Accept All Current etc.,

Difference between static memory allocation and dynamic memory allocation

Difference between STATIC MEMORY ALLOCATION & DYNAMIC MEMORY ALLOCATION

Memory is allocated before the execution of the program begins (During Compilation).
Memory is allocated during the execution of the program.

No memory allocation or deallocation actions are performed during Execution.
Memory Bindings are established and destroyed during the Execution.

Variables remain permanently allocated.
Allocated only when program unit is active.

Implemented using stacks and heaps.
Implemented using data segments.

Pointer is needed to accessing variables.
No need of Dynamically allocated pointers.

Faster execution than Dynamic.
Slower execution than static.

More memory Space required.
Less Memory space required.

Iif equivalent in C#

It's limited in that you can't put statements in there. You can only put values(or things that return/evaluate to values), to return

This works ('a' is a static int within class Blah)

Blah.a=Blah.a<5?1:8;

(round brackets are impicitly between the equals and the question mark).

This doesn't work.

Blah.a = Blah.a < 4 ? Console.WriteLine("asdf") : Console.WriteLine("34er");
or
Blah.a = Blah.a < 4 ? MessageBox.Show("asdf") : MessageBox.Show("34er");

So you can only use the c# ternary operator for returning values. So it's not quite like a shortened form of an if. Javascript and perhaps some other languages let you put statements in there.

How to convert an NSTimeInterval (seconds) into minutes

If you're targeting at or above iOS 8 or OS X 10.10, this just got a lot easier. The new NSDateComponentsFormatter class allows you to convert a given NSTimeInterval from its value in seconds to a localized string to show the user. For example:

Objective-C

NSTimeInterval interval = 326.4;

NSDateComponentsFormatter *componentFormatter = [[NSDateComponentsFormatter alloc] init];

componentFormatter.unitsStyle = NSDateComponentsFormatterUnitsStylePositional;
componentFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;

NSString *formattedString = [componentFormatter stringFromTimeInterval:interval];
NSLog(@"%@",formattedString); // 5:26

Swift

let interval = 326.4

let componentFormatter = NSDateComponentsFormatter()

componentFormatter.unitsStyle = .Positional
componentFormatter.zeroFormattingBehavior = .DropAll

if let formattedString = componentFormatter.stringFromTimeInterval(interval) {
    print(formattedString) // 5:26
}

NSDateCompnentsFormatter also allows for this output to be in longer forms. More info can be found in NSHipster's NSFormatter article. And depending on what classes you're already working with (if not NSTimeInterval), it may be more convenient to pass the formatter an instance of NSDateComponents, or two NSDate objects, which can be done as well via the following methods.

Objective-C

NSString *formattedString = [componentFormatter stringFromDate:<#(NSDate *)#> toDate:<#(NSDate *)#>];
NSString *formattedString = [componentFormatter stringFromDateComponents:<#(NSDateComponents *)#>];

Swift

if let formattedString = componentFormatter.stringFromDate(<#T##startDate: NSDate##NSDate#>, toDate: <#T##NSDate#>) {
    // ...
}

if let formattedString = componentFormatter.stringFromDateComponents(<#T##components: NSDateComponents##NSDateComponents#>) {
    // ...
}

C# Timer or Thread.Sleep

It's important to understand that your code will sleep for 50 seconds between ending one loop, and starting the next...

A timer will call your loop every 50 seconds, which isn't exactly the same.

They're both valid, but a timer is probably what you're looking for here.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I ran into a very similar issue.

I needed to use an old 32-bit DLL within a Web Application that was being developed on a 64-bit machine. I registered the 32-bit DLL into the windows\sysWOW64 folder using the version of regsrv32 in that folder.

Calls to the third party DLL worked from unit tests in Visual Studio but failed from the Web Application hosted in IIS on the same machine with the 80040154 error.

Changing the application pool to "Enable 32-Bit Applications" resolved the issue.

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

jquery - fastest way to remove all rows from a very large table

$("#your-table-id").empty();

That's as fast as you get.

What's the difference between & and && in MATLAB?

&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if or while loop expressions.

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

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

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

a tag as a submit button?

Give the form an id, and then:

document.getElementById("yourFormId").submit();

Best practice would probably be to give your link an id too, and get rid of the event handler:

document.getElementById("yourLinkId").onclick = function() {
    document.getElementById("yourFormId").submit();
}

jQuery validation: change default error message

Add this code in a separate file/script included after the validation plugin to override the messages, edit at will :)

jQuery.extend(jQuery.validator.messages, {
    required: "This field is required.",
    remote: "Please fix this field.",
    email: "Please enter a valid email address.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date (ISO).",
    number: "Please enter a valid number.",
    digits: "Please enter only digits.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    accept: "Please enter a value with a valid extension.",
    maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
    minlength: jQuery.validator.format("Please enter at least {0} characters."),
    rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
    range: jQuery.validator.format("Please enter a value between {0} and {1}."),
    max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
    min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});

Best practice for REST token-based authentication with JAX-RS and Jersey

This answer is all about authorization and it is a complement of my previous answer about authentication

Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.


Supporting role-based authorization with the @Secured annotation

Besides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.

Create an enumeration and define the roles according to your needs:

public enum Role {
    ROLE_1,
    ROLE_2,
    ROLE_3
}

Change the @Secured name binding annotation created before to support roles:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
    Role[] value() default {};
}

And then annotate the resource classes and methods with @Secured to perform the authorization. The method annotations will override the class annotations:

@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // But it's declared within a class annotated with @Secured({Role.ROLE_1})
        // So it only can be executed by the users who have the ROLE_1 role
        ...
    }

    @DELETE
    @Path("{id}")    
    @Produces(MediaType.APPLICATION_JSON)
    @Secured({Role.ROLE_1, Role.ROLE_2})
    public Response myOtherMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
        // The method annotation overrides the class annotation
        // So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
        ...
    }
}

Create a filter with the AUTHORIZATION priority, which is executed after the AUTHENTICATION priority filter defined previously.

The ResourceInfo can be used to get the resource Method and resource Class that will handle the request and then extract the @Secured annotations from them:

@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the resource class which matches with the requested URL
        // Extract the roles declared by it
        Class<?> resourceClass = resourceInfo.getResourceClass();
        List<Role> classRoles = extractRoles(resourceClass);

        // Get the resource method which matches with the requested URL
        // Extract the roles declared by it
        Method resourceMethod = resourceInfo.getResourceMethod();
        List<Role> methodRoles = extractRoles(resourceMethod);

        try {

            // Check if the user is allowed to execute the method
            // The method annotations override the class annotations
            if (methodRoles.isEmpty()) {
                checkPermissions(classRoles);
            } else {
                checkPermissions(methodRoles);
            }

        } catch (Exception e) {
            requestContext.abortWith(
                Response.status(Response.Status.FORBIDDEN).build());
        }
    }

    // Extract the roles from the annotated element
    private List<Role> extractRoles(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return new ArrayList<Role>();
        } else {
            Secured secured = annotatedElement.getAnnotation(Secured.class);
            if (secured == null) {
                return new ArrayList<Role>();
            } else {
                Role[] allowedRoles = secured.value();
                return Arrays.asList(allowedRoles);
            }
        }
    }

    private void checkPermissions(List<Role> allowedRoles) throws Exception {
        // Check if the user contains one of the allowed roles
        // Throw an Exception if the user has not permission to execute the method
    }
}

If the user has no permission to execute the operation, the request is aborted with a 403 (Forbidden).

To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext (which should be already set in the ContainerRequestContext) or inject it using CDI, depending on the approach you go for.

If a @Secured annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.

Supporting role-based authorization with JSR-250 annotations

Alternatively to defining the roles in the @Secured annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed, @PermitAll and @DenyAll.

JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:

So an authorization filter that checks JSR-250 annotations could be like:

@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        // @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
        if (method.isAnnotationPresent(DenyAll.class)) {
            refuseRequest();
        }

        // @RolesAllowed on the method takes precedence over @PermitAll
        RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
            return;
        }

        // @PermitAll on the method takes precedence over @RolesAllowed on the class
        if (method.isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // @DenyAll can't be attached to classes

        // @RolesAllowed on the class takes precedence over @PermitAll on the class
        rolesAllowed = 
            resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
        if (rolesAllowed != null) {
            performAuthorization(rolesAllowed.value(), requestContext);
        }

        // @PermitAll on the class
        if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
            // Do nothing
            return;
        }

        // Authentication is required for non-annotated methods
        if (!isAuthenticated(requestContext)) {
            refuseRequest();
        }
    }

    /**
     * Perform authorization based on roles.
     *
     * @param rolesAllowed
     * @param requestContext
     */
    private void performAuthorization(String[] rolesAllowed, 
                                      ContainerRequestContext requestContext) {

        if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
            refuseRequest();
        }

        for (final String role : rolesAllowed) {
            if (requestContext.getSecurityContext().isUserInRole(role)) {
                return;
            }
        }

        refuseRequest();
    }

    /**
     * Check if the user is authenticated.
     *
     * @param requestContext
     * @return
     */
    private boolean isAuthenticated(final ContainerRequestContext requestContext) {
        // Return true if the user is authenticated or false otherwise
        // An implementation could be like:
        // return requestContext.getSecurityContext().getUserPrincipal() != null;
    }

    /**
     * Refuse the request.
     */
    private void refuseRequest() {
        throw new AccessDeniedException(
            "You don't have permissions to perform this action.");
    }
}

Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature. If you use Jersey, you don't need to write your own filter, just use the existing implementation.

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening. The problem resolved for me by stopping IIS by running the command "iisreset -stop"

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

how to check for datatype in node js- specifically for integer

_x000D_
_x000D_
var val = ... //the value you want to check_x000D_
if(Number.isNaN(Number(val))){_x000D_
  console.log("This is NOT a number!");_x000D_
}else{_x000D_
  console.log("This IS a number!");_x000D_
}
_x000D_
_x000D_
_x000D_

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

Android widget: How to change the text of a button

This may be off topic, but for those who are struggling on how to exactly change also the font of the button text (that was my case and Skatephone's answer helped me) here's how I did it (if you made buttons ind design mode):

First we need to have the button's string name "converted" (it's a foul way to explain, but straightforward) into java from the xml, and so we paste the aforementioned code into our MainActivity.java

IMPORTANT! place the code under the OnCreate method!

import android.widget.RemoteViews;

RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");

Keep in mind:

my_layout has to be substituted with the xml file where your buttons are

Counter has to be substituted with the id name of your button ("@+id/ButtonName")

if you want to change the button text just insert the text in place of "Set button text here"

here comes the part where you change the font:

Now that you "converted" from xml to java, you can set a Typeface method for TextView. Paste the following code exactly under the previous one just described above

TextView txt = (TextView) findViewById(R.id.text_your_text_view_id);
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MyFontName.ttf");
        txt.setTypeface(font);

where in place of text_your_text_view_id you put your button's id name (like as previous code) and in place of MyFontName.ttf you put your desired font

WARNING! This assumes you already put your desired font into the assets/font folder. e.g. assets/fonts/MyFontName.ttf

How to use in jQuery :not and hasClass() to get a specific element without a class

jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.

For ex: x.hasClass('error');

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

Shell command to sum integers, one per line?

Paste typically merges lines of multiple files, but it can also be used to convert individual lines of a file into a single line. The delimiter flag allows you to pass a x+x type equation to bc.

paste -s -d+ infile | bc

Alternatively, when piping from stdin,

<commands> | paste -s -d+ - | bc

Hexadecimal value 0x00 is a invalid character

I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.

It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.

How to restore to a different database in sql server?

  • I have the same error as this topic when I restore a new database using an old database. (using .bak gives the same error)

  • I Changed the name of old database by name of new database (same this picture). It worked.

enter image description here

How do I order my SQLITE database in descending order, for an android app?

Query has two syntax, the syntax you are using, last column represents orderBy, you just need to specify on what column you want to do orderBy +"ASC" (or) orderBy +"DESC"

Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC"); 

Refer this documentation to understand more about query() method.

What encoding/code page is cmd.exe using?

Type

chcp

to see your current code page (as Dewfy already said).

Use

nlsinfo

to see all installed code pages and find out what your code page number means.

You need to have Windows Server 2003 Resource kit installed (works on Windows XP) to use nlsinfo.

What do the icons in Eclipse mean?

This is a fairly comprehensive list from the Eclipse documentation. If anyone knows of another list — maybe with more details, or just the most common icons — feel free to add it.

Latest: JDT Icons

2019-06: JDT Icons

2019-03: JDT Icons

2018-12: JDT Icons

2018-09: JDT Icons

Photon: JDT Icons

Oxygen: JDT Icons

Neon: JDT Icons

Mars: JDT Icons

Luna: JDT Icons

Kepler: JDT Icons

Juno: JDT Icons

Indigo: JDT Icons

Helios: JDT Icons

There are also some CDT icons at the bottom of this help page.

If you're a Subversion user, the icons you're looking for may actually belong to Subclipse; see this excellent answer for more on those.

Java Strings: "String s = new String("silly");"

It is a basic law that Strings in java are immutable and case sensitive.

How to initialise a string from NSData in Swift

This is how you should initialize the NSString:

Swift 2.X or older

let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)

Swift 3 or newer:

let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)

This doc explains the syntax.

FPDF utf-8 encoding (HOW-TO)

This answer didn't work for me, I needed to run html decode on the string also. See

iconv('UTF-8', 'windows-1252', html_entity_decode($str));

Props go to emfi from html_entity_decode in FPDF(using tFPDF extention)

How to remove all null elements from a ArrayList or String Array?

As of 2015, this is the best way (Java 8):

tourists.removeIf(Objects::isNull);

Note: This code will throw java.lang.UnsupportedOperationException for fixed-size lists (such as created with Arrays.asList), including immutable lists.

Retrieve version from maven pom.xml in code

To complement what @kieste has posted, which I think is the best way to have Maven build informations available in your code if you're using Spring-boot: the documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-info is very useful.

You just need to activate actuators, and add the properties you need in your application.properties or application.yml

Automatic property expansion using Maven

You can automatically expand info properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties’ via @..@ placeholders, e.g.

project.artifactId=myproject
project.name=Demo
project.version=X.X.X.X
project.description=Demo project for info endpoint
[email protected]@
[email protected]@
[email protected]@
[email protected]@

What is the JavaScript version of sleep()?

The problem with most solutions here is that they rewind the stack. This can be a big problem in some cases.In this example I show how to use iterators in different way to simulate real sleep

In this example the generator is calling it's own next() so once it's going, it's on his own.

var h=a();
h.next().value.r=h; //that's how U run it, best I came up with

//sleep without breaking stack !!!
function *a(){
    var obj= {};

    console.log("going to sleep....2s")

    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

    console.log("woke up");
    console.log("going to sleep no 2....2s")
    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

     console.log("woke up");
    console.log("going to sleep no 3....2s")

     setTimeout(function(){obj.r.next();},2000) 
     yield obj;

    console.log("done");

}

When to favor ng-if vs. ng-show/ng-hide?

Depends on your use case but to summarise the difference:

  1. ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.
  3. ng-if creates a child scope while ng-show/ng-hide does not

Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if compared to ng-show/ng-hide. In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.

Ultimately, the question you need to answer is whether you can remove element from DOM or not?

How to create a GUID in Excel?

As of modern version of Excel, there's the syntax with commas, not semicolons. I'm posting this answer for convenience of others so they don't have to replace the strings- We're all lazy... hrmp... human, right?

=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4))

Or, if you like me dislike when a guid screams and shouts and you, we can go lower-cased like this.

=LOWER(CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4)))

js window.open then print()

Turgut gave the right solution. Just for clarity, you need to add close after writing.

function openWin()
  {
    myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");


    myWindow.document.close(); //missing code


    myWindow.focus();
    myWindow.print(); 
  }

List Directories and get the name of the Directory

This will print all the subdirectories of the current directory:

print [name for name in os.listdir(".") if os.path.isdir(name)]

I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?

If you want the full pathnames of the directories, use abspath:

print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

How to force a list to be vertical using html css

Hope this is your structure:

   <ul> 
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
   </ul> 

By default, it will be add one after another row:

-----
-----
-----

if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:

|  |  |
|  |  |

li
{
   display:block;
   float:left;
   width:300px; /* adjust */
   height:150px; /* adjust */
   padding: 5px; /*adjust*/
}

Chrome ignores autocomplete="off"

I am posting this answer to bring an updated solution to this problem. I am currently using Chrome 49 and no given answer work for this one. I am also looking for a solution working with other browsers and previous versions.

Put this code on the beginning of your form

<div style="display: none;">
    <input type="text" autocomplete="new-password">
    <input type="password" autocomplete="new-password">
</div>

Then, for your real password field, use

<input type="password" name="password" autocomplete="new-password">

Comment this answer if this is no longer working or if you get an issue with another browser or version.

Approved on:

  • Chrome : 49
  • Firefox : 44, 45
  • Edge : 25
  • Internet Explorer : 11

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Django set default form values

As explained in Django docs, initial is not default.

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.

  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.

To implement that, a straightforward way is to combine initial and clean_<field>():

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

What are all the escape characters?

These are escape characters which are used to manipulate string.

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a form feed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

Read more about them from here.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

Dockerfile copy keep subdirectory structure

If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.

COPY . destinatio-directory/ 

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

Hot deploy on JBoss - how do I make JBoss "see" the change?

I have had the same problem, but think I've got it under control now.

Are you using eclipse or command line or ??

When I use the command line, I think I did "seam clean" or "seam undeploy" or maybe even "seam restart" followed by "seam explode". I probably tried all of these at one time or another never bothering to look up what each one does.

The idea is to remove the deployed war file from TWO places

1. $JBOSS_HOME/server/default/deploy
2. $PROJECT_HOME/exploded_archives

I'm pretty sure "seam undeploy" removes the 1st and "seam clean" removes the 2nd.

When I use eclipse (I use the free one), I first turn off "Project/Build Automatically" Then when I am ready to deploy I do either Project/Build Project or Project/Build All depending on what I've changed. When I change xhtml, Build Project is sufficient. When I change java source Build All works. It's possible these do the same things and the difference is in my imagination, but some combination of this stuff will work for you.

You have to watch the output though. Occasionally the app does not get cleaned or undeployed. This would result in not seeing your change. Sometimes I shut down the server first and then rebuild/clean/deploy the project.

Hope this helps.

TDR

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Try this It'll work perfect.

$('body.overflow-hidden').delegate('#skrollr-body','touchmove',function(e){
    e.preventDefault();
    console.log('Stop skrollrbody');
}).delegate('.mfp-auto-cursor .mfp-content','touchmove',function(e){
    e.stopPropagation();
    console.log('Scroll scroll');
});

React Router v4 - How to get current route?

Here is a solution using history Read more

import { createBrowserHistory } from "history";

const history = createBrowserHistory()

inside Router

<Router>
   {history.location.pathname}
</Router>

Reset Excel to default borders

I was having the same trouble with importing from Excel 2010 to Access, appending an "identical" table. Early on in the wizard it said not all my column names were valid, even though I checked them. It turns out that it saw an "empty" column with no column name. When I tried using the import wizard to create a new table instead, it worked. However, I noticed that it had added a blank column to the right of my data and called it "Field30". So I went back to the spreadsheet I was trying to import, selected the columns to the right of the data that I wanted, right-clicked and chose "clear contents." That did the trick and I was able to import the spreadsheet, appending it to my table.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

This answer simply applies the type=date attribute to the HTML input element and relies on the browser to supply a date picker. Note that even in 2017, not all browsers provide their own date picker, so you may want to provide a fall back.

All you have to do is add attributes to the property in the view model. Example for variable Ldate:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Public DateTime Ldate {get;set;}

Assuming you're using MVC 5 and Visual Studio 2013.

Read CSV file column by column

I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/

Here is one example:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
    try
    {
        in = new FileReader(csvFile);
        records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
        {
            if ( line == "" )
                line = line.concat(record.get(i));
            else
                line = line.concat("," + record.get(i));
        }
        System.out.println("read line: " + line);
    }

It automaticly recognize , and " but not ; (maybe it can be configured...).

My example file is:

col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"

And output is:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

Last line is considered like one value.

Convert LocalDate to LocalDateTime or java.sql.Timestamp

Since Joda is getting faded, someone might want to convert LocaltDate to LocalDateTime in Java 8. In Java 8 LocalDateTime it will give a way to create a LocalDateTime instance using a LocalDate and LocalTime. Check here.

public static LocalDateTime of(LocalDate date, LocalTime time)

Sample would be,

    // just to create a sample LocalDate
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
    LocalDate ld = LocalDate.parse("20180306", dtf);

    // convert ld into a LocalDateTime
    // We need to specify the LocalTime component here as well, it can be any accepted value
    LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00

Just for reference, For getting the epoch seconds below can be used,

    ZoneId zoneId = ZoneId.systemDefault();
    long epoch = ldt.atZone(zoneId).toEpochSecond(); 

    // If you only care about UTC
    long epochUTC = ldt.toEpochSecond(ZoneOffset.UTC);

How to remove an element from an array in Swift

As of Xcode 10+, and according to the WWDC 2018 session 223, "Embracing Algorithms," a good method going forward will be mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows

Apple's example:

var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]

phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."

see Apple's Documentation

So in the OP's example, removing animals[2], "chimps":

var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }

This method may be preferred because it scales well (linear vs quadratic), is readable and clean. Keep in mind that it only works in Xcode 10+, and as of writing this is in Beta.

Can we open pdf file using UIWebView on iOS?

An update to Martin Alléus's answer, to get the full screen whether it is a phone or a iPad without having to hard code:

CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];

NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

How do I list the symbols in a .so file

Try adding -l to the nm flags in order to get the source of each symbol. If the library is compiled with debugging info (gcc -g) this should be the source file and line number. As Konrad said, the object file / static library is probably unknown at this point.

What is JSONP, and why was it created?

Because you can ask the server to prepend a prefix to the returned JSON object. E.g

function_prefix(json_object);

in order for the browser to eval "inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.

In other words, you can achieve cross-domain data exchange.


Normally, XMLHttpRequest doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain) whereas:

<script src="some_other_domain/some_data.js&prefix=function_prefix>` one can access data from a domain different than from the origin.


Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix (i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.

IntelliJ does not show project folders

I encountered this problem when the .idea folder was accidentally added to SVN version control. When I took an update --- blooey! I subsequently removed the .idea folder from version control.

Append Char To String in C?

char* str = "blablabla";     

You should not modify this string at all. It resides in implementation defined read only region. Modifying it causes Undefined Behavior.

You need a char array not a string literal.

Good Read:
What is the difference between char a[] = "string"; and char *p = "string";

Get the current file name in gulp.src()

If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:

import * as debug from 'gulp-debug';

...

    return gulp.src('./examples/*.html')
        .pipe(debug({title: 'example src:'}))
        .pipe(gulp.dest('./build'));

(I also added a title).

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I ran into this issue because in the dependency injection setup I was missing a dependency of a repository that is a dependency of a controller:

services.AddScoped<IDependencyOne, DependencyOne>();    <-- I was missing this line!
services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();

POST request not allowed - 405 Not Allowed - nginx, even with headers included

In my case it was POST submission of a json to be processed and get a return value. I cross checked logs of my app server with and without nginx. What i got was my location was not getting appended to proxy_pass url and the version of HTTP protocol version is different.

  • Without nginx: "POST /xxQuery HTTP/1.1" 200 -
  • With nginx: "POST / HTTP/1.0" 405 -

My earlier location block was

location /xxQuery {
    proxy_method POST;
    proxy_pass http://127.0.0.1:xx00/;
    client_max_body_size 10M;
}

I changed it to

location /xxQuery {
    proxy_method POST;
    proxy_http_version 1.1;
    proxy_pass http://127.0.0.1:xx00/xxQuery;
    client_max_body_size 10M;
}

It worked.

How do I determine if my python shell is executing in 32bit or 64bit?

struct.calcsize("P") returns size of the bytes required to store a single pointer. On a 32-bit system, it would return 4 bytes. On a 64-bit system, it would return 8 bytes.

So the following would return 32 if you're running 32-bit python and 64 if you're running 64-bit python:

Python 2

import struct;print struct.calcsize("P") * 8

Python 3

import struct;print(struct.calcsize("P") * 8)

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Truncate a string straight JavaScript

Yes, substring works great:

stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"

var stringTruncate = function(str, length){
  var dots = str.length > length ? '...' : '';
  return str.substring(0, length)+dots;
};

How do I use the includes method in lodash to check if an object is in the collection?

You could use find to solve your problem

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

How can I save a screenshot directly to a file in Windows?

Thanks to TheSoftwareJedi for providing useful information about snapping tool in Windows 7. Shortcut to open Snipping tool : Go to Start, type sni And you will find the name in the list "Snipping Tool"

enter image description here

Position an element relative to its container

If you need to position an element relative to its containing element first you need to add position: relative to the container element. The child element you want to position relatively to the parent has to have position: absolute. The way that absolute positioning works is that it is done relative to the first relatively (or absolutely) positioned parent element. In case there is no relatively positioned parent, the element will be positioned relative to the root element (directly to the HTML element).

So if you want to position your child element to the top left of the parent container, you should do this:

.parent {
  position: relative;
} 

.child {
  position: absolute;
  top: 0;
  left: 0;  
}

You will benefit greatly from reading this article. Hope this helps!

intelliJ IDEA 13 error: please select Android SDK

File -> Invalidate Caches / Restart did the trick for me (which is always a good first try)

How to show and update echo on same line

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e.

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r

I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \ symbols in there.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

Convert char to int in C#

Has anyone considered using int.Parse() and int.TryParse() like this

int bar = int.Parse(foo.ToString());

Even better like this

int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
    //Do something to correct the problem
}

It's a lot safer and less error prone

How do I add a margin between bootstrap columns without wrapping

Change the number of @grid-columns. Then use -offset. Changing the number of columns will allow you to control the amount of space between columns. E.g.

variables.less (approx line 294).

@grid-columns:              20;

someName.html

<div class="row">
  <div class="col-md-4 col-md-offset-1">First column</div>
  <div class="col-md-13 col-md-offset-1">Second column</div>
</div>

What does `ValueError: cannot reindex from a duplicate axis` mean?

I wasted couple of hours on the same issue. In my case, I had to reset_index() of a dataframe before using apply function. Before merging, or looking up from another indexed dataset, you need to reset the index as 1 dataset can have only 1 Index.

git with IntelliJ IDEA: Could not read from remote repository

what @yabin ya says is a cool solution, just remind you that: if u still get the same problem,go to Settings-Version Control-GitHub and uncheck the Clone git repositories using ssh.

MongoDB logging all queries

I made a command line tool to activate the profiler activity and see the logs in a "tail"able way: "mongotail".

But the more interesting feature (also like tail) is to see the changes in "real time" with the -f option, and occasionally filter the result with grep to find a particular operation.

See documentation and installation instructions in: https://github.com/mrsarm/mongotail

Draw an X in CSS

You could just put the letter X in the HTML inside the div and then style it with css.

See JSFiddle: http://jsfiddle.net/uSwbN/

HTML:

<div id="orangeBox">
  <span id="x">X</span>
</div>

CSS:

#orangeBox {
  background: #f90;
  color: #fff;
  font-family: 'Helvetica', 'Arial', sans-serif;
  font-size: 2em;
  font-weight: bold;
  text-align: center;
  width: 40px;
  height: 40px;
  border-radius: 5px;
}

How to find all the dependencies of a table in sql server

There is builtin procedure to check dependents:
For an example ,

Execute sp_depends @objname=N'ssc.RegDash_RoutingAct'

image

How can I connect to Android with ADB over TCP?

I did get this working. Didn't use any usb cable.

  • app adb wireless.
  • Run it. That will set ip and port; Then in dos

    cd C:\Program Files\Android\android-sdk\platform-tools adb connect "192.168.2.22:8000 "enter"
    

Connected.

WCF error - There was no endpoint listening at

I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.

range() for floats

There will be of course some rounding errors, so this is not perfect, but this is what I use generally for applications, which don't require high precision. If you wanted to make this more accurate, you could add an extra argument to specify how to handle rounding errors. Perhaps passing a rounding function might make this extensible and allow the programmer to specify how to handle rounding errors.

arange = lambda start, stop, step: [i + step * i for i in range(int((stop - start) / step))]

If I write:

arange(0, 1, 0.1)

It will output:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

Extract a subset of a dataframe based on a condition involving a field

Here are the two main approaches. I prefer this one for its readability:

bar <- subset(foo, location == "there")

Note that you can string together many conditionals with & and | to create complex subsets.

The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there" returns a vector of T and F values that is the same length as the rows of foo. You can do this to return only rows where the condition returns true.

foo[foo$location == "there", ]

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.

Following your example code, try making a subclass of AbstractThing without implementing the m2 method and see what errors the compiler gives you. It will force you to implement this method.

Play a Sound with Python

For Windows, you can use winsound. It's built in

import winsound

winsound.PlaySound('sound.wav', winsound.SND_FILENAME)

You should be able to use ossaudiodev for linux:

from wave import open as waveOpen
from ossaudiodev import open as ossOpen
s = waveOpen('tada.wav','rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
try:
  from ossaudiodev import AFMT_S16_NE
except ImportError:
  from sys import byteorder
  if byteorder == "little":
    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
  else:
    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()

(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)

How to store Configuration file and read it using React

With webpack you can put env-specific config into the externals field in webpack.config.js

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? {
    serverUrl: "https://myserver.com"
  } : {
    serverUrl: "http://localhost:8090"
  })
}

If you want to store the configs in a separate JSON file, that's possible too, you can require that file and assign to Config:

externals: {
  'Config': JSON.stringify(process.env.NODE_ENV === 'production' ? require('./config.prod.json') : require('./config.dev.json'))
}

Then in your modules, you can use the config:

var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')

For React:

import Config from 'Config';
axios.get(this.app_url, {
        'headers': Config.headers
        }).then(...);

Not sure if it covers your use case but it's been working pretty well for us.

Function return value in PowerShell

The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.

Function StartingMain {
  $a = 1 + 3
  $b = 2 + 5
  $c = 3 + 7
  Return $a
}

Function StartingEnd($b) {
  Write-Host $b
}

StartingEnd(StartingMain)

This can also be done for an array. The example below will return "Text 2"

Function StartingMain {
  $a = ,@("Text 1","Text 2","Text 3")
  Return $a
}

Function StartingEnd($b) {
  Write-Host $b[1]
}

StartingEnd(StartingMain)

Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.

"Data too long for column" - why?

Varchar has its own limits. Maybe try changing datatype to text.!

How to import a Python class that is in a directory above?

Python is a modular system

Python doesn't rely on a file system

To load python code reliably, have that code in a module, and that module installed in python's library.

Installed modules can always be loaded from the top level namespace with import <name>


There is a great sample project available officially here: https://github.com/pypa/sampleproject

Basically, you can have a directory structure like so:

the_foo_project/
    setup.py  

    bar.py           # `import bar`
    foo/
      __init__.py    # `import foo`

      baz.py         # `import foo.baz`

      faz/           # `import foo.faz`
        __init__.py
        daz.py       # `import foo.faz.daz` ... etc.

.

Be sure to declare your setuptools.setup() in setup.py,

official example: https://github.com/pypa/sampleproject/blob/master/setup.py

In our case we probably want to export bar.py and foo/__init__.py, my brief example:

setup.py

#!/usr/bin/env python3

import setuptools

setuptools.setup(
    ...
    py_modules=['bar'],
    packages=['foo'],
    ...
    entry_points={}, 
        # Note, any changes to your setup.py, like adding to `packages`, or
        # changing `entry_points` will require the module to be reinstalled;
        # `python3 -m pip install --upgrade --editable ./the_foo_project
)

.

Now we can install our module into the python library; with pip, you can install the_foo_project into your python library in edit mode, so we can work on it in real time

python3 -m pip install --editable=./the_foo_project

# if you get a permission error, you can always use 
# `pip ... --user` to install in your user python library

.

Now from any python context, we can load our shared py_modules and packages

foo_script.py

#!/usr/bin/env python3

import bar
import foo

print(dir(bar))
print(dir(foo))

Best Timer for using in a Windows service

Both System.Timers.Timer and System.Threading.Timer will work for services.

The timers you want to avoid are System.Web.UI.Timer and System.Windows.Forms.Timer, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.

Use System.Timers.Timer like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):

using System;
using System.Timers;

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        // Normally, the timer is declared at the class level,
        // so that it stays in scope as long as it is needed.
        // If the timer is declared in a long-running method,  
        // KeepAlive must be used to prevent the JIT compiler 
        // from allowing aggressive garbage collection to occur 
        // before the method ends. (See end of method.)
        //System.Timers.Timer aTimer;

        // Create a timer with a ten second interval.
        aTimer = new System.Timers.Timer(10000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

        // Set the Interval to 2 seconds (2000 milliseconds).
        aTimer.Interval = 2000;
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

/* This code example produces output similar to the following:

Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
 */

If you choose System.Threading.Timer, you can use as follows:

using System;
using System.Threading;

class TimerExample
{
    static void Main()
    {
        AutoResetEvent autoEvent     = new AutoResetEvent(false);
        StatusChecker  statusChecker = new StatusChecker(10);

        // Create the delegate that invokes methods for the timer.
        TimerCallback timerDelegate = 
            new TimerCallback(statusChecker.CheckStatus);

        // Create a timer that signals the delegate to invoke 
        // CheckStatus after one second, and every 1/4 second 
        // thereafter.
        Console.WriteLine("{0} Creating timer.\n", 
            DateTime.Now.ToString("h:mm:ss.fff"));
        Timer stateTimer = 
                new Timer(timerDelegate, autoEvent, 1000, 250);

        // When autoEvent signals, change the period to every 
        // 1/2 second.
        autoEvent.WaitOne(5000, false);
        stateTimer.Change(0, 500);
        Console.WriteLine("\nChanging period.\n");

        // When autoEvent signals the second time, dispose of 
        // the timer.
        autoEvent.WaitOne(5000, false);
        stateTimer.Dispose();
        Console.WriteLine("\nDestroying timer.");
    }
}

class StatusChecker
{
    int invokeCount, maxCount;

    public StatusChecker(int count)
    {
        invokeCount  = 0;
        maxCount = count;
    }

    // This method is called by the timer delegate.
    public void CheckStatus(Object stateInfo)
    {
        AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
        Console.WriteLine("{0} Checking status {1,2}.", 
            DateTime.Now.ToString("h:mm:ss.fff"), 
            (++invokeCount).ToString());

        if(invokeCount == maxCount)
        {
            // Reset the counter and signal Main.
            invokeCount  = 0;
            autoEvent.Set();
        }
    }
}

Both examples comes from the MSDN pages.

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

This is how, I have been using a random user agent from a list of nearlly 1000 fake user agents

from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, OperatingSystem
software_names = [SoftwareName.ANDROID.value]
operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value, OperatingSystem.MAC.value]   

user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=1000)

# Get list of user agents.
user_agents = user_agent_rotator.get_user_agents()

user_agent_random = user_agent_rotator.get_random_user_agent()

Example

print(user_agent_random)

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36

For more details visit this link

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

AngularJS - Passing data between pages

If you only need to share data between views/scopes/controllers, the easiest way is to store it in $rootScope. However, if you need a shared function, it is better to define a service to do that.

How to find the sum of an array of numbers

You can also use reduceRight.

[1,2,3,4,5,6].reduceRight(function(a,b){return a+b;})

which results output as 21.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

AngularJS: How to run additional code after AngularJS has rendered a template?

i've had to do this quite often. i have a directive and need to do some jquery stuff after model stuff is fully loaded into the DOM. so i put my logic in the link: function of the directive and wrap the code in a setTimeout(function() { ..... }, 1); the setTimout will fire after the DOM is loaded and 1 milisecond is the shortest amount of time after DOM is loaded before code would execute. this seems to work for me but i do wish angular raised an event once a template was done loading so that directives used by that template could do jquery stuff and access DOM elements. hope this helps.

Why is “while ( !feof (file) )” always wrong?

feof() indicates if one has tried to read past the end of file. That means it has little predictive effect: if it is true, you are sure that the next input operation will fail (you aren't sure the previous one failed BTW), but if it is false, you aren't sure the next input operation will succeed. More over, input operations may fail for other reasons than the end of file (a format error for formatted input, a pure IO failure -- disk failure, network timeout -- for all input kinds), so even if you could be predictive about the end of file (and anybody who has tried to implement Ada one, which is predictive, will tell you it can complex if you need to skip spaces, and that it has undesirable effects on interactive devices -- sometimes forcing the input of the next line before starting the handling of the previous one), you would have to be able to handle a failure.

So the correct idiom in C is to loop with the IO operation success as loop condition, and then test the cause of the failure. For instance:

while (fgets(line, sizeof(line), file)) {
    /* note that fgets don't strip the terminating \n, checking its
       presence allow to handle lines longer that sizeof(line), not showed here */
    ...
}
if (ferror(file)) {
   /* IO failure */
} else if (feof(file)) {
   /* format error (not possible with fgets, but would be with fscanf) or end of file */
} else {
   /* format error (not possible with fgets, but would be with fscanf) */
}

How do I remove  from the beginning of a file?

Same problem, different solution.

One line in the PHP file was printing out XML headers (which use the same begin/end tags as PHP). Looks like the code within these tags set the encoding, and was executed within PHP which resulted in the strange characters. Either way here's the solution:

# Original
$xml_string = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;";

# fixed
$xml_string = "<" . "?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">";

C#: How do you edit items and subitems in a listview?

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    li = listView1.GetItemAt(e.X, e.Y);
    X = e.X;
    Y = e.Y;
}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
    int nStart = X;
    int spos = 0;
    int epos = listView1.Columns[1].Width;
    for (int i = 0; i < listView1.Columns.Count; i++)
    {
        if (nStart > spos && nStart < epos)
        {
            subItemSelected = i;
            break;
        }

        spos = epos;
        epos += listView1.Columns[i].Width;
    }
    li.SubItems[subItemSelected].Text = "9";
}

SQL Server database backup restore on lower version

Another way to do this is to use "Copy Database" feature:

Find by right clicking the source database > "Tasks" > "Copy Database".

You can copy the database to a lower version of SQL Server Instance. This worked for me from a SQL Server 2008 R2 (SP1) - 10.50.2789.0 to Microsoft SQL Server 2008 (SP2) - 10.0.3798.0

How to generate random number in Bash?

If you are using a linux system you can get a random number out of /dev/random or /dev/urandom. Be carefull /dev/random will block if there are not enough random numbers available. If you need speed over randomness use /dev/urandom.

These "files" will be filled with random numbers generated by the operating system. It depends on the implementation of /dev/random on your system if you get true or pseudo random numbers. True random numbers are generated with help form noise gathered from device drivers like mouse, hard drive, network.

You can get random numbers from the file with dd

Check if item is in an array / list

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.

How to unload a package without restarting R

Note also that you can only use unload() once. If you use it a second time without rerunning library(), y'll get the not very informative error message invalid 'name' argument:

library(vegan)
#> Loading required package: permute
#> Loading required package: lattice
#> This is vegan 2.5-6
detach("package:vegan",  unload=TRUE)
detach("package:vegan",  unload=TRUE)
#> Error in detach("package:vegan", unload = TRUE): invalid 'name' argument

Created on 2020-05-09 by the reprex package (v0.3.0)

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

At least one item in your list is either not three dimensional, or its second or third dimension does not match the other elements. If only the first dimension does not match, the arrays are still matched, but as individual objects, no attempt is made to reconcile them into a new (four dimensional) array. Some examples are below:

That is, the offending element's shape != (?, 224, 3),
or ndim != 3 (with the ? being non-negative integer).
That is what is giving you the error.

You'll need to fix that, to be able to turn your list into a four (or three) dimensional array. Without context, it is impossible to say if you want to lose a dimension from the 3D items or add one to the 2D items (in the first case), or change the second or third dimension (in the second case).


Here's an example of the error:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224))]
>>> np.array(a)
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

or, different type of input, but the same error:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224,13))]
>>> np.array(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

Alternatively, similar but with a different error message:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,100,3))]
>>> np.array(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (224,224,3) into shape (224)

But the following will work, albeit with different results than (presumably) intended:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((10,224,3))]
>>> np.array(a)
# long output omitted
>>> newa = np.array(a)
>>> newa.shape
3  # oops
>>> newa.dtype
dtype('O')
>>> newa[0].shape
(224, 224, 3)
>>> newa[1].shape
(224, 224, 3)
>>> newa[2].shape
(10, 224, 3)
>>> 

How to provide shadow to Button

Try this if this works for you

enter image description here

android:background="@drawable/drop_shadow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="3dp"
        android:paddingTop="3dp"
        android:paddingRight="4dp"
        android:paddingBottom="5dp"

jquery change div text

I think this will do:

$('#'+div_id+' .widget-head > span').text("new dialog title");

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Try this

ALTER DATABASE XXXX  SET RECOVERY SIMPLE

use XXXX

declare @log_File_Name varchar(200) 

select @log_File_Name  = name from sysfiles where filename like '%LDF'

declare @i int = FILE_IDEX ( @log_File_Name)

dbcc shrinkfile ( @i , 50) 

continuing execution after an exception is thrown in java

Try this:

try
{
    throw new InvalidEmployeeTypeException();
    input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
      //do error handling
}

continue;

Comparing two byte arrays in .NET

I developed a method that slightly beats memcmp() (plinth's answer) and very slighly beats EqualBytesLongUnrolled() (Arek Bulski's answer) on my PC. Basically, it unrolls the loop by 4 instead of 8.

Update 30 Mar. 2019:

Starting in .NET core 3.0, we have SIMD support!

This solution is fastest by a considerable margin on my PC:

#if NETCOREAPP3_0
using System.Runtime.Intrinsics.X86;
#endif
…

public static unsafe bool Compare(byte[] arr0, byte[] arr1)
{
    if (arr0 == arr1)
    {
        return true;
    }
    if (arr0 == null || arr1 == null)
    {
        return false;
    }
    if (arr0.Length != arr1.Length)
    {
        return false;
    }
    if (arr0.Length == 0)
    {
        return true;
    }
    fixed (byte* b0 = arr0, b1 = arr1)
    {
#if NETCOREAPP3_0
        if (Avx2.IsSupported)
        {
            return Compare256(b0, b1, arr0.Length);
        }
        else if (Sse2.IsSupported)
        {
            return Compare128(b0, b1, arr0.Length);
        }
        else
#endif
        {
            return Compare64(b0, b1, arr0.Length);
        }
    }
}
#if NETCOREAPP3_0
public static unsafe bool Compare256(byte* b0, byte* b1, int length)
{
    byte* lastAddr = b0 + length;
    byte* lastAddrMinus128 = lastAddr - 128;
    const int mask = -1;
    while (b0 < lastAddrMinus128) // unroll the loop so that we are comparing 128 bytes at a time.
    {
        if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != mask)
        {
            return false;
        }
        if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 32), Avx.LoadVector256(b1 + 32))) != mask)
        {
            return false;
        }
        if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 64), Avx.LoadVector256(b1 + 64))) != mask)
        {
            return false;
        }
        if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 96), Avx.LoadVector256(b1 + 96))) != mask)
        {
            return false;
        }
        b0 += 128;
        b1 += 128;
    }
    while (b0 < lastAddr)
    {
        if (*b0 != *b1) return false;
        b0++;
        b1++;
    }
    return true;
}
public static unsafe bool Compare128(byte* b0, byte* b1, int length)
{
    byte* lastAddr = b0 + length;
    byte* lastAddrMinus64 = lastAddr - 64;
    const int mask = 0xFFFF;
    while (b0 < lastAddrMinus64) // unroll the loop so that we are comparing 64 bytes at a time.
    {
        if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != mask)
        {
            return false;
        }
        if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 16), Sse2.LoadVector128(b1 + 16))) != mask)
        {
            return false;
        }
        if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 32), Sse2.LoadVector128(b1 + 32))) != mask)
        {
            return false;
        }
        if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 48), Sse2.LoadVector128(b1 + 48))) != mask)
        {
            return false;
        }
        b0 += 64;
        b1 += 64;
    }
    while (b0 < lastAddr)
    {
        if (*b0 != *b1) return false;
        b0++;
        b1++;
    }
    return true;
}
#endif
public static unsafe bool Compare64(byte* b0, byte* b1, int length)
{
    byte* lastAddr = b0 + length;
    byte* lastAddrMinus32 = lastAddr - 32;
    while (b0 < lastAddrMinus32) // unroll the loop so that we are comparing 32 bytes at a time.
    {
        if (*(ulong*)b0 != *(ulong*)b1) return false;
        if (*(ulong*)(b0 + 8) != *(ulong*)(b1 + 8)) return false;
        if (*(ulong*)(b0 + 16) != *(ulong*)(b1 + 16)) return false;
        if (*(ulong*)(b0 + 24) != *(ulong*)(b1 + 24)) return false;
        b0 += 32;
        b1 += 32;
    }
    while (b0 < lastAddr)
    {
        if (*b0 != *b1) return false;
        b0++;
        b1++;
    }
    return true;
}

How can I wrap text in a label using WPF?

To wrap text in the label control, change the the template of label as follows:

<Style x:Key="ErrorBoxStyle" TargetType="{x:Type Label}">
    <Setter Property="BorderBrush" Value="#FFF08A73"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Foreground" Value="Red"/>
    <Setter Property="Background" Value="#FFFFE3DF"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Padding" Value="5"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Label}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" CornerRadius="5" HorizontalAlignment="Stretch">
                     
                    <TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}"/>
                </Border>
                    
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

Change the Bootstrap Modal effect

Here is pure Bootstrap 4 with CSS 3 solution.

<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
.fade2 {
    transform: scale(0.9);
    opacity: 0;
    transition: all .2s linear;
    display: block !important;
}

.fade2.show {
    opacity: 1;
    transform: scale(1);
}
$('#exampleModal').modal();

function afterModalTransition(e) {
  e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
    setTimeout( () => afterModalTransition(this), 200);
})

Full example here.

Maybe it will help someone.

--

Thank you @DavidDomain too.

How to find length of a string array?

Since you haven't initialized car yet so it has no existence in JVM(Java Virtual Machine) so you have to initialize it first.

For instance :

car = new String{"Porsche","Lamborghini"};

Now your code will run fine.

INPUT:

String car [];
car = new String{"Porsche","Lamborghini"};
System.out.println(car.length);

OUTPUT:

2

How to pass macro definition from "make" command line arguments (-D) to C source code?

Just use a specific variable for that.

$ cat Makefile 
all:
    echo foo | gcc $(USER_DEFINES) -E -xc - 

$ make USER_DEFINES="-Dfoo=one"
echo foo | gcc -Dfoo=one -E -xc - 
...
one

$ make USER_DEFINES="-Dfoo=bar"
echo foo | gcc -Dfoo=bar -E -xc - 
...
bar

$ make 
echo foo | gcc  -E -xc - 
...
foo

How to center cards in bootstrap 4?

You can also use Bootstrap 4 flex classes

Like: .align-item-center and .justify-content-center

We can use these classes identically for all device view.

Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center

.text-center class is used to align text in center.

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

chart.js load totally new data

ChartJS 2.6 supports data reference replacement (see Note in update(config) documentation). So when you have your Chart, you could basically just do this:

myChart.data.labels = ['1am', '2am', '3am', '4am'];
myChart.data.datasets[0].data = [0, 12, 35, 36];
myChart.update();

It doesn't do the animation you'd get from adding points, but existing points on the graph will be animated.

How to get IP address of running docker container

You can start your container with the flag -P. This "assigns" a random port to the exposed port of your image.

With docker port <container id> you can see the randomly choosen port. Access is then possible via localhost:port.

asp.net mvc3 return raw html to view

That looks fine, unless you want to pass it as Model string

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string model = "<HTML></HTML>";
        return View(model);
    }
}

@model string
@{
    ViewBag.Title = "Index";
}

@Html.Raw(Model)

jquery 3.0 url.indexOf error

Update all your code that calls load function like,

$(window).load(function() { ... });

To

$(window).on('load', function() { ... });

jquery.js:9612 Uncaught TypeError: url.indexOf is not a function

This error message comes from jQuery.fn.load function.

I've come across the same issue on my application. After some digging, I found this statement in jQuery blog,

.load, .unload, and .error, deprecated since jQuery 1.8, are no more. Use .on() to register listeners.

I simply just change how my jQuery objects call the load function like above. And everything works as expected.

Conditionally hide CommandField or ButtonField in Gridview

To conditionally control view of Template/Command fields, use RowDataBound event of Gridview, like:

    <asp:GridView ID="gv1" OnRowDataBound="gv1_RowDataBound"
              runat="server" AutoGenerateColumns="False" DataKeyNames="Id" >
    <Columns>   
        ...        
           <asp:TemplateField HeaderText="Order Status" 
HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"> 
                 <ItemTemplate> 
                       <asp:Label ID="lblOrderStatus" runat="server"
Text='<%# Bind("OrderStatus") %>'></asp:Label> 
                 </ItemTemplate>
                 <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                 <ItemStyle HorizontalAlign="Center"></ItemStyle>
           </asp:TemplateField>  
        ...

            <asp:CommandField ShowSelectButton="True" SelectText="Select" />

    </Columns>
                </asp:GridView>

and following:

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Label lblOrderStatus=(Label) e.Row.Cells[4].FindControl("lblOrderStatus");

        if (lblOrderStatus.Text== "Ordered")
        {
            lblOrderStatus.ForeColor = System.Drawing.Color.DarkBlue;
            LinkButton bt = (LinkButton)e.Row.Cells[5].Controls[0];
            bt.Visible = false;
            e.Row.BackColor = System.Drawing.Color.LightGray;
        }
    }

Broken references in Virtualenvs

Anyone who is using pipenv (and you should!) can simply use these two commands — without having the venv activated:

rm -rf `pipenv --venv` # remove the broken venv
pipenv install --dev   # reinstall the venv from pipfile 

Hide password with "•••••••" in a textField

You can do this by using properties of textfield from Attribute inspector

Tap on Your Textfield from storyboard and go to Attribute inspector , and just check the checkbox of "Secure Text Entry" SS is added for graphical overview to achieve same