Programs & Examples On #Model driven

An interface to support model component of the Struts2 MVC architecture.

Mask for an Input to allow phone numbers?

Angular5 and 6:

angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property

remove host and add @HostListener

 @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io

Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask

Official documentation link https://angular.io/guide/attribute-directives#respond-to-user-initiated-events

Angular2 and 4:

Plunker >= RC.5

original

One way you could do it is using a directive that injects NgControl and manipulates the value

(for details see inline comments)

@Directive({
  selector: '[ngModel][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)': 'onInputChange($event.target.value, true)'
  }
})
export class PhoneMask {
  constructor(public model: NgControl) {}

  onInputChange(event, backspace) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');
    // special handling of backspace necessary otherwise
    // deleting of non-numeric characters is not recognized
    // this laves room for improvement for example if you delete in the 
    // middle of the string
    if (backspace) {
      newVal = newVal.substring(0, newVal.length - 1);
    } 

    // don't show braces for empty value
    if (newVal.length == 0) {
      newVal = '';
    } 
    // don't show braces for empty groups at the end
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);       
  }
}
@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form [ngFormModel]="form">
    <input type="text" phone [(ngModel)]="data" ngControl="phone"> 
  </form>
  `,
  directives: [PhoneMask]
})
export class App {
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      phone: ['']
    })
  }
}

Plunker example <= RC.5

When to use pthread_exit() and when to use pthread_join() in Linux?

When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.

It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.

HTML5 Form Input Pattern Currency Format

Another answer for this would be

^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{2}|)$

This will match a string of:

  • one or more numbers with out the decimal place (\d+)
  • any number of commas each of which must be followed by 3 numbers and have upto 3 numbers before it (\d{1,3})(\,\d{3}|)*

Each or which can have a decimal place which must be followed by 2 numbers (.\d{2}|)

What's the difference between returning value or Promise.resolve from then()

The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb"). Returning a promise from an onFulfilled() handler kicks off promise resolution. That's how promise chaining works.

How to know the size of the string in bytes?

From MSDN:

A String object is a sequential collection of System.Char objects that represent a string.

So you can use this:

var howManyBytes = yourString.Length * sizeof(Char);

Reading a string with scanf

I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.

char str[]  
  1. array of values of type char, with its own address in memory
  2. array of values of type char, with its own address in memory as many consecutive addresses as elements in the array
  3. including termination null character '\0' &str, &str[0] and str, all three represent the same location in memory which is address of the first element of the array str

    char *strPtr = &str[0]; //declaration and initialization

alternatively, you can split this in two:

char *strPtr; strPtr = &str[0];
  1. strPtr is a pointer to a char
  2. strPtr points at array str
  3. strPtr is a variable with its own address in memory
  4. strPtr is a variable that stores value of address &str[0]
  5. strPtr own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])
  6. &strPtr represents the address of strPtr itself

I think that you could declare a pointer to a pointer as:

char **vPtr = &strPtr;  

declares and initializes with address of strPtr pointer

Alternatively you could split in two:

char **vPtr;
*vPtr = &strPtr
  1. *vPtr points at strPtr pointer
  2. *vPtr is a variable with its own address in memory
  3. *vPtr is a variable that stores value of address &strPtr
  4. final comment: you can not do str++, str address is a const, but you can do strPtr++

Laravel blank white screen

for anyone who get blank page even after making storage accessible for displaying errors put these two lines at first lines of public/index.php to see what is happening at least. for me this error was there :Class 'PDO' not found in /var/www/***/config/database.php on line 16

error_reporting(E_ALL);
ini_set('display_errors', 1);

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

How to update a value, given a key in a hashmap?

@Matthew's solution is the simplest and will perform well enough in most cases.

If you need high performance, AtomicInteger is a better solution ala @BalusC.

However, a faster solution (provided thread safety is not an issue) is to use TObjectIntHashMap which provides a increment(key) method and uses primitives and less objects than creating AtomicIntegers. e.g.

TObjectIntHashMap<String> map = new TObjectIntHashMap<String>()
map.increment("aaa");

How to trap on UIViewAlertForUnsatisfiableConstraints?

This usually appears when you want to use UIActivityViewController in iPad.

Add below, before you present the controller to mark the arrow.

activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC

I assume you already have below, if not, add together:

activityViewController.popoverPresentationController?.sourceView = self.view

List<object>.RemoveAll - How to create an appropriate Predicate

This should work (where enquiryId is the id you need to match against):

vehicles.RemoveAll(vehicle => vehicle.EnquiryID == enquiryId);

What this does is passes each vehicle in the list into the lambda predicate, evaluating the predicate. If the predicate returns true (ie. vehicle.EnquiryID == enquiryId), then the current vehicle will be removed from the list.

If you know the types of the objects in your collections, then using the generic collections is a better approach. It avoids casting when retrieving objects from the collections, but can also avoid boxing if the items in the collection are value types (which can cause performance issues).

Vba macro to copy row from table if value in table meets condition

That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.

Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
    CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
    , Unique:=False

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Android: Tabs at the BOTTOM

This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :

ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...

maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.

Remove Object from Array using JavaScript

Performance

Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

For all browsers:

  • fast/fastest solutions when element not exists: A and B
  • fast/fastest solutions for big arrays: C
  • fast/fastest solutions for big arrays when element exists: H
  • quite slow solutions for small arrays: F and G
  • quite slow solutions for big arrays: D, E and F

enter image description here

Details

I perform 4 tests cases:

  • small array (10 elements) and element exists - you can run it HERE
  • small array (10 elements) and element NOT exists - you can run it HERE
  • big array (milion elements) and element exists - you can run it HERE
  • big array (milion elements) and element NOT exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I

_x000D_
_x000D_
function A(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  if(idx>=0) arr.splice(idx, 1);
  return arr;
}


function B(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}


function C(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  delete arr[idx];
  return arr;
}


function D(arr, name) {
  return arr.filter(el => el.name != name);
}


function E(arr, name) {
  let result = [];
  arr.forEach(o => o.name==name || result.push(o));
  return result;
}


function F(arr, name) {
  return _.reject(arr, el => el.name == name);
}


function G(arr, name) {
  let o = arr.find(o => o.name==name);
  return _.without(arr,o);
}


function H(arr, name) {
  $.each(arr, function(i){
      if(arr[i].name === 'Kristian') {
          arr.splice(i,1);
          return false;
      }
  });
  return arr;
}


function I(arr, name) {
  return $.grep(arr,o => o.name!=name);
}








// Test
let test1 = [   
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},  
];

let test2 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

let test3 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);

[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

Avoid printStackTrace(); use a logger call instead

Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders. I think a better replacement could be log.error("errors happend in XXX", e) This will also print out whole information which is easy reading than e.printStackTrace()

How do I get current scope dom-element in AngularJS controller?

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

How to restart adb from root to user mode?

adb kill-server and adb start-server only control the adb daemon on the PC side. You need to restart adbd daemon on the device itself after reverting the service.adb.root property change done by adb root:

~$ adb shell id
uid=2000(shell) gid=2000(shell)

~$ adb root
restarting adbd as root

~$ adb shell id
uid=0(root) gid=0(root)

~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'

~$ adb shell id
uid=2000(shell) gid=2000(shell)

How do I solve the INSTALL_FAILED_DEXOPT error?

Make sure you have all the SDK's you need installed and Gradle is targeting the right version.

I was having the same issue, but it was caused by me updating my device to Android 5.0 and then forgetting to change all my builds to target it.

How to check the extension of a filename in a bash script?

You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.

If you feel comfortable with using the extension you can use grep to see if it matches.

mysql: see all open connections to a given database?

You can invoke MySQL show status command

show status like 'Conn%';

For more info read Show open database connections

C#: New line and tab characters in strings

    StringBuilder SqlScript = new StringBuilder();

    foreach (var file in lstScripts)
    {
        var input = File.ReadAllText(file.FilePath);
        SqlScript.AppendFormat(input, Environment.NewLine);
    }

http://afzal-gujrat.blogspot.com/

Submitting the value of a disabled input field

I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.

Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.

You can use the readonly property in your input field

<input type="text" readonly="readonly" />

For vs. while in C programming?

One common misunderstanding withwhile/for loops I've seen is that their efficiency differs. While loops and for loops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.

For loops are simply syntactically sugared while loops, and make iteration code faster to write.

When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the while and for syntaxes are lost, and they become exactly the same.

how to open a page in new tab on button click in asp.net?

Add this Script  
<script type = "text/javascript">
 function SetTarget() {
     document.forms[0].target = "_blank";
 }
</script>
and 
<asp:Button ID="BTNpRINT"  runat="server" Text="PRINT"  CssClass="btn btn-primary"  OnClick="BTNpRINT_Click" OnClientClick = "SetTarget();"/>    
and 
protected void BTNpRINT_Click(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("~/Print.aspx?ID={0}",txtInv.Text));
    }

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

Failed to load ApplicationContext for JUnit test of Spring controller

Solved by adding the following dependency into pom.xml file :

<dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
</dependency>

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

I had very similar problem today and solution was as it is..

$email = Array("Zaffar Saffee" => "[email protected]");
        $schedule->command('cmd:mycmd')
                 ->everyMinute()
                 ->sendOutputTo("/home/forge/dev.mysite.com/storage/logs/cron.log")
                 ->emailWrittenOutputTo($email);

It laravel 5.2 though...

my basic problem was , I was passing string instead of array so, error was

->emailWrittenOutputTo('[email protected]'); // string, we need an array

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

         ` Adding the following to pom.xml will resolve the issue.      <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </pluginRepository>
   </pluginRepositories>
    
   <repositories>
        <repository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
   </repositories>   `

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

the data you have entered a table(tbldomare) aren't match a data you have assigned primary key table. write between tbldomare and add this word (with nocheck) then execute your code.

for example you entered a table tbldomar this data

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);

and you assigned a foreign key table to accept only 1,2,3.

you have two solutions one is delete the data you have entered a table then execute the code. another is write this word (with nocheck) put it between your table name and add like this

ALTER TABLE  tblDomare with nocheck
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Git keeps prompting me for a password

As static_rtti said above, change

https://github.com/username/repo.git
git://github.com/username/repo.git

to

ssh://[email protected]/username/repo.git

I myself changed the https in the .git/config file to ssh, but it still wasn't working. Then I saw that you must change github.com to [email protected]. A good way to get the actual correct URL is to go to your project page and click this:

Change HTTPS to SSH to get the right URL

Then add this URL to the configuration file.

Import JSON file in React

One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

import Profile from './components/profile';

This answer explains more.

Stratified Train/Test-split in scikit-learn

In addition to the accepted answer by @Andreas Mueller, just want to add that as @tangy mentioned above:

StratifiedShuffleSplit most closely resembles train_test_split(stratify = y) with added features of:

  1. stratify by default
  2. by specifying n_splits, it repeatedly splits the data

Which data type for latitude and longitude?

You can use the data type point - combines (x,y) which can be your lat / long. Occupies 16 bytes: 2 float8 numbers internally.

Or make it two columns of type float (= float8 or double precision). 8 bytes each.
Or real (= float4) if additional precision is not needed. 4 bytes each.
Or even numeric if you need absolute precision. 2 bytes for each group of 4 digits, plus 3 - 8 bytes overhead.

Read the fine manual about numeric types and geometric types.


The geometry and geography data types are provided by the additional module PostGIS and occupy one column in your table. Each occupies 32 bytes for a point. There is some additional overhead like an SRID in there. These types store (long/lat), not (lat/long).

Start reading the PostGIS manual here.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.

  1. Right click on "Indexes" and click "New Index..." (note: this is disabled if you have the table open in design view)

enter image description here

  1. Give new index a name ("U_Name"), check "Unique", and click "Add..."

enter image description here

  1. Select "Name" column in the next windown

enter image description here

  1. Click OK in both windows

What should a JSON service return on failure / error

For server/protocol errors I would try to be as REST/HTTP as possible (Compare this with you typing in URL's in your browser):

  • a non existing item is called (/persons/{non-existing-id-here}). Return a 404.
  • an unexpected error on the server (code bug) occured. Return a 500.
  • the client user is not authorised to get the resource. Return a 401.

For domain/business logic specific errors I would say the protocol is used in the right way and there's no server internal error, so respond with an error JSON/XML object or whatever you prefer to describe your data with (Compare this with you filling in forms on a website):

  • a user wants to change its account name but the user did not yet verify its account by clicking a link in an email which was sent to the user. Return {"error":"Account not verified"} or whatever.
  • a user wants to order a book, but the book was sold (state changed in DB) and can't be ordered anymore. Return {"error":"Book already sold"}.

Checking whether the pip is installed?

$ which pip

or

 $ pip -V 

execute this command into your terminal. It should display the location of executable file eg. /usr/local/bin/pip and the second command will display the version if the pip is installed correctly.

How to call javascript function on page load in asp.net

<html>
<head>
<script type="text/javascript">
function GetTimeZoneOffset() {
    var d = new Date()
    var gmtOffSet = -d.getTimezoneOffset();
    var gmtHours = Math.floor(gmtOffSet / 60);
    var GMTMin = Math.abs(gmtOffSet % 60);
    var dot = ".";
    var retVal = "" + gmtHours + dot + GMTMin;
    document.getElementById('<%= offSet.ClientID%>').value = retVal;
}

</script>
</head>
<body onload="GetTimeZoneOffset()">
    <asp:HiddenField ID="clientDateTime" runat="server" />
    <asp:HiddenField ID="offSet" runat="server" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</body>
</html>

key point to notice here is,body has an attribute onload. Just give it a function name and that function will be called on page load.


Alternatively, you can also call the function on page load event like this

<html>
<head>
<script type="text/javascript">

window.onload = load();

function load() {
    var d = new Date()
    var gmtOffSet = -d.getTimezoneOffset();
    var gmtHours = Math.floor(gmtOffSet / 60);
    var GMTMin = Math.abs(gmtOffSet % 60);
    var dot = ".";
    var retVal = "" + gmtHours + dot + GMTMin;
    document.getElementById('<%= offSet.ClientID%>').value = retVal;
}

</script>
</head>
<body >
    <asp:HiddenField ID="clientDateTime" runat="server" />
    <asp:HiddenField ID="offSet" runat="server" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></body>
</body>
</html>

Failed to find Build Tools revision 23.0.1

While running react-native In case you have installed 23.0.3 and it is asking for 23.0.1 simply in your application project directory. Open anroid/app/build.gradle and change buildToolsVersion "23.0.3"

enter image description here

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening:

Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl https://bootstrap.pypa.io/get-pip.py | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

Using jQuery to center a DIV on the screen

You can use CSS alone to center like so:

Working Example

_x000D_
_x000D_
.center{_x000D_
    position: absolute;_x000D_
    height: 50px;_x000D_
    width: 50px;_x000D_
    background:red;_x000D_
    top:calc(50% - 50px/2); /* height divided by 2*/_x000D_
    left:calc(50% - 50px/2); /* width divided by 2*/_x000D_
}
_x000D_
<div class="center"></div>
_x000D_
_x000D_
_x000D_

calc() allows you to do basic calculations in css.

MDN Documentation for calc()
Browser support table

How to write a cursor inside a stored procedure in SQL Server 2008

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

An alternative to the already provided ways is to simply filter on the column like so

df = df.where(F.col('columnNameHere').isNull())

This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.

How can I convert a string to a float in mysql?

mysql> SELECT CAST(4 AS DECIMAL(4,3));
+-------------------------+
| CAST(4 AS DECIMAL(4,3)) |
+-------------------------+
|                   4.000 |
+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('4.5s' AS DECIMAL(4,3));
+------------------------------+
| CAST('4.5s' AS DECIMAL(4,3)) |
+------------------------------+
|                        4.500 |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT CAST('a4.5s' AS DECIMAL(4,3));
+-------------------------------+
| CAST('a4.5s' AS DECIMAL(4,3)) |
+-------------------------------+
|                         0.000 |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

Testing if a checkbox is checked with jQuery

You can try this:

$('#studentTypeCheck').is(":checked");

How to show what a commit did?

TL;DR

git show <commit>


Show

To show what a commit did with stats:

git show <commit> --stat

Log

To show commit log with differences introduced for each commit in a range:

git log -p <commit1> <commit2>

What is <commit>?

Each commit has a unique id we reference here as <commit>. The unique id is an SHA-1 hash – a checksum of the content you’re storing plus a header. #TMI

If you don't know your <commit>:

  1. git log to view the commit history

  2. Find the commit you care about.

Returning Month Name in SQL Server Query

Have you tried DATENAME(MONTH, S0.OrderDateTime) ?

How to do a redirect to another route with react-router?

With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.

import { Router } from 'react-router';

export default class Foo extends Component {

  static get contextTypes() {
    return {
      router: React.PropTypes.object.isRequired,
    };
  }

  handleClick() {
    this.context.router.push('/some-path');
  }
}

How can I install MacVim on OS X?

  • Step 1. Install homebrew from here: http://brew.sh
  • Step 1.1. Run export PATH=/usr/local/bin:$PATH
  • Step 2. Run brew update
  • Step 3. Run brew install vim && brew install macvim
  • Step 4. Run brew link macvim

You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade every once in a while to upgrade them.

This includes the installation of the CLI mvim and the mac application (which both point to the same thing).

I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.

In Mongoose, how do I sort by date? (node.js)

You can also sort by the _id field. For example, to get the most recent record, you can do,

const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });

It's much quicker too, because I'm more than willing to bet that your date field is not indexed.

Using jquery to get element's position relative to viewport

Look into the Dimensions plugin, specifically scrollTop()/scrollLeft(). Information can be found at http://api.jquery.com/scrollTop.

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

C++ JSON Serialization

For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.

I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :

Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.

For example you can serialize like that :

    // Random class initialization
    com::class1* aObject = new com::class1();

    for (int i=0; i<10; i++){
            aObject->setData(i,i);
    }      

    aObject->pdata = new char[7];
    for (int i=0; i<7; i++){
            aObject->pdata[i] = 7-i;
    }
    // dictionary initialization
    cjson::dictionary aDict("./data/dictionary.xml");

    // json transformation
    std::string aJson = aDict.toJson<com::class1>(aObject);

    // print encoded class
    cout << aJson << std::endl ;

To deserialize data it works like that:

    // decode the object
    com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);

    // modify data
    aDecodedObject->setData(4,22);

    // json transformation
    aJson = aDict.toJson<com::class1>(aDecodedObject);

    // print encoded class
    cout << aJson << std::endl ;

Ouptuts:

>:~/cjson$ ./main
{"_index":54,"_inner":  {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$ 

Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.

Not equal <> != operator on NULL

Old question, but the following might offer some more detail.

null represents no value or an unknown value. It doesn’t specify why there is no value, which can lead to some ambiguity.

Suppose you run a query like this:

SELECT *
FROM orders
WHERE delivered=ordered;

that is, you are looking for rows where the ordered and delivered dates are the same.

What is to be expected when one or both columns are null?

Because at least one of the dates is unknown, you cannot expect to say that the 2 dates are the same. This is also the case when both dates are unknown: how can they be the same if we don’t even know what they are?

For this reason, any expression treating null as a value must fail. In this case, it will not match. This is also the case if you try the following:

SELECT *
FROM orders
WHERE delivered<>ordered;

Again, how can we say that two values are not the same if we don’t know what they are.

SQL has a specific test for missing values:

IS NULL

Specifically it is not comparing values, but rather it seeks out missing values.

Finally, as regards the != operator, as far as I am aware, it is not actually in any of the standards, but it is very widely supported. It was added to make programmers from some languages feel more at home. Frankly, if a programmer has difficulty remembering what language they’re using, they’re off to a bad start.

How to add buttons at top of map fragment API v2 layout

extending de Almeida's answer I am editing code little bit here. since previous code was hiding gps location icon I did following way which worked better.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"

>

<RadioGroup 
    android:id="@+id/radio_group_list_selector"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:orientation="horizontal" 
    android:background="#80000000"
    android:padding="4dp" >

    <RadioButton
        android:id="@+id/radioPopular"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="@string/Popular"
        android:gravity="center_horizontal|center_vertical"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioAZ"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/AZ"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />

    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioCategory"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/Category"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton2"
        android:textColor="@drawable/textcolor_radiobutton" />
    <View
        android:id="@+id/VerticalLine"
        android:layout_width="1dip"
        android:layout_height="match_parent"
        android:background="#aaa" />

    <RadioButton
        android:id="@+id/radioNearBy"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/NearBy"
        android:layout_weight="1"
        android:button="@null"
        android:background="@drawable/shape_radiobutton3"
        android:textColor="@drawable/textcolor_radiobutton" />
</RadioGroup>

<fragment
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:scrollbars="vertical" />

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

Is there a way to make a DIV unselectable?

As Johannes has already suggested, a background-image is probally the best way to achieve this in CSS alone.

A JavaScript solution would also have to affect "dragstart" to be effective across all popular browsers.

JavaScript:

<div onselectstart="return false;" ondragstart="return false;">your text</div>

jQuery:

var _preventDefault = function(evt) { evt.preventDefault(); };
$("div").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);

Rich

Simple argparse example wanted: 1 argument, 3 results

I went through all the examples and answers and in a way or another they didn't address my need. So I will list her a scenario that I need more help and I hope this can explain the idea more.

Initial Problem

I need to develop a tool which is getting a file to process it and it needs some optional configuration file to be used to configure the tool.

so what I need is something like the following

mytool.py file.text -config config-file.json

The solution

Here is the solution code

import argparse

def main():
    parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
    parser.add_argument('filename', help="Input file either text, image or video")
    # parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
    # parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
    parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

    args = parser.parse_args()
    
    filename = args.filename
    configfile = args.config_file

    print("The file to be processed is", filename)
    print("The config file is", configfile)

    if args.debug:
        print("Debug mode enabled")
    else:
        print("Debug mode disabled")

    print("and all arguments are: ", args)

if __name__ == '__main__':
    main()

I will show the solution in multiple enhancements to show the idea

First Round: List the arguments

List all input as mandatory inputs so second argument will be

parser.add_argument('config_file', help="a JSON file to load the initial configuration ")

When we get the help command for this tool we find the following outcome

(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename     Input file either text, image or video
  config_file  a JSON file to load the initial configuration

optional arguments:
  -h, --help   show this help message and exit

and when I execute it as the following

(base) > python .\argparser_example.py filename.txt configfile.json

the outcome will be

The file to be processed is filename.txt
The config file is configfile.json
and all arguments are:  Namespace(config_file='configfile.json', filename='filename.txt')

But the config file should be optional, I removed it from the arguments

(base) > python .\argparser_example.py filename.txt

The outcome will be is:

usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c

Which means we have a problem in the tool

Second Round : Make it optimal

So to make it optional I modified the program as follows

    parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)

The help outcome should be

usage: argparser_example.py [-h] [-c CONFIG] filename

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename              Input file either text, image or video

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        a JSON file to load the initial configuration

so when I execute the program

(base) > python .\argparser_example.py filename.txt

the outcome will be

The file to be processed is filename.txt
The config file is configFile.json
and all arguments are:  Namespace(config_file='configFile.json', filename='filename.txt')

with arguments like

(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json

The outcome will be

The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are:  Namespace(config_file='anotherConfig.json', filename='filename.txt')

Round 3: Enhancements

to change the flag name from --config_file to --config while we keep the variable name as is we modify the code to include dest='config_file' as the following:

parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')

and the command will be

(base) > python .\argparser_example.py filename.txt --config anotherConfig.json

To add the support for having a debug mode flag, we need to add a flag in the arguments to support a boolean debug flag. To implement it i added the following:

    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

the tool command will be:

(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug

the outcome will be

The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are:  Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')

How to split a string in Ruby and get all items except the first one?

You probably mistyped a few things. From what I gather, you start with a string such as:

string = "test1, test2, test3, test4, test5"

Then you want to split it to keep only the significant substrings:

array = string.split(/, /)

And in the end you only need all the elements excluding the first one:

# We extract and remove the first element from array
first_element = array.shift

# Now array contains the expected result, you can check it with
puts array.inspect

Did that answer your question ?

How to increase editor font size?

Very Simple .

Go to File then Settings then Select Editor then Font and change the size .

File -> Settings -> Editor -> Colors & Fonts -> Font.

Session 'app': Error Launching activity

Try reinstalling the app, this solved the error for me. The trick was that, I uninstalled my app, but Android didn't truly uninstall it. On my phone, there is a guest user (my sister uses it sometimes). If you uninstall the app from your main user, it will still be available on the phone, but only for the guest user. It looks like Android Studio can't handle this case. I guess it detects that the app is installed, so it will not be reinstalled again for the current user, hence the OS can't access and launch the activity. Nice bug, I'll report it.

Align button to the right

Maybe you can use float:right;:

_x000D_
_x000D_
.one {_x000D_
  padding-left: 1em;_x000D_
  text-color: white;_x000D_
   display:inline; _x000D_
}_x000D_
.two {_x000D_
  background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
  float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
 _x000D_
  </head>_x000D_
  <body>_x000D_
      <div class="row">_x000D_
       <h3 class="one">Text</h3>_x000D_
       <button class="btn btn-secondary pull-right">Button</button>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

I corrected this error as there was a syntax error or some unwanted characters in the query, but MySQL was not able to catch it. I was using and in between multiple fields during update, e.g.

update user 
set token='lamblala', 
    accessverion='dummy' and 
    key='somekey' 
where user = 'myself'

The problem in above query can be resolved by replacing and with comma(,)

Why is my Spring @Autowired field null?

I think you have missed to instruct spring to scan classes with annotation.

You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.

@Service, @Component etc annotations add meta description.

Spring only injects instances of those classes which are either created as bean or marked with annotation.

Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.

Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

How can I get a list of all classes within current module in Python?

I frequently find myself writing command line utilities wherein the first argument is meant to refer to one of many different classes. For example ./something.py feature command —-arguments, where Feature is a class and command is a method on that class. Here's a base class that makes this easy.

The assumption is that this base class resides in a directory alongside all of its subclasses. You can then call ArgBaseClass(foo = bar).load_subclasses() which will return a dictionary. For example, if the directory looks like this:

  • arg_base_class.py
  • feature.py

Assuming feature.py implements class Feature(ArgBaseClass), then the above invocation of load_subclasses will return { 'feature' : <Feature object> }. The same kwargs (foo = bar) will be passed into the Feature class.

#!/usr/bin/env python3
import os, pkgutil, importlib, inspect

class ArgBaseClass():
    # Assign all keyword arguments as properties on self, and keep the kwargs for later.
    def __init__(self, **kwargs):
        self._kwargs = kwargs
        for (k, v) in kwargs.items():
            setattr(self, k, v)
        ms = inspect.getmembers(self, predicate=inspect.ismethod)
        self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])

    # Add the names of the methods to a parser object.
    def _parse_arguments(self, parser):
        parser.add_argument('method', choices=list(self.methods))
        return parser

    # Instantiate one of each of the subclasses of this class.
    def load_subclasses(self):
        module_dir = os.path.dirname(__file__)
        module_name = os.path.basename(os.path.normpath(module_dir))
        parent_class = self.__class__
        modules = {}
        # Load all the modules it the package:
        for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
            modules[name] = importlib.import_module('.' + name, module_name)

        # Instantiate one of each class, passing the keyword arguments.
        ret = {}
        for cls in parent_class.__subclasses__():
            path = cls.__module__.split('.')
            ret[path[-1]] = cls(**self._kwargs)
        return ret

How can I reset eclipse to default settings?

Delete the .metadata folder in your workspace.

delete all from table

You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.

TRUNCATE TABLE table_name

Regular expression for address field validation

Regex is a very bad choice for this kind of task. Try to find a web service or an address database or a product which can clean address data instead.

Related:

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

what is the use of "response.setContentType("text/html")" in servlet

You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

downloading all the files in a directory with cURL

OK, considering that you are using Windows, the most simple way to do that is to use the standard ftp tool bundled with it. I base the following solution on Windows XP, hoping it'll work as well (or with minor modifications) on other versions.

First of all, you need to create a batch (script) file for the ftp program, containing instructions for it. Name it as you want, and put into it:

curl -u login:pass ftp.myftpsite.com/iiumlabs* -O

open ftp.myftpsite.com
login
pass
mget *
quit

The first line opens a connection to the ftp server at ftp.myftpsite.com. The two following lines specify the login, and the password which ftp will ask for (replace login and pass with just the login and password, without any keywords). Then, you use mget * to get all files. Instead of the *, you can use any wildcard. Finally, you use quit to close the ftp program without interactive prompt.

If you needed to enter some directory first, add a cd command before mget. It should be pretty straightforward.

Finally, write that file and run ftp like this:

ftp -i -s:yourscript

where -i disables interactivity (asking before downloading files), and -s specifies path to the script you created.


Sadly, file transfer over SSH is not natively supported in Windows. But for that case, you'd probably want to use PuTTy tools anyway. The one of particular interest for this case would be pscp which is practically the PuTTy counter-part of the openssh scp command.

The syntax is similar to copy command, and it supports wildcards:

pscp -batch [email protected]:iiumlabs* .

If you authenticate using a key file, you should pass it using -i path-to-key-file. If you use password, -pw pass. It can also reuse sessions saved using PuTTy, using the load -load your-session-name argument.

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

Function names in C++: Capitalize or not?

Do as you wish, as long as your are consistent among your dev. group. every few years the conventions changes..... (remmeber nIntVAr)...

Loop inside React JSX

I use this:

gridItems = this.state.applications.map(app =>
          <ApplicationItem key={app.Id} app={app } />
);

PS: never forget the key or you will have a lot of warnings!

How to set custom ActionBar color / style?

Another possibility of making.

actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));

How to perform element-wise multiplication of two lists?

Fairly intuitive way of doing this:

a = [1,2,3,4]
b = [2,3,4,5]
ab = []                        #Create empty list
for i in range(0, len(a)):
     ab.append(a[i]*b[i])      #Adds each element to the list

Using C# regular expressions to remove HTML tags

The correct answer is don't do that, use the HTML Agility Pack.

Edited to add:

To shamelessly steal from the comment below by jesse, and to avoid being accused of inadequately answering the question after all this time, here's a simple, reliable snippet using the HTML Agility Pack that works with even most imperfectly formed, capricious bits of HTML:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Properties.Resources.HtmlContents);
var text = doc.DocumentNode.SelectNodes("//body//text()").Select(node => node.InnerText);
StringBuilder output = new StringBuilder();
foreach (string line in text)
{
   output.AppendLine(line);
}
string textOnly = HttpUtility.HtmlDecode(output.ToString());

There are very few defensible cases for using a regular expression for parsing HTML, as HTML can't be parsed correctly without a context-awareness that's very painful to provide even in a nontraditional regex engine. You can get part way there with a RegEx, but you'll need to do manual verifications.

Html Agility Pack can provide you a robust solution that will reduce the need to manually fix up the aberrations that can result from naively treating HTML as a context-free grammar.

A regular expression may get you mostly what you want most of the time, but it will fail on very common cases. If you can find a better/faster parser than HTML Agility Pack, go for it, but please don't subject the world to more broken HTML hackery.

Reading/writing an INI file

Here is my class, works like a charm :

public static class IniFileManager
{


    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section,
        string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section,
             string key, string def, StringBuilder retVal,
        int size, string filePath);
    [DllImport("kernel32.dll")]
    private static extern int GetPrivateProfileSection(string lpAppName,
             byte[] lpszReturnBuffer, int nSize, string lpFileName);


    /// <summary>
    /// Write Data to the INI File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// Section name
    /// <PARAM name="Key"></PARAM>
    /// Key Name
    /// <PARAM name="Value"></PARAM>
    /// Value Name
    public static void IniWriteValue(string sPath,string Section, string Key, string Value)
    {
        WritePrivateProfileString(Section, Key, Value, sPath);
    }

    /// <summary>
    /// Read Data Value From the Ini File
    /// </summary>
    /// <PARAM name="Section"></PARAM>
    /// <PARAM name="Key"></PARAM>
    /// <PARAM name="Path"></PARAM>
    /// <returns></returns>
    public static string IniReadValue(string sPath,string Section, string Key)
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(Section, Key, "", temp,
                                        255, sPath);
        return temp.ToString();

    }

}

The use is obviouse since its a static class, just call IniFileManager.IniWriteValue for readsing a section or IniFileManager.IniReadValue for reading a section.

Jenkins: Is there any way to cleanup Jenkins workspace?

If you want to manually clean it up, for me with my version of jenkins (didn't appear to need an extra plugin installed, but who knows), there is a "workspace" link on the left column, click on your project, then on "workspace", then a "Wipe out current workspace" link appears beneath it on the left hand side column. screenshot

Converting Hexadecimal String to Decimal Integer

It looks like there's an extra space character in your string. You can use trim() to remove leading and trailing whitespaces:

temp1 = Integer.parseInt(display.getText().trim(), 16 );

Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.

WooCommerce - get category for product page

$product->get_categories() is deprecated since version 3.0! Use wc_get_product_category_list instead.

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html

SQL Server Profiler - How to filter trace to only display events from one database?

In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.

Assuming you have the Tuning template selected, to filter:

  • Click the "Events Selection" tab
  • Click the "Column Filters" button
  • Check Show all Columns (Right Side Down)
  • Select "DatabaseName", click the plus next to Like in the right-hand pane, and type your database name.

I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.

Rename multiple files based on pattern in Unix

There are several ways, but using rename will probably be the easiest.

Using one version of rename:

rename 's/^fgh/jkl/' fgh*

Using another version of rename (same as Judy2K's answer):

rename fgh jkl fgh*

You should check your platform's man page to see which of the above applies.

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

java: use StringBuilder to insert at the beginning

StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
    sb.insert(0, Integer.toString(i));
}

Warning: It defeats the purpose of StringBuilder, but it does what you asked.


Better technique (although still not ideal):

  1. Reverse each string you want to insert.
  2. Append each string to a StringBuilder.
  3. Reverse the entire StringBuilder when you're done.

This will turn an O(n²) solution into O(n).

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

Content Type application/soap+xml; charset=utf-8 was not supported by service

For me, it was very difficult to identify the problem because of a large number of methods and class involved.

What I did is commented (removed) some methods from the WebService interface and try, and then comment another bunch of methods and try, I kept doing this until I found the method that cause the problem.

In my case, it was using a complex object which cannot be serialized.

Good luck!

Finding Variable Type in JavaScript

typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. You can also use instanceof to test if an object is of a specific type.

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

What is the difference between active and passive FTP?

Active Mode—The client issues a PORT command to the server signaling that it will “actively” provide an IP and port number to open the Data Connection back to the client.

Passive Mode—The client issues a PASV command to indicate that it will wait “passively” for the server to supply an IP and port number, after which the client will create a Data Connection to the server.

There are lots of good answers above, but this blog post includes some helpful graphics and gives a pretty solid explanation: https://titanftp.com/2018/08/23/what-is-the-difference-between-active-and-passive-ftp/

How do you synchronise projects to GitHub with Android Studio?

Android Studio 3.0

I love how easy this is in Android Studio.

1. Enter your GitHub login info

In Android Studio go to File > Settings > Version Control > GitHub. Then enter your GitHub username and password. (You only have to do this step once. For future projects you can skip it.)

enter image description here

2. Share your project

With your Android Studio project open, go to VCS > Import into Version Control > Share Project on GitHub.

Then click Share and OK.

enter image description here

That's all!

How do I get video durations with YouTube API version 3?

You will have to make a call to the YouTube data API's video resource after you make the search call. You can put up to 50 video IDs in a search, so you won't have to call it for each element.

https://developers.google.com/youtube/v3/docs/videos/list

You'll want to set part=contentDetails, because the duration is there.

For example, the following call:

https://www.googleapis.com/youtube/v3/videos?id=9bZkp7q19f0&part=contentDetails&key={YOUR_API_KEY}

Gives this result:

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/ny1S4th-ku477VARrY_U4tIqcTw\"",
 "items": [
  {

   "id": "9bZkp7q19f0",
   "kind": "youtube#video",
   "etag": "\"XlbeM5oNbUofJuiuGi6IkumnZR8/HN8ILnw-DBXyCcTsc7JG0z51BGg\"",
   "contentDetails": {
    "duration": "PT4M13S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "false",
    "licensedContent": true,
    "regionRestriction": {
     "blocked": [
      "DE"
     ]
    }
   }
  }
 ]
}

The time is formatted as an ISO 8601 string. PT stands for Time Duration, 4M is 4 minutes, and 13S is 13 seconds.

Close pre-existing figures in matplotlib when running from eclipse

You can close a figure by calling matplotlib.pyplot.close, for example:

from numpy import *
import matplotlib.pyplot as plt
from scipy import *

t = linspace(0, 0.1,1000)
w = 60*2*pi


fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)

You can also close all open figures by calling matplotlib.pyplot.close("all")

How does one convert a grayscale image to RGB in OpenCV (Python)?

I am promoting my comment to an answer:

The easy way is:

You could draw in the original 'frame' itself instead of using gray image.

The hard way (method you were trying to implement):

backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) is the correct syntax.

Where does Oracle SQL Developer store connections?

SqlDeveloper stores all the connections in a file named

connections.xml

In windows XP you can find the file in location

C:\Documents and Settings\<username>\Application Data\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml

In Windows 7 you will find it in location

C:\Users\<username>\AppData\Roaming\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml

Does Python have a string 'contains' substring method?

Does Python have a string contains substring method?

99% of use cases will be covered using the keyword, in, which returns True or False:

'substring' in any_string

For the use case of getting the index, use str.find (which returns -1 on failure, and has optional positional arguments):

start = 0
stop = len(any_string)
any_string.find('substring', start, stop)

or str.index (like find but raises ValueError on failure):

start = 100 
end = 1000
any_string.index('substring', start, end)

Explanation

Use the in comparison operator because

  1. the language intends its usage, and
  2. other Python programmers will expect you to use it.
>>> 'foo' in '**foo**'
True

The opposite (complement), which the original question asked for, is not in:

>>> 'foo' not in '**foo**' # returns False
False

This is semantically the same as not 'foo' in '**foo**' but it's much more readable and explicitly provided for in the language as a readability improvement.

Avoid using __contains__

The "contains" method implements the behavior for in. This example,

str.__contains__('**foo**', 'foo')

returns True. You could also call this function from the instance of the superstring:

'**foo**'.__contains__('foo')

But don't. Methods that start with underscores are considered semantically non-public. The only reason to use this is when implementing or extending the in and not in functionality (e.g. if subclassing str):

class NoisyString(str):
    def __contains__(self, other):
        print(f'testing if "{other}" in "{self}"')
        return super(NoisyString, self).__contains__(other)

ns = NoisyString('a string with a substring inside')

and now:

>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True

Don't use find and index to test for "contains"

Don't use the following string methods to test for "contains":

>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2

>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    '**oo**'.index('foo')
ValueError: substring not found

Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the in comparison operator.

Also, these are not drop-in replacements for in. You may have to handle the exception or -1 cases, and if they return 0 (because they found the substring at the beginning) the boolean interpretation is False instead of True.

If you really mean not any_string.startswith(substring) then say it.

Performance comparisons

We can compare various ways of accomplishing the same goal.

import timeit

def in_(s, other):
    return other in s

def contains(s, other):
    return s.__contains__(other)

def find(s, other):
    return s.find(other) != -1

def index(s, other):
    try:
        s.index(other)
    except ValueError:
        return False
    else:
        return True



perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}

And now we see that using in is much faster than the others. Less time to do an equivalent operation is better:

>>> perf_dict
{'in:True': 0.16450627865128808,
 'in:False': 0.1609668098178645,
 '__contains__:True': 0.24355481654697542,
 '__contains__:False': 0.24382793854783813,
 'find:True': 0.3067379407923454,
 'find:False': 0.29860888058124146,
 'index:True': 0.29647137792585454,
 'index:False': 0.5502287584545229}

Restart node upon changing a file

Various NPM packages are available to make this task easy.

For Development

For Production (with extended functionality such as clustering, remote deploy etc.)

Comparison between Forever, pm2 and StrongLoop can be found on StrongLoop's website.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Better and quicker approach without any software to download.

  • Open command prompt and follow steps mentioned below
  • cd path/from/where/file/istobe/copied
  • ftp (serverip or name)
  • It will ask for Server(AIX) User: (username)
  • It will ask for password : (password)
  • cd path/where/file/istobe/copied
  • pwd (to check current path)
  • mput (directory name which is to be copied)

This should work.

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

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

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

getPath() returns the path used to create the File object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)

File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"

File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"

File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"

getAbsolutePath() will resolve the path based on the execution location or drive. So if run from c:\test:

path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"

getCanonicalPath() is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.

As to when to use them. It depends on what you are trying to achieve. getPath() is useful for portability. getAbsolutePath() is useful to find the file system location, and getCanonicalPath() is particularly useful to check if two files are the same.

SQL WHERE condition is not equal to?

Best solution is to use

DELETE FROM table WHERE id NOT IN ( 2 )

Handling optional parameters in javascript

I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.

I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)

This is what the implementation looks like:

function displayOverlay(/*message, timeout, callback*/) {
  return arrangeArgs(arguments, String, Number, Function, 
    function(message, timeout, callback) {
      /* ... your code ... */
    });
};

For clarity, here is what is going on:

function displayOverlay(/*message, timeout, callback*/) {
  //arrangeArgs is the proxy
  return arrangeArgs(
           //first pass in the original arguments
           arguments, 
           //then pass in the type for each argument
           String,  Number,  Function, 
           //lastly, pass in your function and the proxy will do the rest!
           function(message, timeout, callback) {

             //debug output of each argument to verify it's working
             console.log("message", message, "timeout", timeout, "callback", callback);

             /* ... your code ... */

           }
         );
};

You can view the arrangeArgs proxy code in my GitHub repository here:

https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js

Here is the utility function with some comments copied from the repository:

/*
 ****** Overview ******
 * 
 * Strongly type a function's arguments to allow for any arguments to be optional.
 * 
 * Other resources:
 * http://ejohn.org/blog/javascript-method-overloading/
 * 
 ****** Example implementation ******
 * 
 * //all args are optional... will display overlay with default settings
 * var displayOverlay = function() {
 *   return Sysmo.optionalArgs(arguments, 
 *            String, [Number, false, 0], Function, 
 *            function(message, timeout, callback) {
 *              var overlay = new Overlay(message);
 *              overlay.timeout = timeout;
 *              overlay.display({onDisplayed: callback});
 *            });
 * }
 * 
 ****** Example function call ******
 * 
 * //the window.alert() function is the callback, message and timeout are not defined.
 * displayOverlay(alert);
 * 
 * //displays the overlay after 500 miliseconds, then alerts... message is not defined.
 * displayOverlay(500, alert);
 * 
 ****** Setup ******
 * 
 * arguments = the original arguments to the function defined in your javascript API.
 * config = describe the argument type
 *  - Class - specify the type (e.g. String, Number, Function, Array) 
 *  - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
 *                                         The "boolean" indicates if the first value should be treated as a function.
 *                                         The "default" is an optional default value to use instead of undefined.
 * 
 */
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
  //config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
  //config doesn't need a default value.
  //config can also be classes instead of an array if not required and no default value.

  var configs = Sysmo.makeArray(arguments),
      values = Sysmo.makeArray(configs.shift()),
      callback = configs.pop(),
      args = [],
      done = function() {
        //add the proper number of arguments before adding remaining values
        if (!args.length) {
          args = Array(configs.length);
        }
        //fire callback with args and remaining values concatenated
        return callback.apply(null, args.concat(values));
      };

  //if there are not values to process, just fire callback
  if (!values.length) {
    return done();
  }

  //loop through configs to create more easily readable objects
  for (var i = 0; i < configs.length; i++) {

    var config = configs[i];

    //make sure there's a value
    if (values.length) {

      //type or validator function
      var fn = config[0] || config,
          //if config[1] is true, use fn as validator, 
          //otherwise create a validator from a closure to preserve fn for later use
          validate = (config[1]) ? fn : function(value) {
            return value.constructor === fn;
          };

      //see if arg value matches config
      if (validate(values[0])) {
        args.push(values.shift());
        continue;
      }
    }

    //add a default value if there is no value in the original args
    //or if the type didn't match
    args.push(config[2]);
  }

  return done();
}

How to fix HTTP 404 on Github Pages?

In my case, all the suggestions above were correct. I had most pages working except few that were returning 404 even though the markdown files are there and they seemed correct. Here is what fixed it for me on these pages:

  • On one page, there were a few special characters that are not part of UTF-8 and I think that's why GitHub pages was not able to render them. Updating/removing these char and pushing a new commit fixed it.
  • On another page, I found that there were apostrophes ' surrounding the title, I removed them and the page content started showing fine

When is std::weak_ptr useful?

Apart from the other already mentioned valid use cases std::weak_ptr is an awesome tool in a multithreaded environment, because

  • It doesn't own the object and so can't hinder deletion in a different thread
  • std::shared_ptr in conjunction with std::weak_ptr is safe against dangling pointers - in opposite to std::unique_ptr in conjunction with raw pointers
  • std::weak_ptr::lock() is an atomic operation (see also About thread-safety of weak_ptr)

Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join() etc is omitted, the threads would have to be handled differently in a real implementation etc)

// a simplified class to hold the thumbnail and data
struct ImageData {
  std::string path;
  std::unique_ptr<YourFavoriteImageLibData> image;
};

// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
   for( auto& imageData : imagesToLoad )
     imageData->image = YourFavoriteImageLib::load( imageData->path );
}

// a simplified manager
class Manager {
   std::vector<std::shared_ptr<ImageData>> m_imageDatas;
   std::vector<std::unique_ptr<std::thread>> m_threads;
public:
   void load( const std::string& folderPath ) {
      std::vector<std::string> imagePaths = readFolder( folderPath );
      m_imageDatas = createImageDatas( imagePaths );
      const unsigned numThreads = std::thread::hardware_concurrency();
      std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas = 
        splitImageDatas( m_imageDatas, numThreads );
      for( auto& dataRangeToLoad : splitDatas )
        m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
   }
};

But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.

You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.

The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr in conjunction with std::weak_ptr.

// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
   for( auto& imageDataWeak : imagesToLoad ) {
     std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
     if( !imageData )
        continue;
     imageData->image = YourFavoriteImageLib::load( imageData->path );
   }
}

// a simplified manager
class Manager {
   std::vector<std::shared_ptr<ImageData>> m_imageDatas;
   std::vector<std::unique_ptr<std::thread>> m_threads;
public:
   void load( const std::string& folderPath ) {
      std::vector<std::string> imagePaths = readFolder( folderPath );
      m_imageDatas = createImageDatas( imagePaths );
      const unsigned numThreads = std::thread::hardware_concurrency();
      std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas = 
        splitImageDatasToWeak( m_imageDatas, numThreads );
      for( auto& dataRangeToLoad : splitDatas )
        m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
   }
};

This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation. You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Add System.Web.Extensions as a reference to your project

enter image description here

For Ref.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:

ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );

Or just type the script in the HTML page suggested in the other answers.

Pandas split DataFrame by column value

You can use boolean indexing:

df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:

mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

How to get Toolbar from fragment?

You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();

The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

In Kotlin:

(activity as AppCompatActivity).supportActionBar?.title = "My Title"

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

Occasionally when a disk runs out of space, the message "transaction log for database XXXXXXXXXX is full due to 'LOG_BACKUP'" will be returned when an update SQL statement fails. Check your diskspace :)

Get Time from Getdate()

You can use the datapart to maintain time date type and you can compare it to another time.
Check below example:

declare @fromtime time = '09:30'
declare @totime time
SET @totime=CONVERT(TIME, CONCAT(DATEPART(HOUR, GETDATE()),':', DATEPART(MINUTE, GETDATE())))
if @fromtime <= @totime 
begin print 'true' end
else begin print 'no' end

Tree implementation in Java (root, parents and children)

The process of assembling tree nodes is similar to the process of assembling lists. We have a constructor for tree nodes that initializes the instance variables.

public Tree (Object cargo, Tree left, Tree right) { 
    this.cargo = cargo; 
    this.left = left; 
    this.right = right; 
} 

We allocate the child nodes first:

Tree left = new Tree (new Integer(2), null, null); 
Tree right = new Tree (new Integer(3), null, null); 

We can create the parent node and link it to the children at the same time:

Tree tree = new Tree (new Integer(1), left, right); 

How can I add reflection to a C++ application?

EDIT: Updated broken link as of February, the 7th, 2017.

I think noone mentioned this:

At CERN they use a full reflection system for C++:

CERN Reflex. It seems to work very well.

Substring with reverse index

A crazy regex approach

"xxx_456".match(/...$/)[0] //456

how to display variable value in alert box?

Clean way with no jQuery:

function check(some_id) {
    var content = document.getElementById(some_id).childNodes[0].nodeValue;
    alert(content);
}

This is assuming each span has only the value as a child and no embedded HTML.

Deleting all pending tasks in celery / rabbitmq

celery 4+ celery purge command to purge all configured task queues

celery -A *APPNAME* purge

programmatically:

from proj.celery import app
app.control.purge()

all pending task will be purged. Reference: celerydoc

momentJS date string add 5 days

updated:

startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');

alert(new_date)

Best way to create an empty map in Java

Either Collections.emptyMap(), or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()

updating table rows in postgres using subquery

update json_source_tabcol as d
set isnullable = a.is_Nullable
from information_schema.columns as a 
where a.table_name =d.table_name 
and a.table_schema = d.table_schema 
and a.column_name = d.column_name;

How to use type: "POST" in jsonp ajax call

Modern browsers allow cross-domain AJAX queries, it's called Cross-Origin Resource Sharing (see also this document for a shorter and more practical introduction), and recent versions of jQuery support it out of the box; you need a relatively recent browser version though (FF3.5+, IE8+, Safari 4+, Chrome4+; no Opera support AFAIK).

Spring Boot Program cannot find main class

I was facing the same problem. I have deleted the target folder and run maven install, it worked.

How should I remove all the leading spaces from a string? - swift

This String extension removes all whitespace from a string, not just trailing whitespace ...

 extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(string: " ", replacement: "")
    }
  }

Example:

let string = "The quick brown dog jumps over the foxy lady."
let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady.

Find rows that have the same value on a column in MySQL

First part of accepted answer does not work for MSSQL.
This worked for me:

select email, COUNT(*) as C from table 
group by email having COUNT(*) >1 order by C desc

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

It's as simple as that:

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1
}

function isWindows() {
  return navigator.platform.indexOf('Win') > -1
}

You can do funny things then like:

var isMac = isMacintosh();
var isPC = !isMacintosh();

OS X Bash, 'watch' command

If watch doesn't want to install via

brew install watch

There is another similar/copy version that installed and worked perfectly for me

brew install visionmedia-watch

https://github.com/tj/watch

Calling a method inside another method in same class

It is just an overload. The add method is from the ArrayList class. Look that Staff inherits from it.

Android - Best and safe way to stop thread

The Thread.stop() method that could be used to stop a thread has been deprecated; for more info see; Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

Your best bet is to have a variable which the thread itself consults, and voluntarily exits if the variable equals a certain value. You then manipulate the variable inside your code when you want the thread to exit. Alternately of course, you can use an AsyncTask instead.

How to show all shared libraries used by executables in Linux?

On Linux I use:

lsof -P -T -p Application_PID

This works better than ldd when the executable uses a non default loader

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table

Add MIME mapping in web.config for IIS Express

I know this is an old question, but...

I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:

http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/

I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:

  • Open a console application with administrator privilages.
  • Navigation to the IIS Express directory. This lives under Program Files or Program Files (x86)
  • Run the command:

    appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']

Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT and DELETE verbs). Yay!

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

To find the HSV value of Green, try following commands in Python terminal

green = np.uint8([[[0,255,0 ]]])
hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
print hsv_green
[[[ 60 255 255]]]

Python Pandas Replacing Header with Top Row

header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.reset_index(drop=True)
table_df.columns = header
table_df

Compare two files in Visual Studio

In Visual Studio Code you can:

  • Go to the Explorer
  • Right click the first file you want to compare
  • Select Select for compare
  • Right click on the second file you want to compare
  • Select Compare with '[NAME OF THE PREVIOUSLY SELECTED FILE]'

How to insert a column in a specific position in oracle without dropping and recreating the table?

Amit-

I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:

CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;

Drop the table you want to add columns to:

DROP TABLE TABLE_TO_CHANGE;

It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".

Now insert the data back into the new table:

INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4) 
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;

When the data is inserted into your "new-old" table, you can drop the temp table.

DROP TABLE MY_TEMP_TABLE;

This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.

-CJ

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

select your target and search for user-Defined section on build Settings,select provisioning profile and delete it

Delete provisioning profile

OWIN Startup Class Missing

I tried most of the recommended fixes here, and still couldn't avoid the error message. I finally performed a combination of a few recommended solutions:

  1. Added this entry to the top of the AppSettings section of my web.config:

    <add key="owin:AutomaticAppStartup" value="false"/>

  2. Expanded the References node of my project and deleted everything that contained the string OWIN. (I felt safe doing so since my organization is not (and won't be) an active OWIN provider in the future)

I then clicked Run and my homepage loaded right up.

Convert python datetime to timestamp in milliseconds

For Python2.7

You can format it into seconds and then multiply by 1000 to convert to millisecond.

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s')
d_in_ms = int(d)*1000
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482206922000
2016-12-20 09:38:42

Unable to merge dex

I find out the reason of this problem for my project. I was added one dependency twice in build.gradle. One time by adding dependency and one time again by adding jar dependency:

compile 'org.achartengine:achartengine:1.2.0'
...
implementation files('../achartengine-1.2.0.jar')

after remove the first line problem solved.

Unable to create Genymotion Virtual Device

It works fine by running genymotion with administrative privileges.

I solved it by deleting all of file in Ova,Templates and Deployed folder, I can run download and reinstall again and run without Administrative privileges

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

Div Background Image Z-Index Issue

To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:

Add to your footer and header this CSS:

position: relative; 

EDITED:

Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...

Remove From the #backstretch:

z-index: -999999;

Read a little bit about Z-Index here!

Taking multiple inputs from user in python

You can try this.

import sys

for line in sys.stdin:
    j= int(line[0])
    e= float(line[1])
    t= str(line[2])

For details, please review,

https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects

What's the difference between "Solutions Architect" and "Applications Architect"?

There are valid differences between types of architects:

Enterprise architects look at solutions for the enterprise aligining tightly with the enterprise strategy. Eg in a bank, they'll look at the complete IT landscape.

Solution architects focus on a particular solution, for example a new credit card acquiring system in a bank.

Domain architects focus on specific areas, for example an application architect or network architect.

Technical architects generally play the role of solution architects with less focus on the business aspect and more on the techology aspect.

PostgreSQL "DESCRIBE TABLE"

Use this command 

\d table name

like 

\d queuerecords

             Table "public.queuerecords"
  Column   |            Type             | Modifiers
-----------+-----------------------------+-----------
 id        | uuid                        | not null
 endtime   | timestamp without time zone |
 payload   | text                        |
 queueid   | text                        |
 starttime | timestamp without time zone |
 status    | text                        |

What is the default username and password in Tomcat?

If people still have problems after adding/modifying the tomcat-users.xml file and adding the relevant user/role for the version of Tomcat that they're using then please be sure that you've removed the comment tags that are surrounding this block. They will look like this in the XML file:
<!--
-->
They will be above and below the user/role section.

Set textbox to readonly and background color to grey in jquery

As per you question this is what you can do

HTML

<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>

JS/Jquery

$(function () {
    $('#sample').attr('readonly', 'true'); // mark it as read only
    $('#sample').css('background-color' , '#DEDEDE'); // change the background color
});

or add a class in you css with the required styling

$('#sample').addClass('yourclass');

DEMO

Let me know if the requirement was different

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

if you have number of columns in your database table more than number of columns in your csv you can proceed like this:

LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable 
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"' 
ESCAPED BY '\\' 
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);

How can I convert a VBScript to an executable (EXE) file?

You can do this with PureBasic and MsScriptControl

All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below

InitScriptControl()
SCtr_AddCode("MsgBox 1")

How to use a dot "." to access members of dictionary?

Use SimpleNamespace:

>>> from types import SimpleNamespace   
>>> d = dict(x=[1, 2], y=['a', 'b'])
>>> ns = SimpleNamespace(**d)
>>> ns.x
[1, 2]
>>> ns
namespace(x=[1, 2], y=['a', 'b'])

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

The compiler is confused by the function signature. You can fix it like this:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

This is the automatic casting between NSMutableURLRequest and the new URLRequest that is failing and which forced us to do this casting here.

How to change my Git username in terminal?

Firstly you need to change credentials from your local machine

  1. remove generic credentials if there is any

Generic credentials

  1. configure new user and email (you can make it globally if you want)
git config [--global] user.name "Your Name"
git config [--global] user.email "[email protected]"
  1. now upload or update your repo it will ask your username and password to get access to github

What does it mean to write to stdout in C?

@K Scott Piel wrote a great answer here, but I want to add one important point.

Note that the stdout stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf statement with a \n

Ex:

printf("hello world\n");

or

printf("hello world"); 
printf("\n");

or similar, OR you must call fflush(stdout); after your printf call.

Ex:

printf("hello world"); 
fflush(stdout);

Read more here: Why does printf not flush after the call unless a newline is in the format string?

HTML5 Canvas: Zooming

IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.

Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.

CSS media queries: max-width OR max-height

yes, using and, like:

@media screen and (max-width: 800px), 
       screen and (max-height: 600px) {
  ...
}

Search an array for matching attribute

you can also use the Array.find feature of es6. the doc is here

return restaurants.find(item => {
   return item.restaurant.food == 'chicken'
})

How to detect orientation change in layout in Android?

use this method

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
    {
        Toast.makeText(getActivity(),"PORTRAIT",Toast.LENGTH_LONG).show();
       //add your code what you want to do when screen on PORTRAIT MODE
    }
    else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
        Toast.makeText(getActivity(),"LANDSCAPE",Toast.LENGTH_LONG).show();
        //add your code what you want to do when screen on LANDSCAPE MODE
   }
}

And Do not forget to Add this in your Androidmainfest.xml

android:configChanges="orientation|screenSize"

like this

<activity android:name=".MainActivity"
          android:theme="@style/Theme.AppCompat.NoActionBar"
          android:configChanges="orientation|screenSize">

    </activity>

How to use confirm using sweet alert?

You need To use then() function, like this

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!"
 }).then(
       function () { /*Your Code Here*/ },
       function () { return false; });

How do you add an ActionListener onto a JButton in Java

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

How to abort a Task like aborting a Thread (Thread.Abort method)?

The guidance on not using a thread abort is controversial. I think there is still a place for it but in exceptional circumstance. However you should always attempt to design around it and see it as a last resort.

Example;

You have a simple windows form application that connects to a blocking synchronous web service. Within which it executes a function on the web service within a Parallel loop.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;

Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{

    Thread.Sleep(120000); // pretend web service call

});

Say in this example, the blocking call takes 2 mins to complete. Now I set my MaxDegreeOfParallelism to say ProcessorCount. iListOfItems has 1000 items within it to process.

The user clicks the process button and the loop commences, we have 'up-to' 20 threads executing against 1000 items in the iListOfItems collection. Each iteration executes on its own thread. Each thread will utilise a foreground thread when created by Parallel.ForEach. This means regardless of the main application shutdown, the app domain will be kept alive until all threads have finished.

However the user needs to close the application for some reason, say they close the form. These 20 threads will continue to execute until all 1000 items are processed. This is not ideal in this scenario, as the application will not exit as the user expects and will continue to run behind the scenes, as can be seen by taking a look in task manger.

Say the user tries to rebuild the app again (VS 2010), it reports the exe is locked, then they would have to go into task manager to kill it or just wait until all 1000 items are processed.

I would not blame you for saying, but of course! I should be cancelling these threads using the CancellationTokenSource object and calling Cancel ... but there are some problems with this as of .net 4.0. Firstly this is still never going to result in a thread abort which would offer up an abort exception followed by thread termination, so the app domain will instead need to wait for the threads to finish normally, and this means waiting for the last blocking call, which would be the very last running iteration (thread) that ultimately gets to call po.CancellationToken.ThrowIfCancellationRequested. In the example this would mean the app domain could still stay alive for up to 2 mins, even though the form has been closed and cancel called.

Note that Calling Cancel on CancellationTokenSource does not throw an exception on the processing thread(s), which would indeed act to interrupt the blocking call similar to a thread abort and stop the execution. An exception is cached ready for when all the other threads (concurrent iterations) eventually finish and return, the exception is thrown in the initiating thread (where the loop is declared).

I chose not to use the Cancel option on a CancellationTokenSource object. This is wasteful and arguably violates the well known anti-patten of controlling the flow of the code by Exceptions.

Instead, it is arguably 'better' to implement a simple thread safe property i.e. Bool stopExecuting. Then within the loop, check the value of stopExecuting and if the value is set to true by the external influence, we can take an alternate path to close down gracefully. Since we should not call cancel, this precludes checking CancellationTokenSource.IsCancellationRequested which would otherwise be another option.

Something like the following if condition would be appropriate within the loop;

if (loopState.ShouldExitCurrentIteration || loopState.IsExceptional || stopExecuting) {loopState.Stop(); return;}

The iteration will now exit in a 'controlled' manner as well as terminating further iterations, but as I said, this does little for our issue of having to wait on the long running and blocking call(s) that are made within each iteration (parallel loop thread), since these have to complete before each thread can get to the option of checking if it should stop.

In summary, as the user closes the form, the 20 threads will be signaled to stop via stopExecuting, but they will only stop when they have finished executing their long running function call.

We can't do anything about the fact that the application domain will always stay alive and only be released when all foreground threads have completed. And this means there will be a delay associated with waiting for any blocking calls made within the loop to complete.

Only a true thread abort can interrupt the blocking call, and you must mitigate leaving the system in a unstable/undefined state the best you can in the aborted thread's exception handler which goes without question. Whether that's appropriate is a matter for the programmer to decide, based on what resource handles they chose to maintain and how easy it is to close them in a thread's finally block. You could register with a token to terminate on cancel as a semi workaround i.e.

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;

Parallel.ForEach(iListOfItems, po, (item, loopState) =>
{

    using (cts.Token.Register(Thread.CurrentThread.Abort))
    {
        Try
        {
           Thread.Sleep(120000); // pretend web service call          
        }
        Catch(ThreadAbortException ex)
        {
           // log etc.
        }
        Finally
        {
          // clean up here
        }
    }

});

but this will still result in an exception in the declaring thread.

All things considered, interrupt blocking calls using the parallel.loop constructs could have been a method on the options, avoiding the use of more obscure parts of the library. But why there is no option to cancel and avoid throwing an exception in the declaring method strikes me as a possible oversight.

Jquery-How to grey out the background while showing the loading icon over it

Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

If the gif is displayed but not animating, see reference links at very bottom of this answer.

Displaying the gif + overlay, however, is easier than you might think.

All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

So, when the button is pressed, just unhide those two divs. That's it!

jsFiddle Demo

_x000D_
_x000D_
$("#button").click(function() {_x000D_
    $('#myOverlay').show();_x000D_
    $('#loadingGIF').show();_x000D_
    setTimeout(function(){_x000D_
   $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    },2500);_x000D_
});_x000D_
/*  Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
 $('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Update:

You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)

References:

http://www.paulirish.com/2007/animated-gif-not-animating/

Animated GIF while loading page does not animate

https://wordpress.org/support/topic/animated-gif-not-working

http://forums.mozillazine.org/viewtopic.php?p=987829

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

How to use Fiddler to monitor WCF service

Fiddler listens to outbound requests rather than inbound requests so you're not going to be able to monitor all the requests coming in to your service by using Fiddler.

The best you're going to get with Fiddler is the ability to see all of the requests as they are generated by your Console App (assuming that the app generates web requests rather than using some other pipeline).

If you want a tool that is more powerful (but more difficult to use) that will allow you to monitor ALL incoming requests, you should check out WireShark.

Edit

I stand corrected. Thanks to Eric Law for posting the directions to configuring Fiddler to be a reverse proxy!

C++ vector of char array

You need

char test[] = "abcde";  // This will add a terminating \0 character to the array
std::vector<std::string> v;
v.push_back(test);

Of if you meant to make a vector of character instead of a vector of strings,

std::vector<char> v(test, test + sizeof(test)/sizeof(*test));

The expression sizeof(test)/sizeof(*test) is for calculating the number of elements in the array test.

Regular expression: find spaces (tabs/space) but not newlines

Try this character set:

[ \t]

This does only match a space or a tabulator.

ASP.NET MVC on IIS 7.5

One more thing to make sure you have is the following set in your web.config:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/> 
</system.webServer>

json parsing error syntax error unexpected end of input

This error occurs on an empty JSON file reading.

To avoid this error in NodeJS I'm checking the file's size:

const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;

Rails where condition using NOT NIL

Not sure of this is helpful but this what worked for me in Rails 4

Foo.where.not(bar: nil)

Cassandra port usage - how are the ports used?

@Schildmeijer is largely right, however port 7001 is still used when using TLS Encrypted Internode communication

So my complete list would be for current versions of Cassandra:

  • 7199 - JMX (was 8080 pre Cassandra 0.8.xx)
  • 7000 - Internode communication (not used if TLS enabled)
  • 7001 - TLS Internode communication (used if TLS enabled)
  • 9160 - Thrift client API
  • 9042 - CQL native transport port

Java: How to convert List to Map

A Java 8 example to convert a List<?> of objects into a Map<k, v>:

List<Hosting> list = new ArrayList<>();
list.add(new Hosting(1, "liquidweb.com", new Date()));
list.add(new Hosting(2, "linode.com", new Date()));
list.add(new Hosting(3, "digitalocean.com", new Date()));

//example 1
Map<Integer, String> result1 = list.stream().collect(
    Collectors.toMap(Hosting::getId, Hosting::getName));

System.out.println("Result 1 : " + result1);

//example 2
Map<Integer, String> result2 = list.stream().collect(
    Collectors.toMap(x -> x.getId(), x -> x.getName()));

Code copied from:
https://www.mkyong.com/java8/java-8-convert-list-to-map/

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I had same problem. After one day, I got it.

Problem was from adding two smtp tags in mailSettings under <system.net>.

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

What's the strangest corner case you've seen in C# or .NET?

What if you have a generic class that has methods that could be made ambiguous depending on the type arguments? I ran into this situation recently writing a two-way dictionary. I wanted to write symmetric Get() methods that would return the opposite of whatever argument was passed. Something like this:

class TwoWayRelationship<T1, T2>
{
    public T2 Get(T1 key) { /* ... */ }
    public T1 Get(T2 key) { /* ... */ }
}

All is well good if you make an instance where T1 and T2 are different types:

var r1 = new TwoWayRelationship<int, string>();
r1.Get(1);
r1.Get("a");

But if T1 and T2 are the same (and probably if one was a subclass of another), it's a compiler error:

var r2 = new TwoWayRelationship<int, int>();
r2.Get(1);  // "The call is ambiguous..."

Interestingly, all other methods in the second case are still usable; it's only calls to the now-ambiguous method that causes a compiler error. Interesting case, if a little unlikely and obscure.

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

How can I remove a key and its value from an associative array?

Consider this array:

$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
  • To remove an element using the array key:

    // To unset an element from array using Key:
    unset($arr["key2"]);
    var_dump($arr);
    // output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
    
  • To remove element by value:

    // remove an element by value:
    $arr = array_diff($arr, ["value1"]);
    var_dump($arr);
    // output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" } 
    

read more about array_diff: http://php.net/manual/en/function.array-diff.php

  • To remove an element by using index:

    array_splice($arr, 1, 1);
    var_dump($arr);
    // array(1) { ["key3"]=> string(6) "value3" } 
    

read more about array_splice: http://php.net/manual/en/function.array-splice.php

Regex match digits, comma and semicolon?

You current regex will only match 1 character. you need either * (includes empty string) or + (at least one) to match multiple characters and numbers have a shortcut : \d (need \\ in a string).

word.matches("^[\\d,;]+$") 

The Pattern documentation is pretty good : http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

Also you can try your regexps online at: http://www.regexplanet.com/simple/index.html

What does <T> denote in C#

It is a generic type parameter, see Generics documentation.

T is not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).

T GetDefault<T>()
{
    return default(T);
}

Note that the return type is T. With this method you can get the default value of any type by calling the method as:

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET uses generics in collections, ... example:

List<int> integerList = new List<int>();

This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:

public class List<T> : ...
{
    public void Add(T item);
}

Some more information about generics.

You can limit the scope of the type T.

The following example only allows you to invoke the method with types that are classes:

void Foo<T>(T item) where T: class
{
}

The following example only allows you to invoke the method with types that are Circle or inherit from it.

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.

How to obtain the total numbers of rows from a CSV file in Python?

I think we can improve the best answer a little bit, I'm using:

len = sum(1 for _ in reader)

Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles.

How to disable gradle 'offline mode' in android studio?

Offline mode could be set in Android Studio and in your project. To verify that gradle won't build your project in offline mode:

  1. Disable gradle offline mode in Android Studio gradle settings.
  2. Verify that your project's gradle.settings won't contain: startParameter.offline=true

How to split csv whose columns may contain ,

Use the Microsoft.VisualBasic.FileIO.TextFieldParser class. This will handle parsing a delimited file, TextReader or Stream where some fields are enclosed in quotes and some are not.

For example:

using Microsoft.VisualBasic.FileIO;

string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

TextFieldParser parser = new TextFieldParser(new StringReader(csv));

// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");

parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");

string[] fields;

while (!parser.EndOfData)
{
    fields = parser.ReadFields();
    foreach (string field in fields)
    {
        Console.WriteLine(field);
    }
} 

parser.Close();

This should result in the following output:

2
1016
7/31/2008 14:22
Geoff Dalgas
6/5/2011 22:21
http://stackoverflow.com
Corvallis, OR
7679
351
81
b437f461b3fd27387c5d8ab47a293d35
34

See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.

You need to add a reference to Microsoft.VisualBasic in the Add References .NET tab.

How do you create a daemon in Python?

Probably not a direct answer to the question, but systemd can be used to run your application as a daemon. Here is an example:

[Unit]
Description=Python daemon
After=syslog.target
After=network.target

[Service]
Type=simple
User=<run as user>
Group=<run as group group>
ExecStart=/usr/bin/python <python script home>/script.py

# Give the script some time to startup
TimeoutSec=300

[Install]
WantedBy=multi-user.target

I prefer this method because a lot of the work is done for you, and then your daemon script behaves similarly to the rest of your system.

-Orby

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

How do I rotate text in css?

Using writing-mode and transform.

.rotate {
     writing-mode: vertical-lr;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
}


<span class="rotate">Hello</span>

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Deep cloning objects

  1. Basically you need to implement ICloneable interface and then realize object structure copying.
  2. If it's deep copy of all members, you need to insure (not relating on solution you choose) that all children are clonable as well.
  3. Sometimes you need to be aware of some restriction during this process, for example if you copying the ORM objects most of frameworks allow only one object attached to the session and you MUST NOT make clones of this object, or if it's possible you need to care about session attaching of these objects.

Cheers.

Re-sign IPA (iPhone)

None of these resigning approaches were working for me, so I had to work out something else.

In my case, I had an IPA with an expired certificate. I could have rebuilt the app, but because we wanted to ensure we were distributing exactly the same version (just with a new certificate), we did not want to rebuild it.

Instead of the ways of resigning mentioned in the other answers, I turned to Xcode’s method of creating an IPA, which starts with an .xcarchive from a build.

  1. I duplicated an existing .xcarchive and started replacing the contents. (I ignored the .dSYM file.)

  2. I extracted the old app from the old IPA file (via unzipping; the app is the only thing in the Payload folder)

  3. I moved this app into the new .xcarchive, under Products/Applications replacing the app that was there.

  4. I edited Info.plist, editing

    • ApplicationProperties/ApplicationPath
    • ApplicationProperties/CFBundleIdentifier
    • ApplicationProperties/CFBundleShortVersionString
    • ApplicationProperties/CFBundleVersion
    • Name
  5. I moved the .xcarchive into Xcode’s archive folder, usually /Users/xxxx/Library/Developer/Xcode/Archives.

  6. In Xcode, I opened the Organiser window, picked this new archive and did a regular (in this case Enterprise) export.

The result was a good IPA that works.

RegEx for Javascript to allow only alphanumeric

Jquery to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
Enter Only Numbers: _x000D_
<input type="text" id="onlynumbers">_x000D_
<br><br>_x000D_
Enter Only Alphabets: _x000D_
<input type="text" id="onlyalpha">_x000D_
<br><br>_x000D_
Enter other than Alphabets and numbers like special characters: _x000D_
<input type="text" id="speclchar">_x000D_
_x000D_
<script>_x000D_
    $('#onlynumbers').keypress(function(e) {_x000D_
      var letters=/^[0-9]/g; //g means global_x000D_
      if(!(e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    _x000D_
    $('#onlyalpha').keypress(function(e) {_x000D_
      var letters=/^[a-z]/gi; //i means ignorecase_x000D_
      if(!(e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    _x000D_
    $('#speclchar').keypress(function(e) {_x000D_
      var letters=/^[0-9a-z]/gi; _x000D_
      if((e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

**JQUERY to accept only NUMBERS , ALPHABETS and SPECIAL CHARACTERS **


<!DOCTYPE html>
    $('#onlynumbers').keypress(function(e) {
      var letters=/^[0-9]/g; //g means global
      if(!(e.key).match(letters)) e.preventDefault();
    });

    $('#onlyalpha').keypress(function(e) {
      var letters=/^[a-z]/gi; //i means ignorecase
      if(!(e.key).match(letters)) e.preventDefault();
    });

    $('#speclchar').keypress(function(e) {
      var letters=/^[0-9a-z]/gi; 
      if((e.key).match(letters)) e.preventDefault();
    });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

Enter Only Numbers:

Enter Only Alphabets:

Enter other than Alphabets and numbers like special characters:

</body>
</html>

Java HTTP Client Request with defined timeout

HttpParams is deprecated in the new Apache HTTPClient library. Using the code provided by Laz leads to deprecation warnings.

I suggest to use RequestConfig instead on your HttpGet or HttpPost instance:

final RequestConfig params = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
httpPost.setConfig(params);

What is a postback?

When a script generates an html form and that form's action http POSTs back to the same form.