Show datalist labels but submit the actual value
Using PHP i've found a quite simple way to do this. Guys, Just Use something like this
<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
<datalist id="customers">
<?php
$querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
$resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());
while ($row_this = mysqli_fetch_array($resultSnamex)) {
echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
<input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
}
?>
</datalist>
The Code Above lets the form carry the id of the option also selected.
How to get coordinates of an svg element?
I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.
How to use subList()
To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:
dataList.subList(30, 35);
A guaranteed safe way to do this is:
dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
HTML Form: Select-Option vs Datalist-Option
Think of it as the difference between a requirement and a suggestion. For the select
element, the user is required to select one of the options you've given. For the datalist
element, it is suggested that the user select one of the options you've given, but he can actually enter anything he wants in the input.
Edit 1: So which one you use depends upon your requirements. If the user must enter one of your choices, use the select
element. If the use can enter whatever, use the datalist
element.
Edit 2: Found this tidbit in the HTML Living Standard: "Each option element that is a descendant of the datalist element...represents a suggestion."
Checking if an object is null in C#
Jeffrey L Whitledge is right. Your `dataList´-Object itself is null.
There is also another problem with your code: You are using the ref-keyword, which means the argument data cannot be null! The MSDN says:
An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed
It's also not a good idea to use generics with the type `Object´. Generics should avoid boxing/unboxing and also ensure type safety. If you want a common type make your method generic. Finally your code should look like this:
public class Foo<T> where T : MyTypeOrInterface {
public List<T> dataList = new List<T>();
public bool AddData(ref T data) {
bool success = false;
try {
dataList.Add(data);
success = doOtherStuff(data);
} catch (Exception e) {
throw new Exception(e.ToString());
}
return success;
}
private bool doOtherStuff(T data) {
//...
}
}
How to get datas from List<Object> (Java)?
System.out.println("Element "+i+list.get(0));}
Should be
System.out.println("Element "+i+list.get(i));}
To use the JSF tags, you give the dataList value attribute a reference to your list of elements, and the var attribute is a local name for each element of that list in turn. Inside the dataList, you use properties of the object (getters) to output the information about that individual object:
<t:dataList id="myDataList" value="#{houseControlList}" var="element" rows="3" >
...
<t:outputText id="houseId" value="#{element.houseId}"/>
...
</t:dataList>
Show hide div using codebehind
There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.
Rendering and Visibility
There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.
Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat
attribute value to server
on the markup page.
<div id="myDiv" runat="server"></div>
The decision to render the div or not can now be done in the code behind class like so:
myDiv.Visible = someConditionalBool;
If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.
Client Side Hiding
Hiding an element is done on the client side only. Meaning, it's rendered but it has a display
CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server
set just as I explained in the previous example.
Hiding in the Code Behind Class
To hide an element that you want rendered to the page but hidden is another simple single line of code:
myDiv.Style["display"] = "none";
If you have a need to remove the display
style server side, it can be done by removing the display
style, or setting it to a different value like inline
or block
(values described here).
myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
// then to show again
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
// ... and to show
myDiv.show();
Quickly reading very large tables as dataframes
I've tried all above and [readr][1] made the best job. I have only 8gb RAM
Loop for 20 files, 5gb each, 7 columns:
read_fwf(arquivos[i],col_types = "ccccccc",fwf_cols(cnpj = c(4,17), nome = c(19,168), cpf = c(169,183), fantasia = c(169,223), sit.cadastral = c(224,225), dt.sitcadastral = c(226,233), cnae = c(376,382)))
How to dynamically create CSS class in JavaScript and apply?
For the benefit of searchers; if you are using jQuery, you can do the following:
var currentOverride = $('#customoverridestyles');
if (currentOverride) {
currentOverride.remove();
}
$('body').append("<style id=\"customoverridestyles\">body{background-color:pink;}</style>");
Obviously you can change the inner css to whatever you want.
Appreciate some people prefer pure JavaScript, but it works and has been pretty robust for writing/overwriting styles dynamically.
Neither BindingResult nor plain target object for bean name available as request attr
Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem);
which contains @RequestMapping(method = RequestMethod.GET)
annotation.
For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java
myform.jsp contains
<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>
MyFormController.java
@RequestMapping("/securedArea")
@Controller
public class SecureAreaController {
@RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
UploadItem uploadItem = new UploadItem(); // declareing
model.addAttribute("uploadItem", uploadItem); // adding in model
return "securedArea/upload";
}
}
As you can see I am declaring UploadItem.java in controller GET method.
C#: Waiting for all threads to complete
With .NET 4.0 I find System.Threading.Tasks a lot easier to work with. Here's spin-wait loop which works reliably for me. It blocks the main thread until all the tasks complete. There's also Task.WaitAll, but that hasn't always worked for me.
for (int i = 0; i < N; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
DoThreadStuff(localData);
});
}
while (tasks.Any(t => !t.IsCompleted)) { } //spin wait
How do you add an image?
The other option to try is a straightforward
<img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>
i.e. without {} but instead giving the direct image path
How to include Javascript file in Asp.Net page
add like
<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>
OR can add in code behind.
Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));
Couldn't load memtrack module Logcat Error
I had this issue too, also running on an emulator.. The same message was showing up on Logcat, but it wasn't affecting the functionality of the app. But it was annoying, and I don't like seeing errors on the log that I don't understand.
Anyway, I got rid of the message by increasing the RAM on the emulator.
How to manually trigger click event in ReactJS?
In a functional component this principle also works, it's just a slightly different syntax and way of thinking.
const UploadsWindow = () => {
// will hold a reference for our real input file
let inputFile = '';
// function to trigger our input file click
const uploadClick = e => {
e.preventDefault();
inputFile.click();
return false;
};
return (
<>
<input
type="file"
name="fileUpload"
ref={input => {
// assigns a reference so we can trigger it later
inputFile = input;
}}
multiple
/>
<a href="#" className="btn" onClick={uploadClick}>
Add or Drag Attachments Here
</a>
</>
)
}
How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?
With pure html (no JS), you can't really substitute a radio-button for an image (at least, I don't think you can). You could, though use the following to make the same connection to the user:
<form action="" method="post">
<fieldset>
<input type="radio" name="feeling" id="feelingSad" value="sad" /><label for="feelingSad"><img src="path/to/sad.png" /></label>
<label for="feelingHappy"><input type="radio" name="feeling" id="feelingHappy" value="happy" /><img src="path/to/happy.png" /></label>
</fieldset>
</form>
Trying to check if username already exists in MySQL database using PHP
Try this:
$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")
Don't add $con
to mysql_query()
function.
Disclaimer: using the username
variable in the string passed to mysql_query
, as shown above, is a trivial SQL injection attack vector in so far the username
depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.
C++ Returning reference to local variable
A good thing to remember are these simple rules, and they apply to both parameters and return types...
- Value - makes a copy of the item in question.
- Pointer - refers to the address of the item in question.
- Reference - is literally the item in question.
There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int*
and returning &i
would have been equally incorrect. You would be better off in that case doing this...
void func1(int& oValue)
{
oValue = 1;
}
Doing so would directly change the value of your passed in parameter. Whereas this code...
void func1(int oValue)
{
oValue = 1;
}
would not. It would just change the value of oValue
local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue
, and not oValue
itself.
jQuery slide left and show
Don't forget the padding and margins...
jQuery.fn.slideLeftHide = function(speed, callback) {
this.animate({
width: "hide",
paddingLeft: "hide",
paddingRight: "hide",
marginLeft: "hide",
marginRight: "hide"
}, speed, callback);
}
jQuery.fn.slideLeftShow = function(speed, callback) {
this.animate({
width: "show",
paddingLeft: "show",
paddingRight: "show",
marginLeft: "show",
marginRight: "show"
}, speed, callback);
}
With the speed/callback arguments added, it's a complete drop-in replacement for slideUp()
and slideDown()
.
How to use a variable for a key in a JavaScript object literal?
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
How to hash some string with sha256 in Java?
I traced the Apache code through DigestUtils
and sha256
seems to default back to java.security.MessageDigest
for calculation. Apache does not implement an independent sha256
solution. I was looking for an independent implementation to compare against the java.security
library. FYI only.
if block inside echo statement?
In sake of readability it should be something like
<?php
$countries = $myaddress->get_countries();
foreach($countries as $value) {
$selected ='';
if($value=='United States') $selected ='selected="selected"';
echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
}
?>
desire to stuff EVERYTHING in a single line is a decease, man. Write distinctly.
But there is another way, a better one. There is no need to use echo at all. Learn to use templates. Prepare your data first, and display it only then ready.
Business logic part:
$countries = $myaddress->get_countries();
$selected_country = 1;
Template part:
<? foreach($countries as $row): ?>
<option value="<?=$row['id']?>"<? if ($row['id']==$current_country):> "selected"><? endif ?>
<?=$row['name']?>
</option>
<? endforeach ?>
html5 input for money/currency
I stumbled across this article looking for a similar answer. I read @vsync example Using javascript's Number.prototype.toLocaleString: and it appeared to work well. The only complaint I had was that if you had more than a single input type="currency"
within your page it would only modify the first instance of it.
As he mentions in his comments it was only designed as an example for stackoverflow.
However, the example worked well for me and although I have little experience with JS I figured out how to modify it so that it will work with multiple input type="currency"
on the page using the document.querySelectorAll
rather than document.querySelector
and adding a for loop.
I hope this can be useful for someone else. ( Credit for the bulk of the code is @vsync )
var currencyInput = document.querySelectorAll( 'input[type="currency"]' );
for ( var i = 0; i < currencyInput.length; i++ ) {
var currency = 'GBP'
onBlur( {
target: currencyInput[ i ]
} )
currencyInput[ i ].addEventListener( 'focus', onFocus )
currencyInput[ i ].addEventListener( 'blur', onBlur )
function localStringToNumber( s ) {
return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
}
function onFocus( e ) {
var value = e.target.value;
e.target.value = value ? localStringToNumber( value ) : ''
}
function onBlur( e ) {
var value = e.target.value
var options = {
maximumFractionDigits: 2,
currency: currency,
style: "currency",
currencyDisplay: "symbol"
}
e.target.value = ( value || value === 0 ) ?
localStringToNumber( value ).toLocaleString( undefined, options ) :
''
}
}
_x000D_
_x000D_
var currencyInput = document.querySelectorAll( 'input[type="currency"]' );
for ( var i = 0; i < currencyInput.length; i++ ) {
var currency = 'GBP'
onBlur( {
target: currencyInput[ i ]
} )
currencyInput[ i ].addEventListener( 'focus', onFocus )
currencyInput[ i ].addEventListener( 'blur', onBlur )
function localStringToNumber( s ) {
return Number( String( s ).replace( /[^0-9.-]+/g, "" ) )
}
function onFocus( e ) {
var value = e.target.value;
e.target.value = value ? localStringToNumber( value ) : ''
}
function onBlur( e ) {
var value = e.target.value
var options = {
maximumFractionDigits: 2,
currency: currency,
style: "currency",
currencyDisplay: "symbol"
}
e.target.value = ( value || value === 0 ) ?
localStringToNumber( value ).toLocaleString( undefined, options ) :
''
}
}
_x000D_
.input_date {
margin:1px 0px 50px 0px;
font-family: 'Roboto', sans-serif;
font-size: 18px;
line-height: 1.5;
color: #111;
display: block;
background: #ddd;
height: 50px;
border-radius: 5px;
border: 2px solid #111111;
padding: 0 20px 0 20px;
width: 100px;
}
_x000D_
<label for="cost_of_sale">Cost of Sale</label>
<input class="input_date" type="currency" name="cost_of_sale" id="cost_of_sale" value="0.00">
<label for="sales">Sales</label>
<input class="input_date" type="currency" name="sales" id="sales" value="0.00">
<label for="gm_pounds">GM Pounds</label>
<input class="input_date" type="currency" name="gm_pounds" id="gm_pounds" value="0.00">
_x000D_
_x000D_
_x000D_
Create a temporary table in a SELECT statement without a separate CREATE TABLE
CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)
From the manual found at http://dev.mysql.com/doc/refman/5.7/en/create-table.html
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.
Markdown to create pages and table of contents?
I just coded an extension for python-markdown
, which uses its parser to retrieve headings, and outputs a TOC as Markdown-formatted unordered list with local links. The file is
... and it should be placed in markdown/extensions/
directory in the markdown installation. Then, all you have to do, is type anchor <a>
tags with an id="..."
attribute as a reference - so for an input text like this:
$ cat test.md
Hello
=====
## <a id="sect one"></a>SECTION ONE ##
something here
### <a id='sect two'>eh</a>SECTION TWO ###
something else
#### SECTION THREE
nothing here
### <a id="four"></a>SECTION FOUR
also...
... the extension can be called like this:
$ python -m markdown -x md_toc test.md
* Hello
* [SECTION ONE](#sect one)
* [SECTION TWO](#sect two)
* SECTION THREE
* [SECTION FOUR](#four)
... and then you can paste back this toc in your markdown document (or have a shortcut in your text editor, that calls the script on the currently open document, and then inserts the resulting TOC in the same document).
Note that older versions of python-markdown
don't have a __main__.py
module, and as such, the command line call as above will not work for those versions.
How can I check if character in a string is a letter? (Python)
str.isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.
In python2.x:
>>> s = u'a1??'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
? True
? True
>>> s = 'a1??'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
? False
? False
? False
? False
? False
? False
>>>
In python3.x:
>>> s = 'a1??'
>>> for char in s: print(char, char.isalpha())
...
a True
1 False
? True
? True
>>>
This code work:
>>> def is_alpha(word):
... try:
... return word.encode('ascii').isalpha()
... except:
... return False
...
>>> is_alpha('??')
False
>>> is_alpha(u'??')
False
>>>
>>> a = 'a'
>>> b = 'a'
>>> ord(a), ord(b)
(65345, 97)
>>> a.isalpha(), b.isalpha()
(True, True)
>>> is_alpha(a), is_alpha(b)
(False, True)
>>>
How do I remove an object from an array with JavaScript?
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter()
is non-mutating, so you'll get a new array back.
See the Mozilla Developer Network notes on Filter.
How to call a RESTful web service from Android?
Perhaps am late or maybe you've already used it before but there is another one called ksoap and its pretty amazing.. It also includes timeouts and can parse any SOAP based webservice efficiently. I also made a few changes to suit my parsing.. Look it up
Populate one dropdown based on selection in another
_x000D_
_x000D_
function configureDropDownLists(ddl1, ddl2) {_x000D_
var colours = ['Black', 'White', 'Blue'];_x000D_
var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
switch (ddl1.value) {_x000D_
case 'Colours':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < colours.length; i++) {_x000D_
createOption(ddl2, colours[i], colours[i]);_x000D_
}_x000D_
break;_x000D_
case 'Shapes':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < shapes.length; i++) {_x000D_
createOption(ddl2, shapes[i], shapes[i]);_x000D_
}_x000D_
break;_x000D_
case 'Names':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < names.length; i++) {_x000D_
createOption(ddl2, names[i], names[i]);_x000D_
}_x000D_
break;_x000D_
default:_x000D_
ddl2.options.length = 0;_x000D_
break;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
var opt = document.createElement('option');_x000D_
opt.value = value;_x000D_
opt.text = text;_x000D_
ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
<option value=""></option>_x000D_
<option value="Colours">Colours</option>_x000D_
<option value="Shapes">Shapes</option>_x000D_
<option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
_x000D_
_x000D_
Get full path of the files in PowerShell
Why has nobody used the foreach loop yet? A pro here is that you can easily name your variable:
# Note that I'm pretty explicit here. This would work as well as the line after:
# Get-ChildItem -Recurse C:\windows\System32\*.txt
$fileList = Get-ChildItem -Recurse -Path C:\windows\System32 -Include *.txt
foreach ($textfile in $fileList) {
# This includes the filename ;)
$filePath = $textfile.fullname
# You can replace the next line with whatever you want to.
Write-Output $filePath
}
Find Item in ObservableCollection without using a loop
I Don't know what do you mean exactly, but technially speaking, this is not possible without a loop.
May be you mean using a LINQ, like for example:
list.Where(x=>x.Title == title)
It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.
Hope this helps.
EDIT
In other words if you really concerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.
PHP ternary operator vs null coalescing operator
It seems there are pros and cons to using either ??
or ?:
. The pro to using ?:
is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ??
the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else
.
The following is an example of the difference of using the ??
operator using both null and false:
$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---
$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---
By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:
$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---
Personally, I think it would be really nice if a future rev of PHP included another new operator: :?
that replaced the above syntax. ie:
// $var = $false :? "true";
That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...
Resizing Images in VB.NET
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
phpmailer error "Could not instantiate mail function"
For what it's worth I had this issue and had to go into cPanel where I saw the error message
"Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find "Registered Mail IDs" plugin in paper_lantern theme."
Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.
Hope that helps someone.
Android - Dynamically Add Views into View
Use the LayoutInflater
to create a view based on your layout template, and then inject it into the view where you need it.
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);
// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
You may have to adjust the index where you want to insert the view.
Additionally, set the LayoutParams according to how you would like it to fit in the parent view. e.g. with FILL_PARENT
, or MATCH_PARENT
, etc.
JavaScript, get date of the next day
Copy-pasted from here:
Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating
a new date):
var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow
= new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than
returning a new instance, so today.add(1, 'days') would modify today.
That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
Why is list initialization (using curly braces) better than the alternatives?
There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:
- If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
- If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
- For default initialization I always use curly braces.
For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.
In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).
It e.g. fits nicely with standard library-types like std::vector
:
vector<int> a{10,20}; //Curly braces -> fills the vector with the arguments
vector<int> b(10,20); //Parentheses -> uses arguments to parametrize some functionality,
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.
vector<int> d{}; //empty braces -> default constructs vector, which is equivalent
//to a vector that is filled with zero elements
how to convert JSONArray to List of Object using camel-jackson
The problem is not in your code but in your json:
{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}
this represents an object which contains a property Compemployes which is a list of
Employee. In that case you should create that object like:
class EmployeList{
private List<Employe> compemployes;
(with getter an setter)
}
and to deserialize the json simply do:
EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);
If your json should directly represent a list of employees it should look like:
[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]
Last remark:
List<Employee> list2 = mapper.readValue(jsonString,
TypeFactory.collectionType(List.class, Employee.class));
TypeFactory.collectionType
is deprecated you should now use something like:
List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,
Employee.class));
How to increase the distance between table columns in HTML?
A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.
For example,
_x000D_
_x000D_
table {_x000D_
border-collapse: separate;_x000D_
border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>First Column</td>_x000D_
<td>Second Column</td>_x000D_
<td>Third Column</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
To avoid this use: border-left: 100px solid #FFF;
and set border:0px
for the first column.
For example,
_x000D_
_x000D_
td,th{_x000D_
border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
tr>td:first-child {_x000D_
border:0px;_x000D_
}
_x000D_
<table id="t">_x000D_
<tr>_x000D_
<td>Column1</td>_x000D_
<td>Column2</td>_x000D_
<td>Column3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1000</td>_x000D_
<td>2000</td>_x000D_
<td>3000</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
Javascript Equivalent to C# LINQ Select
I am answering the title of the question rather than the original question which was more specific.
With the new features of Javascript like iterators and generator functions and objects, something like LINQ for Javascript becomes possible. Note that linq.js, for example, uses a completely different approach, using regular expressions, probably to overcome the lack of support in the language at the time.
With that being said, I've written a LINQ library for Javascript and you can find it at https://github.com/Siderite/LInQer. Comments and discussion at https://siderite.dev/blog/linq-in-javascript-linqer.
From previous answers, only Manipula seems to be what one would expect from a LINQ port in Javascript.
E: Unable to locate package mongodb-org
I had the same issue in 14.04, but I fixed it by these steps:
- sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
- echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb- org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
- sudo apt-get update
- sudo apt-get install -y mongodb
It worked like charm :)
Append an array to another array in JavaScript
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_
How do I add a simple jQuery script to WordPress?
You can use WordPress predefined function to add script file to WordPress plugin.
wp_enqueue_script( 'script', plugins_url('js/demo_script.js', __FILE__), array('jquery'));
Look at the post which helps you to understand that how easily you can implement jQuery and CSS in WordPress plugin.
How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?
I use this code ...
function rmDirectory($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}
or this one...
<?php
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
?>
How should you diagnose the error SEHException - External component has thrown an exception
Just another information...
Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users.
Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException
jQuery $("#radioButton").change(...) not firing during de-selection
With Ajax, for me worked:
Html:
<div id='anID'>
<form name="nameOfForm">
<p><b>Your headline</b></p>
<input type='radio' name='nameOfRadio' value='seed'
<?php if ($interviewStage == 'seed') {echo" checked ";}?>
onchange='funcInterviewStage()'><label>Your label</label><br>
</form>
</div>
Javascript:
function funcInterviewStage() {
var dis = document.nameOfForm.nameOfRadio.value;
//Auswahltafel anzeigen
if (dis == "") {
document.getElementById("anID").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("anID").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/includes/[name].php?id="+dis,true);
xmlhttp.send();
}
}
And php:
//// Get Value
$id = mysqli_real_escape_string($db, $_GET['id']);
//// Insert to database
$insert = mysqli_query($db, "UPDATE [TABLE] SET [column] = '$id' WHERE [...]");
//// Show radio buttons again
$mysqliAbfrage = mysqli_query($db, "SELECT [column] FROM [Table] WHERE [...]");
while ($row = mysqli_fetch_object($mysqliAbfrage)) {
...
}
echo"
<form name='nameOfForm'>
<p><b>Your headline</b></p>
<input type='radio' name='nameOfRadio' value='seed'"; if ($interviewStage == 'seed') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Yourr Label</label><br>
<input type='radio' name='nameOfRadio' value='startup'"; if ($interviewStage == 'startup') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Your label</label><br>
</form> ";
How to debug apk signed for release?
Besides Manuel's way, you can still use the Manifest.
In Android Studio stable, you have to add the following 2 lines to application
in the AndroidManifest
file:
android:debuggable="true"
tools:ignore="HardcodedDebugMode"
The first one will enable debugging of signed APK, and the second one will prevent compile-time error.
After this, you can attach to the process via "Attach debugger to Android process" button.
scp (secure copy) to ec2 instance without password
copy a file from a local server to a remote server
sudo scp -i my-pem-file.pem ./source/test.txt [email protected]:~/destination/
copy a file from a remote server to a local machine
sudo scp -i my-pem-file.pem [email protected]:~/source/of/remote/test.txt ./where/to/put
So the basically syntax is:-
scp -i my-pem-file.pem username@source:/location/to/file username@destination:/where/to/put
-i
is for the identity_file
NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?
This is the problem that is occurring,
if the JAR file was loaded from "C:\java\apps\appli.jar", and your manifest file has the Class-Path: reference "lib/other.jar", the class loader will look in "C:\java\apps\lib\" for "other.jar". It won't look at the JAR file entry "lib/other.jar".
Solution:-
- Right click on project, Select Export.
- Select Java Folder and in it select Runnable JAR File instead of JAR file.
- Select the proper options and in the Library Handling section select the 3rd option i.e. (Copy required libraries into a sub-folder next to the generated JAR).
[ EDIT = 3rd option generates a folder in addition to the jar, 2nd option ("Package required libraries into generated JAR") can also be used as you have the jar. ]
- Click finish and your JAR is created at the specified position along with a folder that contains the JARS mentioned in the manifest file.
open the terminal,give the proper path to your jar and run it using this command java -jar abc.jar
Now what will happen is the class loader will look in the correct folder for the referenced JARS since now they are present in the same folder that contains your app JAR..There is no "java.lang.NoClassDefFoundError" exception thrown now.
This worked for me... Hope it works for you too!!!
Adding rows to dataset
To add rows to existing DataTable in Dataset:
DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);
How do I pass multiple attributes into an Angular.js attribute directive?
The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.
Template:
<div example-directive example-number="99" example-function="exampleCallback()"></div>
Directive:
app.directive('exampleDirective ', function () {
return {
restrict: 'A', // 'A' is the default, so you could remove this line
scope: {
callback : '&exampleFunction',
},
link: function (scope, element, attrs) {
var num = scope.$eval(attrs.exampleNumber);
console.log('number=',num);
scope.callback(); // calls exampleCallback()
}
};
});
fiddle
If the value of attribute example-number
will be hard-coded, I suggest using $eval
once, and storing the value. Variable num
will have the correct type (a number).
Java - Reading XML file
If using another library is an option, the following may be easier:
package for_so;
import java.io.File;
import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;
public class Q7704827_SimpleRead
{
public static void
main(String[] args)
{
String fileName = args[0];
TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
String recipient = emailNode.nextTextFieldE("recipient");
String sender = emailNode.nextTextFieldE("sender");
String subject = emailNode.nextTextFieldE("subject");
String description = emailNode.nextTextFieldE("description");
emailNode.verifyNoMoreChildren();
System.out.println("recipient = " + recipient);
System.out.println("sender = " + sender);
System.out.println("subject = " + subject);
System.out.println("desciption = " + description);
}
}
The library and its documentation are at rasmustorkel.com
Non-alphanumeric list order from os.listdir()
The proposed combination of os.listdir
and sorted
commands generates the same result as ls -l
command under Linux. The following example verifies this assumption:
user@user-PC:/tmp/test$ touch 3a 4a 5a b c d1 d2 d3 k l p0 p1 p3 q 410a 409a 408a 407a
user@user-PC:/tmp/test$ ls -l
total 0
-rw-rw-r-- 1 user user 0 Feb 15 10:31 3a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 407a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 408a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 409a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 410a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 4a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 5a
-rw-rw-r-- 1 user user 0 Feb 15 10:31 b
-rw-rw-r-- 1 user user 0 Feb 15 10:31 c
-rw-rw-r-- 1 user user 0 Feb 15 10:31 d1
-rw-rw-r-- 1 user user 0 Feb 15 10:31 d2
-rw-rw-r-- 1 user user 0 Feb 15 10:31 d3
-rw-rw-r-- 1 user user 0 Feb 15 10:31 k
-rw-rw-r-- 1 user user 0 Feb 15 10:31 l
-rw-rw-r-- 1 user user 0 Feb 15 10:31 p0
-rw-rw-r-- 1 user user 0 Feb 15 10:31 p1
-rw-rw-r-- 1 user user 0 Feb 15 10:31 p3
-rw-rw-r-- 1 user user 0 Feb 15 10:31 q
user@user-PC:/tmp/test$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir( './' )
['d3', 'k', 'p1', 'b', '410a', '5a', 'l', 'p0', '407a', '409a', '408a', 'd2', '4a', 'p3', '3a', 'q', 'c', 'd1']
>>> sorted( os.listdir( './' ) )
['3a', '407a', '408a', '409a', '410a', '4a', '5a', 'b', 'c', 'd1', 'd2', 'd3', 'k', 'l', 'p0', 'p1', 'p3', 'q']
>>> exit()
user@user-PC:/tmp/test$
So, for someone who wants to reproduce the result of the well-known ls -l
command in their python code, sorted( os.listdir( DIR ) )
works pretty well.
CASCADE DELETE just once
I cannot comment Palehorse's answer so I added my own answer.
Palehorse's logic is ok but efficiency can be bad with big data sets.
DELETE FROM some_child_table sct
WHERE exists (SELECT FROM some_Table st
WHERE sct.some_fk_fiel=st.some_id);
DELETE FROM some_table;
It is faster if you have indexes on columns and data set is bigger than few records.
Codeigniter displays a blank page instead of error messages
In system/core/Common.php
there is an exception handler, with a block of code that looks like this:
// We don't bother with "strict" notices since they tend to fill up
// the log file with excess information that isn't normally very helpful.
if ($severity == E_STRICT)
{
return;
}
By removing the if
and the return
and the incorrect comment, I was able to get an error message, instead of just a blank page. This project isn't using the most recent version of CodeIgniter, hopefully they've fixed this bug by now.
Div Height in Percentage
There is the semicolon missing (;) after the "50%"
but you should also notice that the percentage of your div is connected to the div that contains it.
for instance:
<div id="wrapper">
<div class="container">
adsf
</div>
</div>
#wrapper {
height:100px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.
if you have:
adsf
#wrapper {
height:400px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
then you .container will be 200px. 50% of the wrapper.
So you may want to look at the divs "wrapping" your ".container"...
When to use SELECT ... FOR UPDATE?
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
Utility of HTTP header "Content-Type: application/force-download" for mobile?
To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type
$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php
SQLException: No suitable driver found for jdbc:derby://localhost:1527
For me
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
helped. In this way, the DriveManager does know the derby EmbeddedDriver. Maybe allocating a new EmbeddedDriver is to heavy but on the other side, Class.forName needs try/catch/doSomethingIntelligentWithException that I dont like very much.
How to get the onclick calling object?
I think the best way is to use currentTarget property instead of target property.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.
For example:
<a href="#"><span class="icon"></span> blah blah</a>
Javascript:
a.addEventListener('click', e => {
e.currentTarget; // always returns "a" element
e.target; // may return "a" or "span"
})
Errors in pom.xml with dependencies (Missing artifact...)
I know it is an old question. But I hope my answer will help somebody. I had the same issue and I think the problem is that it cannot find those .jar files in your local repository. So what I did is I added the following code to my pom.xml and it worked.
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
IE Enable/Disable Proxy Settings via Registry
I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:
set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyEnable).proxyenable))
Is it possible to open developer tools console in Chrome on Android phone?
Kiwi Browser is mobile Chromium and allows installing extensions. Install Kiwi and then install "Mini JS console" Chrome extension(just search in Google and install from Chrome extensions website, uBlock also works ;). It will become available in Kiwi menu at the bottom and will show the console output for the current page.
Angular 4: no component factory found,did you add it to @NgModule.entryComponents?
TL;DR: A service in ng6 with providedIn: "root"
cannot find the ComponentFactory when the Component is not added in the entryComponents
of app.module.
This problem can also occur if you are using angular 6 in combination with dynamically creating a Component in a service!
For example, creating an Overlay:
@Injectable({
providedIn: "root"
})
export class OverlayService {
constructor(private _overlay: Overlay) {}
openOverlay() {
const overlayRef = this._createOverlay();
const portal = new ComponentPortal(OverlayExampleComponent);
overlayRef.attach(portal).instance;
}
}
The Problem is the
providedIn: "root"
definition, which provides this service in app.module.
So if your service is located in, for example, the "OverlayModule", where you also declared the OverlayExampleComponent and added it to the entryComponents, the service cannot find the ComponentFactory for OverlayExampleComponent.
A CSS selector to get last visible div
If you can use inline styles, then you can do it purely with CSS.
I am using this for doing CSS on the next element when the previous one is visible:
div[style='display: block;'] + table {
filter: blur(3px);
}
How to sort a dataframe by multiple column(s)
I learned about order
with the following example which then confused me for a long time:
set.seed(1234)
ID = 1:10
Age = round(rnorm(10, 50, 1))
diag = c("Depression", "Bipolar")
Diagnosis = sample(diag, 10, replace=TRUE)
data = data.frame(ID, Age, Diagnosis)
databyAge = data[order(Age),]
databyAge
The only reason this example works is because order
is sorting by the vector Age
, not by the column named Age
in the data frame data
.
To see this create an identical data frame using read.table
with slightly different column names and without making use of any of the above vectors:
my.data <- read.table(text = '
id age diagnosis
1 49 Depression
2 50 Depression
3 51 Depression
4 48 Depression
5 50 Depression
6 51 Bipolar
7 49 Bipolar
8 49 Bipolar
9 49 Bipolar
10 49 Depression
', header = TRUE)
The above line structure for order
no longer works because there is no vector named age
:
databyage = my.data[order(age),]
The following line works because order
sorts on the column age
in my.data
.
databyage = my.data[order(my.data$age),]
I thought this was worth posting given how confused I was by this example for so long. If this post is not deemed appropriate for the thread I can remove it.
EDIT: May 13, 2014
Below is a generalized way of sorting a data frame by every column without specifying column names. The code below shows how to sort from left to right or by right to left. This works if every column is numeric. I have not tried with a character column added.
I found the do.call
code a month or two ago in an old post on a different site, but only after extensive and difficult searching. I am not sure I could relocate that post now. The present thread is the first hit for ordering a data.frame
in R
. So, I thought my expanded version of that original do.call
code might be useful.
set.seed(1234)
v1 <- c(0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1)
v2 <- c(0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1)
v3 <- c(0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1)
v4 <- c(0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1)
df.1 <- data.frame(v1, v2, v3, v4)
df.1
rdf.1 <- df.1[sample(nrow(df.1), nrow(df.1), replace = FALSE),]
rdf.1
order.rdf.1 <- rdf.1[do.call(order, as.list(rdf.1)),]
order.rdf.1
order.rdf.2 <- rdf.1[do.call(order, rev(as.list(rdf.1))),]
order.rdf.2
rdf.3 <- data.frame(rdf.1$v2, rdf.1$v4, rdf.1$v3, rdf.1$v1)
rdf.3
order.rdf.3 <- rdf.1[do.call(order, as.list(rdf.3)),]
order.rdf.3
Object variable or With block variable not set (Error 91)
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
Simulate user input in bash script
Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:
echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
Expected corresponding JSX closing tag for input Reactjs
All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.
Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:
<hr class="my-4">
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
>
Fix:
<hr class="my-4"/>
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
/>
The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.
How to place and center text in an SVG rectangle
SVG 1.2 Tiny added text wrapping, but most implementations of SVG that you will find in the browser (with the exception of Opera) have not implemented this feature. It's typically up to you, the developer, to position text manually.
The SVG 1.1 specification provides a good overview of this limitation, and the possible solutions to overcome it:
Each ‘text’ element causes a single
string of text to be rendered. SVG
performs no automatic line breaking or
word wrapping. To achieve the effect
of multiple lines of text, use one of
the following methods:
- The author or authoring package needs
to pre-compute the line breaks and use
multiple ‘text’ elements (one for each
line of text).
- The author or authoring
package needs to pre-compute the line
breaks and use a single ‘text’ element
with one or more ‘tspan’ child
elements with appropriate values for
attributes ‘x’, ‘y’, ‘dx’ and ‘dy’ to
set new start positions for those
characters who start new lines.
(This approach allows user text
selection across multiple lines of
text -- see Text selection and
clipboard operations.)
- Express the
text to be rendered in another XML
namespace such as XHTML [XHTML]
embedded inline within a
‘foreignObject’ element. (Note: the
exact semantics of this approach are
not completely defined at this time.)
http://www.w3.org/TR/SVG11/text.html#Introduction
As a primitive, text wrapping can be simulated by using the dy
attribute and tspan
elements, and as mentioned in the spec, some tools can automate this. For example, in Inkscape, select the shape you want, and the text you want, and use Text -> Flow into Frame. This will allow you to write your text, with wrapping, which will wrap based on the bounds of the shape. Also, make sure you follow these instructions to tell Inkscape to maintain compatibility with SVG 1.1:
http://wiki.inkscape.org/wiki/index.php/FAQ#What_about_flowed_text.3F
Furthermore, there are some JavaScript libraries that can be used to dynamically automate text wrapping:
http://www.carto.net/papers/svg/textFlow/
It's interesting to note CSVG's solution to wrapping a shape to a text element (e.g. see their "button" example), although it's important to mention that their implementation is not usable in a browser:
http://www.csse.monash.edu.au/~clm/csvg/about.html
I'm mentioning this because I have developed a CSVG-inspired library that allows you to do similar things and does work in web browsers, although I haven't released it yet.
SQL Error: 0, SQLState: 08S01 Communications link failure
The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing.
So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.
Smooth GPS data
As for least squares fit, here are a couple other things to experiment with:
Just because it's least squares fit doesn't mean that it has to be linear. You can least-squares-fit a quadratic curve to the data, then this would fit a scenario in which the user is accelerating. (Note that by least squares fit I mean using the coordinates as the dependent variable and time as the independent variable.)
You could also try weighting the data points based on reported accuracy. When the accuracy is low weight those data points lower.
Another thing you might want to try is rather than display a single point, if the accuracy is low display a circle or something indicating the range in which the user could be based on the reported accuracy. (This is what the iPhone's built-in Google Maps application does.)
Angular checkbox and ng-click
The order of execution of ng-click
and ng-model
is ambiguous since they do not define clear priorities. Instead you should use ng-change
or a $watch
on the $scope
to ensure that you obtain the correct values of the model variable.
In your case, this should work:
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
Uncaught TypeError: Cannot set property 'value' of null
You don't have an element with the id u
.That's why the error occurs.
Note that the global variable document.getElementById("u").value
means you are trying to get the value of input element with name u
and its not defined in your code.
Two HTML tables side by side, centered on the page
I found I could solve this by simply putting the two side by side tables inside of a third table that was centered. Here is the code
I added two lines of code at the top and bottom of the two existing tables
_x000D_
_x000D_
<style>_x000D_
#outer {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#inner {_x000D_
text-align: left;_x000D_
margin: 0 auto;_x000D_
}_x000D_
_x000D_
.t {_x000D_
float: left;_x000D_
}_x000D_
_x000D_
table {_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
#clearit {_x000D_
clear: left;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<div id="outer">_x000D_
_x000D_
<p>Two tables, side by side, centered together within the page.</p>_x000D_
_x000D_
<div id="inner">_x000D_
<table style="margin-left: auto; margin-right: auto;">_x000D_
<td>_x000D_
<div class="t">_x000D_
<table>_x000D_
<tr>_x000D_
<th>a</th>_x000D_
<th>b</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>9</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>16</td>_x000D_
<td>25</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="t">_x000D_
<table>_x000D_
<tr>_x000D_
<th>a</th>_x000D_
<th>b</th>_x000D_
<th>c</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>5</td>_x000D_
<td>15</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>8</td>_x000D_
<td>13</td>_x000D_
<td>104</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</td>_x000D_
</table>_x000D_
</div>_x000D_
<div id="clearit">all done.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to access a value defined in the application.properties file in Spring Boot
You can do it this way as well....
@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {
@Autowired
private Environment env;
public String getConfigValue(String configKey){
return env.getProperty(configKey);
}
}
Then wherever you want to read from application.properties, just pass the key to getConfigValue method.
@Autowired
ConfigProperties configProp;
// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port");
How to present a simple alert message in java?
If you don't like "verbosity" you can always wrap your code in a short method:
private void msgbox(String s){
JOptionPane.showMessageDialog(null, s);
}
and the usage:
msgbox("don't touch that!");
Javascript add method to object
You can make bar a function making it a method.
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
Foo.bar = "a place";
Apache Name Virtual Host with SSL
It sounds like Apache is warning you that you have multiple <VirtualHost>
sections with the same IP address and port... as far as getting it to work without warnings, I think you would need to use something like Server Name Indication (SNI), a way of identifying the hostname requested as part of the SSL handshake. Basically it lets you do name-based virtual hosting over SSL, but I'm not sure how well it's supported by browsers. Other than something like SNI, you're basically limited to one SSL-enabled domain name for each IP address you expose to the public internet.
Of course, if you are able to access the websites properly, you'll probably be fine ignoring the warnings. These particular ones aren't very serious - they're mainly an indication of what to look at if you are experiencing problems
How to select true/false based on column value?
Maybe too late, but I'd cast 0/1 as bit to make the datatype eventually becomes True/False when consumed by .NET framework:
SELECT EntityId,
EntityName,
CASE
WHEN EntityProfileIs IS NULL
THEN CAST(0 as bit)
ELSE CAST(1 as bit) END AS HasProfile
FROM Entities
LEFT JOIN EntityProfiles ON EntityProfiles.EntityId = Entities.EntityId`
How to show progress bar while loading, using ajax
_x000D_
_x000D_
$(document).ready(function () { _x000D_
$(document).ajaxStart(function () {_x000D_
$('#wait').show();_x000D_
});_x000D_
$(document).ajaxStop(function () {_x000D_
$('#wait').hide();_x000D_
});_x000D_
$(document).ajaxError(function () {_x000D_
$('#wait').hide();_x000D_
}); _x000D_
});
_x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
<img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_
Android - how to make a scrollable constraintlayout?
Just use constraint layout inside NestedScrollView
or ScrollView
.
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
thats it. enjoy your coding.
Setting table row height
once I need to fix the height of a particular valued row
by using inline CSS as following..
<tr><td colspan="4" style="height: 10px;">xxxyyyzzz</td></tr>
Bloomberg Open API
This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.
The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.
What is ".NET Core"?
I was trying to create a new project in Visual Studio 2017 today (recently upgraded from Visual Studio 2015) and noticed new set of choices for the type of project. Either they're new or it's been a while since I started a new project!! :)
I came across this documentation link and found it very useful, so I am sharing. The details of the bullets are also provided in the article. I am just posting bullets here:
You should use .NET Core for your server application when:
You have cross-platform needs.
You are targeting microservices.
You are using Docker containers.
You need high performance and scalable systems.
You need side by side of .NET versions by application.
You should use .NET Framework for your server application when:
Your application currently uses .NET Framework (recommendation is to extend instead of migrating)
You need to use third-party .NET libraries or NuGet packages not available for .NET Core.
You need to use .NET technologies that are not available for .NET Core.
You need to use a platform that doesn’t support .NET Core.
This link provides a glossary of .NET terms.
EDIT 10/7/2020
Check out .NET 5.0 - "... just one .NET going forward, and you will be able to use it to target Windows, Linux, macOS, iOS, Android, tvOS, watchOS and WebAssembly and more"
It's supposed to be released November 2020.
Make elasticsearch only return certain fields?
There are several methods that can be useful to achieve field-specific results.
One can be through the source method.
And another method that can also be useful to receive cleaner and more summarized answers according to our interests is filter_path:
Document Json:
"hits" : [
{
"_index" : "xxxxxx",
"_type" : "_doc",
"_id" : "xxxxxx",
"_score" : xxxxxx,
"_source" : {
"year" : 2020,
"created_at" : "2020-01-29",
"url" : "www.github.com/mbarr0987",
"name":"github"
}
}
Query:
GET bot1/_search?filter_path=hits.hits._source.url
{
"query": {
"bool": {
"must": [
{"term": {"name.keyword":"github" }}
]
}
}
}
Output:
{
"hits" : {
"hits" : [
{
"_source" : {
"url" : "www.github.com/mbarr0987"
}
}
]
}
}
Performance of Arrays vs. Lists
if you are just getting a single value out of either (not in a loop) then both do bounds checking (you're in managed code remember) it's just the list does it twice.
See the notes later for why this is likely not a big deal.
If you are using your own for(int int i = 0; i < x.[Length/Count];i++) then the key difference is as follows:
- Array:
- bounds checking is removed
- Lists
- bounds checking is performed
If you are using foreach then the key difference is as follows:
- Array:
- no object is allocated to manage the iteration
- bounds checking is removed
- List via a variable known to be List.
- the iteration management variable is stack allocated
- bounds checking is performed
- List via a variable known to be IList.
- the iteration management variable is heap allocated
- bounds checking is performed
also Lists values may not be altered during the foreach whereas the array's can be.
The bounds checking is often no big deal (especially if you are on a cpu with a deep pipeline and branch prediction - the norm for most these days) but only your own profiling can tell you if that is an issue.
If you are in parts of your code where you are avoiding heap allocations (good examples are libraries or in hashcode implementations) then ensuring the variable is typed as List not IList will avoid that pitfall.
As always profile if it matters.
How to use MapView in android using google map V2?
I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX
You can find complete project here: github-link
MainActivity.kt
class MainActivity : AppCompatActivity() {
val position = LatLng(-33.920455, 18.466941)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with(mapView) {
// Initialise the MapView
onCreate(null)
// Set the map ready callback to receive the GoogleMap object
getMapAsync{
MapsInitializer.initialize(applicationContext)
setMapLocation(it)
}
}
}
private fun setMapLocation(map : GoogleMap) {
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
addMarker(MarkerOptions().position(position))
mapType = GoogleMap.MAP_TYPE_NORMAL
setOnMapClickListener {
Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
}
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API_KEY_HERE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/mapView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
android.os.NetworkOnMainThreadException with android 4.2
Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And below import statement into your java file.
import android.os.StrictMode;
React-Router open Link in new tab
For external link simply use an achor in place of Link:
<a rel="noopener noreferrer" href="http://url.com" target="_blank">Link Here</a>
How to measure height, width and distance of object using camera?
If you think about it, a body XRay scan (at the medical center) too needs this kind of measurement for estimating size of tumors. So they place a 1 Dollar Coin on the body, to do a comparative measurement.
Even newspaper is printed with some marks on the corners.
You need a reference to measure. May be you can get your person to wear a cap which has a few bright green circles. Once you recognize the size of the circle you can comparatively measure the remaining.
Or you can create a transparent 1 inch circle which will superimpose on the face, move the camera toward/away the face, aim your superimposed circle on that bright green circle on the cap. Then on your photo will be as per scale.
Clearing coverage highlighting in Eclipse
I found a workaround over on GitHub: https://github.com/jmhofer/eCobertura/issues/8
For those who don't want to click the link, here's the text of the comment:
Good workaround:
Create a run configuration with a filter, that excludes everything ("*") and let it run just a single test. Name it "Undo coverage".
I did this and it worked quite well in Eclipse Juno.
Credit for this goes to UsulSK.
How to store Node.js deployment settings/configuration files?
npm i config
In config/default.json
{
"app": {
"port": 3000
},
"db": {
"port": 27017,
"name": "dev_db_name"
}
}
In config/production.json
{
"app": {
"port": 4000
},
"db": {
"port": 27000,
"name": "prod_db_name"
}
}
In index.js
const config = require('config');
let appPort = config.get('app.port');
console.log(`Application port: ${appPort}`);
let dbPort = config.get('db.port');
console.log(`Database port: ${dbPort}`);
let dbName = config.get('db.name');
console.log(`Database name: ${dbName}`);
console.log('NODE_ENV: ' + config.util.getEnv('NODE_ENV'));
$ node index.js
Application port: 3000
Database port: 27017
Database name: dev_db_name
NODE_ENV: development
For production
$ set NODE_ENV=production
$ node index.js
Application port: 4000
Database port: 27000
Database name: prod_db_name
NODE_ENV: production
Pass a simple string from controller to a view MVC3
To pass a string to the view as the Model, you can do:
public ActionResult Index()
{
string myString = "This is my string";
return View((object)myString);
}
You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:
return View("Index", myString);
.. which is a bit more verbose.
Then in your view, just type it as a string:
@model string
<p>Value: @Model</p>
Then you can manipulate Model how you want.
For accessing it from a Layout page, it might be better to create an HtmlExtension for this:
public static string GetThemePath(this HtmlHelper helper)
{
return "/path-to-theme";
}
Then inside your layout page:
<p>Value: @Html.GetThemePath()</p>
Hopefully you can apply this to your own scenario.
Edit: explicit HtmlHelper code:
namespace <root app namespace>
{
public static class Helpers
{
public static string GetThemePath(this HtmlHelper helper)
{
return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
}
}
}
Then in your view:
@{
var path = Html.GetThemePath();
// .. do stuff
}
Or:
<p>Path: @Html.GetThemePath()</p>
Edit 2:
As discussed, the Helper will work if you add a @using
statement to the top of your view, with the namespace pointing to the one that your helper is in.
How to change the value of ${user} variable used in Eclipse templates
dovescrywolf gave tip as a comment on article linked by Davide Inglima
It was was very useful for me on MacOS.
- Close Eclipse if it's opened.
Open Termnal (bash console) and do below things:
$ pwd /Users/You/YourEclipseInstalationDirectory
$ cd Eclipse.app/Contents/MacOS/
$ echo "-Duser.name=Your Name" >> eclipse.ini
$ cat eclipse.ini
Close Terminal and start/open Eclipse again.
How to resolve Value cannot be null. Parameter name: source in linq?
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
How to write LDAP query to test if user is member of a group?
You must set your query base to the DN of the user in question, then set your filter to the DN of the group you're wondering if they're a member of. To see if jdoe is a member of the office group then your query will look something like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host '(memberof=cn=officegroup,dc=example,dc=local)'
If you want to see ALL the groups he's a member of, just request only the 'memberof' attribute in your search, like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host **memberof**
Cannot set content-type to 'application/json' in jQuery.ajax
Hi These two lines worked for me.
contentType:"application/json; charset=utf-8",
dataType:"json"
$.ajax({
type: "POST",
url: "/v1/candidates",
data: obj,
**contentType:"application/json; charset=utf-8",
dataType:"json",**
success: function (data) {
table.row.add([
data.name, data.title
]).draw(false);
}
Thanks,
Prashant
Git, How to reset origin/master to a commit?
origin/xxx
branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).
What you need to do to update the remote is to force push your local changes to master:
git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master
Cast Int to enum in Java
You can iterate over values()
of enum and compare integer value of enum with given id
like below:
public enum TestEnum {
None(0),
Value1(1),
Value2(2),
Value3(3),
Value4(4),
Value5(5);
private final int value;
private TestEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static TestEnum getEnum(int value){
for (TestEnum e:TestEnum.values()) {
if(e.getValue() == value)
return e;
}
return TestEnum.None;//For values out of enum scope
}
}
And use just like this:
TestEnum x = TestEnum.getEnum(4);//Will return TestEnum.Value4
I hope this helps ;)
How to parse JSON in Kotlin?
i am using my custom implementation in kotlin:
/**
* Created by Anton Kogan on 10/9/2020
*/
object JsonParser {
val TAG = "JsonParser"
/**
* parse json object
* @param objJson
* @param include - all keys, that you want to display
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?, map :HashMap<String, String>, include : Array<String>?): Map<String, String> {
// If obj is a json array
if (objJson is JSONArray) {
for (i in 0 until objJson.length()) {
parseJson(objJson[i], map, include)
}
} else if (objJson is JSONObject) {
val it: Iterator<*> = objJson.keys()
while (it.hasNext()) {
val key = it.next().toString()
// If you get an array
when (val jobject = objJson[key]) {
is JSONArray -> {
Log.e(TAG, " JSONArray: $jobject")
parseJson(
jobject, map, include
)
}
is JSONObject -> {
Log.e(TAG, " JSONObject: $jobject")
parseJson(
jobject, map, include
)
}
else -> {
//
if(include == null || include.contains(key)) // here is check for include param
{
map[key] = jobject.toString()
Log.e(TAG, " adding to map: $key $jobject")
}
}
}
}
}
return map
}
/**
* parse json object
* @param objJson
* @param include - all keys, that you want to display
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?, map :HashMap<String, String>): Map<String, String> {
return parseJson(objJson, map, null)
}
}
You can use it like:
val include= arrayOf(
"atHome",//JSONArray
"cat",
"dog",
"persons",//JSONArray
"man",
"woman"
)
JsonParser.parseJson(jsonObject, map, include)
val linearContent: LinearLayout = taskInfoFragmentBinding.infoContainer
here is some useful links:
json parsing :
plugin:
https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-
create POJOs from json:
https://codebeautify.org/jsonviewer
Retrofit:
https://square.github.io/retrofit/
Gson:
https://github.com/google/gson
How to search JSON data in MySQL?
for MySQL all (and 5.7)
SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;
Extract csv file specific columns to list in Python
This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv
module:
import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)
If you want your lists as in the question, you can now do:
names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()
Loop Through Each HTML Table Column and Get the Data using jQuery
When you create your table, put your td with class = "suma"
$(function(){
//funcion suma todo
var sum = 0;
$('.suma').each(function(x,y){
sum += parseInt($(this).text());
})
$('#lblTotal').text(sum);
// funcion suma por check
$( "input:checkbox").change(function(){
if($(this).is(':checked')){
$(this).parent().parent().find('td:last').addClass('suma2');
}else{
$(this).parent().parent().find('td:last').removeClass('suma2');
}
suma2Total();
})
function suma2Total(){
var sum2 = 0;
$('.suma2').each(function(x,y){
sum2 += parseInt($(this).text());
})
$('#lblTotal2').text(sum2);
}
});
Ejemplo completo
How to get row count in sqlite using Android?
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery
documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
Cannot read property 'style' of undefined -- Uncaught Type Error
It's currently working, I've just changed the operator >
in order to work in the snippet, take a look:
_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
if (window.location.href.indexOf("test") <= -1) {_x000D_
var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
search_span[0].style.color = "blue";_x000D_
search_span[0].style.fontWeight = "bold";_x000D_
search_span[0].style.fontSize = "40px";_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_
How to use java.net.URLConnection to fire and handle HTTP requests?
First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial IOException
s and RuntimeException
s like NullPointerException
, ArrayIndexOutOfBoundsException
and consorts yourself.
Preparing
We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.
String url = "http://example.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
The query parameters must be in name=value
format and be concatenated by &
. You would normally also URL-encode the query parameters with the specified charset using URLEncoder#encode()
.
The String#format()
is just for convenience. I prefer it when I would need the String concatenation operator +
more than twice.
Firing an HTTP GET request with (optionally) query parameters
It's a trivial task. It's the default request method.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
Any query string should be concatenated to the URL using ?
. The Accept-Charset
header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the Accept-Charset
header away. If you don't need to set any headers, then you can even use the URL#openStream()
shortcut method.
InputStream response = new URL(url).openStream();
// ...
Either way, if the other side is an HttpServlet
, then its doGet()
method will be called and the parameters will be available by HttpServletRequest#getParameter()
.
For testing purposes, you can print the response body to stdout as below:
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
Firing an HTTP POST request with query parameters
Setting the URLConnection#setDoOutput()
to true
implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type application/x-www-form-urlencoded
wherein the query string is written to the request body.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
// ...
Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the name=value
pairs of any <input type="hidden">
elements into the query string and of course also the name=value
pair of the <input type="submit">
element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).
You can also cast the obtained URLConnection
to HttpURLConnection
and use its HttpURLConnection#setRequestMethod()
instead. But if you're trying to use the connection for output you still need to set URLConnection#setDoOutput()
to true
.
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...
Either way, if the other side is an HttpServlet
, then its doPost()
method will be called and the parameters will be available by HttpServletRequest#getParameter()
.
Actually firing the HTTP request
You can fire the HTTP request explicitly with URLConnection#connect()
, but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using URLConnection#getInputStream()
and so on. The above examples does exactly that, so the connect()
call is in fact superfluous.
Gathering HTTP response information
- HTTP response status:
You need an HttpURLConnection
here. Cast it first if necessary.
int status = httpConnection.getResponseCode();
HTTP response headers:
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
HTTP response encoding:
When the Content-Type
contains a charset
parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
Maintaining the session
The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the CookieHandler
API to maintain cookies. You need to prepare a CookieManager
with a CookiePolicy
of ACCEPT_ALL
before sending all HTTP requests.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all Set-Cookie
headers from the response of the login or the first GET
request and then pass this through the subsequent requests.
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
The split(";", 2)[0]
is there to get rid of cookie attributes which are irrelevant for the server side like expires
, path
, etc. Alternatively, you could also use cookie.substring(0, cookie.indexOf(';'))
instead of split()
.
Streaming mode
The HttpURLConnection
will by default buffer the entire request body before actually sending it, regardless of whether you've set a fixed content length yourself using connection.setRequestProperty("Content-Length", contentLength);
. This may cause OutOfMemoryException
s whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the HttpURLConnection#setFixedLengthStreamingMode()
.
httpConnection.setFixedLengthStreamingMode(contentLength);
But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the HttpURLConnection#setChunkedStreamingMode()
accordingly. This will set the HTTP Transfer-Encoding
header to chunked
which will force the request body being sent in chunks. The below example will send the body in chunks of 1KB.
httpConnection.setChunkedStreamingMode(1024);
User-Agent
It can happen that a request returns an unexpected response, while it works fine with a real web browser. The server side is probably blocking requests based on the User-Agent
request header. The URLConnection
will by default set it to Java/1.6.0_19
where the last part is obviously the JRE version. You can override this as follows:
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
Use the User-Agent string from a recent browser.
Error handling
If the HTTP response code is 4nn
(Client Error) or 5nn
(Server Error), then you may want to read the HttpURLConnection#getErrorStream()
to see if the server has sent any useful error information.
InputStream error = ((HttpURLConnection) connection).getErrorStream();
If the HTTP response code is -1, then something went wrong with connection and response handling. The HttpURLConnection
implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the http.keepAlive
system property to false
. You can do this programmatically in the beginning of your application by:
System.setProperty("http.keepAlive", "false");
Uploading files
You'd normally use multipart/form-data
encoding for mixed POST content (binary and character data). The encoding is in more detail described in RFC2388.
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
If the other side is an HttpServlet
, then its doPost()
method will be called and the parts will be available by HttpServletRequest#getPart()
(note, thus not getParameter()
and so on!). The getPart()
method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc). Prior to Servlet 3.0, your best choice is using Apache Commons FileUpload to parse a multipart/form-data
request. Also see this answer for examples of both the FileUpload and the Servelt 3.0 approaches.
Dealing with untrusted or misconfigured HTTPS sites
Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a javax.net.ssl.SSLException: Not trusted server certificate
on some HTTPS sites who doesn't keep their SSL certificates up to date, or a java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found
or javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
on some misconfigured HTTPS sites.
The following one-time-run static
initializer in your web scraper class should make HttpsURLConnection
more lenient as to those HTTPS sites and thus not throw those exceptions anymore.
static {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Not relevant.
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Just allow them all.
}
};
try {
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e) {
throw new ExceptionInInitializerError(e);
}
}
Last words
The Apache HttpComponents HttpClient is much more convenient in this all :)
Parsing and extracting HTML
If all you want is parsing and extracting data from HTML, then better use a HTML parser like Jsoup
How can I get argv[] as int?
/*
Input from command line using atoi, and strtol
*/
#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol
//strtol - converts a string to a long int
//atoi - converts string to an int
int main(int argc, char *argv[]){
char *p;//used in strtol
int i;//used in for loop
long int longN = strtol( argv[1],&p, 10);
printf("longN = %ld\n",longN);
//cast (int) to strtol
int N = (int) strtol( argv[1],&p, 10);
printf("N = %d\n",N);
int atoiN;
for(i = 0; i < argc; i++)
{
//set atoiN equal to the users number in the command line
//The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
atoiN = atoi(argv[i]);
}
printf("atoiN = %d\n",atoiN);
//-----------------------------------------------------//
//Get string input from command line
char * charN;
for(i = 0; i < argc; i++)
{
charN = argv[i];
}
printf("charN = %s\n", charN);
}
Hope this helps. Good luck!
In a simple to understand explanation, what is Runnable in Java?
Runnable
is an interface defined as so:
interface Runnable {
public void run();
}
To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {
It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.
If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.
It should also be noted that Threads implement Runnable
, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable)
without overriding Thread's run
method.
How to debug when Kubernetes nodes are in 'Not Ready' state
First, describe nodes and see if it reports anything:
$ kubectl describe nodes
Look for conditions, capacity and allocatable:
Conditions:
Type Status
---- ------
OutOfDisk False
MemoryPressure False
DiskPressure False
Ready True
Capacity:
cpu: 2
memory: 2052588Ki
pods: 110
Allocatable:
cpu: 2
memory: 1950188Ki
pods: 110
If everything is alright here, SSH into the node and observe kubelet
logs to see if it reports anything. Like certificate erros, authentication errors etc.
If kubelet
is running as a systemd service, you can use
$ journalctl -u kubelet
Function to return only alpha-numeric characters from string?
Warning: Note that English is not restricted to just A-Z.
Try this to remove everything except a-z, A-Z and 0-9:
$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.
Try this to leave only A-Z:
$result = preg_replace("/[^A-Z]+/", "", $s);
The reason for the warning is that words like résumé contains the letter é
that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.
jQuery DataTables Getting selected row values
You can iterate over the row data
$('#button').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
console.log(ids)
alert(table.rows('.selected').data().length + ' row(s) selected');
});
Demo: Fiddle
How to get city name from latitude and longitude coordinates in Google Maps?
import org.json.JSONObject
fun parseLocation(response: String): GeoLocation? {
val geoCodes by lazy { doubleArrayOf(0.0, 0.0) }
val jObj = JSONObject(response)
if (jObj.has(KEY_RESULTS)) {
val jArrResults = jObj.getJSONArray(KEY_RESULTS)
for (i in 0 until jArrResults.length()) {
val jObjResult = jArrResults.getJSONObject(i)
//getting latitude and longitude
if (jObjResult.has(KEY_GEOMETRY)) {
val jObjGeometry = jObjResult.getJSONObject(KEY_GEOMETRY)
if (jObjGeometry.has(KEY_LOCATION)) {
val jObjLocation = jObjGeometry.getJSONObject(KEY_LOCATION)
if (jObjLocation.has(KEY_LAT)) {
geoCodes[0] = jObjLocation.getDouble(KEY_LAT)
}
if (jObjLocation.has(KEY_LNG)) {
geoCodes[1] = jObjLocation.getDouble(KEY_LNG)
}
}
}
var administrativeAreaLevel1: String? = null
//getting city
if (jObjResult.has(KEY_ADDRESS_COMPONENTS)) {
val jArrAddressComponents = jObjResult.getJSONArray(KEY_ADDRESS_COMPONENTS)
for (i in 0 until jArrAddressComponents.length()) {
val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
if (jObjAddressComponents.has(KEY_TYPES)) {
val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
for (j in 0 until jArrTypes.length()) {
when (jArrTypes.getString(j)) {
VALUE_LOCALITY, VALUE_POSTAL_TOWN -> {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
ADMINISTRATIVE_AREA_LEVEL_1 -> {
administrativeAreaLevel1 = jObjAddressComponents.getString(KEY_LONG_NAME)
}
else -> {
}
}
}
}
}
for (i in 0 until jArrAddressComponents.length()) {
val jObjAddressComponents = jArrAddressComponents.getJSONObject(i)
if (jObjAddressComponents.has(KEY_TYPES)) {
val jArrTypes = jObjAddressComponents.getJSONArray(KEY_TYPES)
val typeList = ArrayList<String>()
for (j in 0 until jArrTypes.length()) {
typeList.add(jArrTypes.getString(j))
}
if (typeList.contains(VALUE_SUBLOCALITY)) {
var hasSubLocalityLevel = false
typeList.forEach { type ->
if (type.contains(VALUE_SUBLOCALITY_LEVEL)) {
hasSubLocalityLevel = true
if (type == VALUE_SUBLOCALITY_LEVEL_1) {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
}
}
if (!hasSubLocalityLevel) {
return GeoLocation(jObjAddressComponents.getString(KEY_LONG_NAME), *geoCodes)
}
}
}
}
}
if (geoCodes.isNotEmpty()) return GeoLocation(administrativeAreaLevel1, geoCodes = *geoCodes)
}
}
return null
}
data class GeoLocation(val latitude: Double = 0.0, val longitude: Double = 0.0, val city: String? = null) : Parcelable {
constructor(city: String? = null, vararg geoCodes: Double) : this(geoCodes[0], geoCodes[1], city)
constructor(source: Parcel) : this(source.readDouble(), source.readDouble(), source.readString())
companion object {
@JvmField
val CREATOR = object : Parcelable.Creator<GeoLocation> {
override fun createFromParcel(source: Parcel) = GeoLocation(source)
override fun newArray(size: Int): Array<GeoLocation?> = arrayOfNulls(size)
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeDouble(latitude)
dest.writeDouble(longitude)
dest.writeString(city)
}
override fun describeContents() = 0
}
How do I do an initial push to a remote repository with Git?
You can try this:
on Server:
adding new group to /etc/group
like
(example)
mygroup:1001:michael,nir
create new git repository:
mkdir /srv/git
cd /srv/git
mkdir project_dir
cd project_dir
git --bare init (initial git repository )
chgrp -R mygroup objects/ refs/ (change owner of directory )
chmod -R g+w objects/ refs/ (give permission write)
on Client:
mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin [email protected]:/path/to/my_project.git
git push origin master
(Thanks Josh Lindsey for client side)
after Client, do on Server this commands:
cd /srv/git/project_dir
chmod -R g+w objects/ refs/
If got this error after git pull:
There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details
git pull <remote> <branch>
If you wish to set tracking information for this branch you can do so with:
git branch --set-upstream new origin/<branch>
try:
git push -u origin master
It will help.
Call PHP function from Twig template
While I agree with the comments about passing in variables from your controller you can also register undefined functions when setting up the twig environment
$twig->registerUndefinedFunctionCallback(function ($name) {
// security
$allowed = false;
switch ($name) {
// example of calling a wordpress function
case 'get_admin_page_title':
$allowed = true;
break;
}
if ($allowed && function_exists($name)) {
return new Twig_Function_Function($name);
}
return false;
});
This is from the Twig recipe page
Haven't tried calling a function on an object as the original question requested
How do I execute a program from Python? os.system fails due to spaces in path
Suppose we want to run your Django web server (in Linux) that there is space between your path (path='/home/<you>/<first-path-section> <second-path-section>'
), so do the following:
import subprocess
args = ['{}/manage.py'.format('/home/<you>/<first-path-section> <second-path-section>'), 'runserver']
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()
if not error_:
print(output)
else:
print(error_)
[Note]:
- Do not forget accessing permission:
chmod 755 -R <'yor path'>
manage.py
is exceutable: chmod +x manage.py
Get Base64 encode file-data from Input Form
After struggling with this myself, I've come to implement FileReader for browsers that support it (Chrome, Firefox and the as-yet unreleased Safari 6), and a PHP script that echos back POSTed file data as Base64-encoded data for the other browsers.
unique combinations of values in selected columns in pandas data frame and count
Placing @EdChum's very nice answer into a function count_unique_index
.
The unique method only works on pandas series, not on data frames.
The function below reproduces the behavior of the unique function in R:
unique returns a vector, data frame or array like x but with duplicate elements/rows removed.
And adds a count of the occurrences as requested by the OP.
df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],
'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})
def count_unique_index(df, by):
return df.groupby(by).size().reset_index().rename(columns={0:'count'})
count_unique_index(df1, ['A','B'])
A B count
0 no no 1
1 no yes 2
2 yes no 4
3 yes yes 3
How to override the path of PHP to use the MAMP path?
Probably too late to comment but here's what I did when I ran into issues with setting php PATH for my XAMPP installation on Mac OSX
- Open up the file .bash_profile (found under current user folder) using the available text editor.
- Add the path as below:
export PATH=/path/to/your/php/installation/bin:leave/rest/of/the/stuff/untouched/:$PATH
- Save your .bash_profile and re-start your Mac.
Explanation: Terminal / Mac tries to run a search on the PATHS it knows about, in a hope of finding the program, when user initiates a program from the "Terminal", hence the trick here is to make the terminal find the php, the user intends to, by pointing it to the user's version of PHP at some bin folder, installed by the user.
Worked for me :)
P.S I'm still a lost sheep around my new Computer ;)
How to make background of table cell transparent
It is possible
You just also need to apply the color to 'tbody' element as that's the table body that's been causing our trouble by peeking underneath.
table, tbody, tr, th, td{
background-color: rgba(0, 0, 0, 0.0) !important;
}
Remove ':hover' CSS behavior from element
You want to keep the selector, so adding/removing it won't work. Instead of writing a hard and fast CSS selectors (or two), perhaps you can just use the original selector to apply new CSS rule to that element based on some criterion:
$(".test").hover(
if(some evaluation) {
$(this).css('border':0);
}
);
JavaFX "Location is required." even though it is in the same package
This problem can be caused by incorrect path to the FXML file.
If you're using absolute paths (my/package/views/view.fxml
), you have to precede then with a slash:
getClass().getResource("/my/package/views/view.fxml")
You can use relative paths as well:
getClass().getResource("views/view.fxml")
get the titles of all open windows
Hera's the function UpdateWindowsList_WindowMenu() that you must call after any operations are performed on Tabs.Here windowToolStripMenuItem is the menu item added to Window Menu to menu strip.
public void UpdateWindowsList_WindowMenu()
{
//get all tab pages from tabControl1
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
//get windowToolStripMenuItem drop down menu items count
int n = windowToolStripMenuItem.DropDownItems.Count;
//remove all menu items from of windowToolStripMenuItem
for (int i = n - 1; i >=2; i--)
{
windowToolStripMenuItem.DropDownItems.RemoveAt(i);
}
//read each tabpage from tabcoll and add each tabpage text to windowToolStripMenuItem
foreach (TabPage tabpage in tabcoll)
{
//create Toolstripmenuitem
ToolStripMenuItem menuitem = new ToolStripMenuItem();
String s = tabpage.Text;
menuitem.Text = s;
if (tabControl1.SelectedTab == tabpage)
{
menuitem.Checked = true;
}
else
{
menuitem.Checked = false;
}
//add menuitem to windowToolStripMenuItem
windowToolStripMenuItem.DropDownItems.Add(menuitem);
//add click events to each added menuitem
menuitem.Click += new System.EventHandler(WindowListEvent_Click);
}
}
private void WindowListEvent_Click(object sender, EventArgs e)
{
//casting ToolStripMenuItem to ToolStripItem
ToolStripItem toolstripitem = (ToolStripItem)sender;
//create collection of tabs of tabContro1
//check every tab text is equal to clicked menuitem then select the tab
TabControl.TabPageCollection tabcoll = tabControl1.TabPages;
foreach (TabPage tb in tabcoll)
{
if (toolstripitem.Text == tb.Text)
{
tabControl1.SelectedTab = tb;
//call UpdateWindowsList_WindowMenu() to perform changes on menuitems
UpdateWindowsList_WindowMenu();
}
}
}
Changing Locale within the app itself
This is for my comment on Andrey's answer but I cant include code in the comments.
Is you preference activity being called from you main activity? you could place this in the on resume...
@Override
protected void onResume() {
if (!(PreferenceManager.getDefaultSharedPreferences(
getApplicationContext()).getString("listLanguage", "en")
.equals(langPreference))) {
refresh();
}
super.onResume();
}
private void refresh() {
finish();
Intent myIntent = new Intent(Main.this, Main.class);
startActivity(myIntent);
}
Hexadecimal To Decimal in Shell Script
Dealing with a very lightweight embedded version of busybox on Linux means many of the traditional commands are not available (bc, printf, dc, perl, python)
echo $((0x2f))
47
hexNum=2f
echo $((0x${hexNum}))
47
Credit to Peter Leung for this solution.
How to get all table names from a database?
@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
List<String> tables = new ArrayList<String>();
String db = "";
while (rs.next()) {
tables.add(rs.getString(3));
db = rs.getString(1);
}
List<String> database = new ArrayList<String>();
database.add(db);
databaseTables.put("database", database);
Collections.reverse(tables);
databaseTables.put("tables", tables);
return new ObjectMapper().writeValueAsString(databaseTables);
}
@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{
System.out.println("...tablename......"+tablename);
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
Statement st = con.createStatement();
String sql = "select * from "+tablename;
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
HashMap<String,String> columnDetails = new HashMap<String,String>();
for (int i = 0; i < rowCount; i++) {
columnDetails = new HashMap<String,String>();
Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
method.setAccessible(true);
com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
columnDetails.put("columnColl", field.getCollation());
columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
if (field.isPrimaryKey()) {
columnDetails.put("columnKEY", "PRI");
} else if(field.isMultipleKey()) {
columnDetails.put("columnKEY", "MUL");
} else if(field.isUniqueKey()) {
columnDetails.put("columnKEY", "UNI");
} else {
columnDetails.put("columnKEY", "");
}
columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
databaseColumns.add(columnDetails);
}
HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
Collections.reverse(databaseColumns);
tableColumns.put("columns", databaseColumns);
return new ObjectMapper().writeValueAsString(tableColumns);
}
How to use a keypress event in AngularJS?
Some example of code that I did for my project.
Basically you add tags to your entity.
Imagine you have input text, on entering Tag name you get drop-down menu with preloaded tags to choose from, you navigate with arrows and select with Enter:
HTML + AngularJS v1.2.0-rc.3
<div>
<form ng-submit="addTag(newTag)">
<input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
data-toggle="dropdown"
ng-change="preloadTags()"
ng-keydown="navigateTags($event)">
<div ng-show="preloadedTags.length > 0">
<nav class="dropdown">
<div class="dropdown-menu preloadedTagPanel">
<div ng-repeat="preloadedTag in preloadedTags"
class="preloadedTagItemPanel"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemPanelActive' : '' "
ng-click="selectTag(preloadedTag)"
tabindex="{{ $index }}">
<a class="preloadedTagItem"
ng-class="preloadedTag.activeTag ? 'preloadedTagItemActive' : '' "
ng-click="selectTag(preloadedTag)">{{ preloadedTag.label }}</a>
</div>
</div>
</nav>
</div>
</form>
</div>
Controller.js
$scope.preloadTags = function () {
var newTag = $scope.newTag;
if (newTag && newTag.trim()) {
newTag = newTag.trim().toLowerCase();
$http(
{
method: 'GET',
url: 'api/tag/gettags',
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
params: {'term': newTag}
}
)
.success(function (result) {
$scope.preloadedTags = result;
$scope.preloadedTagsIndex = -1;
}
)
.error(function (data, status, headers, config) {
}
);
} else {
$scope.preloadedTags = {};
$scope.preloadedTagsIndex = -1;
}
};
function checkIndex(index) {
if (index > $scope.preloadedTags.length - 1) {
return 0;
}
if (index < 0) {
return $scope.preloadedTags.length - 1;
}
return index;
}
function removeAllActiveTags() {
for (var x = 0; x < $scope.preloadedTags.length; x++) {
if ($scope.preloadedTags[x].activeTag) {
$scope.preloadedTags[x].activeTag = false;
}
}
}
$scope.navigateTags = function ($event) {
if (!$scope.newTag || $scope.preloadedTags.length == 0) {
return;
}
if ($event.keyCode == 40) { // down
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 38) { // up
removeAllActiveTags();
$scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
$scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
} else if ($event.keyCode == 13) { // enter
removeAllActiveTags();
$scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
}
};
$scope.selectTag = function (preloadedTag) {
$scope.addTag(preloadedTag.label);
};
CSS + Bootstrap v2.3.2
.preloadedTagPanel {
background-color: #FFFFFF;
display: block;
min-width: 250px;
max-width: 700px;
border: 1px solid #666666;
padding-top: 0;
border-radius: 0;
}
.preloadedTagItemPanel {
background-color: #FFFFFF;
border-bottom: 1px solid #666666;
cursor: pointer;
}
.preloadedTagItemPanel:hover {
background-color: #666666;
}
.preloadedTagItemPanelActive {
background-color: #666666;
}
.preloadedTagItem {
display: inline-block;
text-decoration: none;
margin-left: 5px;
margin-right: 5px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 20px;
padding-right: 10px;
color: #666666 !important;
font-size: 11px;
}
.preloadedTagItem:hover {
background-color: #666666;
}
.preloadedTagItemActive {
background-color: #666666;
color: #FFFFFF !important;
}
.dropdown .preloadedTagItemPanel:last-child {
border-bottom: 0;
}
Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"
import form module in app.module.ts.
import { FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
ContactsComponent
],
imports: [
BrowserModule,HttpModule,FormsModule //Add here form module
],
providers: [],
bootstrap: [AppComponent]
})
In html:
<input type="text" name="last_name" [(ngModel)]="last_name" [ngModelOptions]="{standalone: true}" class="form-control">
Adding image inside table cell in HTML
Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.
How do I create a file and write to it?
Creating a sample file:
try {
File file = new File ("c:/new-file.txt");
if(file.createNewFile()) {
System.out.println("Successful created!");
}
else {
System.out.println("Failed to create!");
}
}
catch (IOException e) {
e.printStackTrace();
}
How to search all loaded scripts in Chrome Developer Tools?
Your text may be located in the networking response.There is also a search tool in the Network tab, and you may try it.
What you want to search for may stay either in DOM or in memory. If it is not in DOM, well, it may be in memory, because you have just see it in your computer screen anyway.
The text you search for may be loaded either from scripts in the initial DOM or from response in the later request.
Writing JSON object to a JSON file with fs.writeFileSync
When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify()
.
Here is a working example:
var fs = require('fs');
var originalNote = {
title: 'Meeting',
description: 'Meeting John Doe at 10:30 am'
};
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
var note = JSON.parse(noteString);
console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);
Hope it could help.
How to check if a string starts with one of several prefixes?
Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:
Set<String> dayNames = Calendar.getInstance()
.getDisplayNames(Calendar.DAY_OF_WEEK,
Calendar.SHORT,
Locale.getDefault())
.keySet();
From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.
Java associative-array
Well i also was in search of Associative array and found the List of maps as the best solution.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class testHashes {
public static void main(String args[]){
Map<String,String> myMap1 = new HashMap<String, String>();
List<Map<String , String>> myMap = new ArrayList<Map<String,String>>();
myMap1.put("URL", "Val0");
myMap1.put("CRC", "Vla1");
myMap1.put("SIZE", "Vla2");
myMap1.put("PROGRESS", "Vla2");
myMap.add(0,myMap1);
myMap.add(1,myMap1);
for (Map<String, String> map : myMap) {
System.out.println(map.get("URL"));
}
//System.out.println(myMap);
}
}
What generates the "text file busy" message in Unix?
I came across this in PHP when using fopen()
on a file and then trying to unlink()
it before using fclose()
on it.
No good:
$handle = fopen('file.txt');
// do something
unlink('file.txt');
Good:
$handle = fopen('file.txt');
// do something
fclose($handle);
unlink('file.txt');
How is VIP swapping + CNAMEs better than IP swapping + A records?
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
How do I install PHP cURL on Linux Debian?
Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version
and see the versions.
Here's what I did to get the latest curl version installed in Ubuntu:
sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
sudo apt-get update
sudo apt-get install curl
JavaScript seconds to time string with format hh:mm:ss
Non-prototype version of toHHMMSS:
function toHHMMSS(seconds) {
var sec_num = parseInt(seconds);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.
Was facing the same issue multiple times and I have 2 solutions:
Solution 1:
Add surefire plugin reference to pom.xml. Watch that you have all nodes!
In my IDEs auto import version was missing!!!
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
</plugins>
Solution 2: My IDE added wrong import to the start of the file.
IDE added
import org.junit.Test;
I had to replace it with
import org.junit.jupiter.api.Test;
Rails find_or_create_by more than one attribute?
You can do:
User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create
Or to just initialize:
User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize
Best Practice to Organize Javascript Library & CSS Folder Structure
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
How to get the file-path of the currently executing javascript code
I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.
// Get script file location
// doesn't work for older browsers
var getScriptLocation = function() {
var fileName = "fileName";
var stack = "stack";
var stackTrace = "stacktrace";
var loc = null;
var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };
try {
// Invalid code
0();
} catch (ex) {
if(fileName in ex) { // Firefox
loc = ex[fileName];
} else if(stackTrace in ex) { // Opera
ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
} else if(stack in ex) { // WebKit, Blink and IE10
ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
}
return loc;
}
};
You can see it here.
IPython/Jupyter Problems saving notebook as PDF
I am using Anaconda-Jupyter Notebook on OS: Ubuntu 16.0 for Python programming.
Install Nbconvert, Pandoc, and Tex:
Open a terminal and implement the following commands in it.
Install Nbconvert: though it's part of the Jupyter ecosystem still install it once again
$conda install nbconvert
Or
$pip install nbconvert
But I will recommend using conda instead pip if you are using anaconda
Install Pandoc: since Nbconvert uses Pandoc for converting markdown to formats other than HTML. Type following command
$sudo apt-get install pandoc
Install TeX: For converting to PDF, nbconvert uses the TeX. Type following command
$sudo apt-get install texlive-xetex
After execution of these commands, close the opened notebooks refresh the home page Or restart the kernel of the opened notebook. Now try to download notebook as a pdf :)
Note: For more details, please refer the official documentation:
https://nbconvert.readthedocs.io/en/latest/install.html
Example of Mockito's argumentCaptor
I agree with what @fge said, more over. Lets look at example.
Consider you have a method:
class A {
public void foo(OtherClass other) {
SomeData data = new SomeData("Some inner data");
other.doSomething(data);
}
}
Now if you want to check the inner data you can use the captor:
// Create a mock of the OtherClass
OtherClass other = mock(OtherClass.class);
// Run the foo method with the mock
new A().foo(other);
// Capture the argument of the doSomething function
ArgumentCaptor<SomeData> captor = ArgumentCaptor.forClass(SomeData.class);
verify(other, times(1)).doSomething(captor.capture());
// Assert the argument
SomeData actual = captor.getValue();
assertEquals("Some inner data", actual.innerData);
How to exclude file only from root folder in Git
If the above solution does not work for you, try this:
#1.1 Do NOT ignore file pattern in any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php
##########################
# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php
Sending cookies with postman
Enable intercepter in this way
Basically it is a chrome plug in. After installing the extention, you also need to make sure the extention is enabled from chrome side.
Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation:
https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps
Check if a user has scrolled to the bottom
My solution in plain js:
_x000D_
_x000D_
let el=document.getElementById('el');_x000D_
el.addEventListener('scroll', function(e) {_x000D_
if (this.scrollHeight - this.scrollTop - this.clientHeight<=0) {_x000D_
alert('Bottom');_x000D_
}_x000D_
});
_x000D_
#el{_x000D_
width:400px;_x000D_
height:100px;_x000D_
overflow-y:scroll;_x000D_
}
_x000D_
<div id="el">_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
<div>content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How do I check/uncheck all checkboxes with a button using jQuery?
This is the shortest way I've found (needs jQuery1.6+)
HTML:
<input type="checkbox" id="checkAll"/>
JS:
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.
Example-
_x000D_
_x000D_
$("#checkAll").change(function () {_x000D_
$("input:checkbox").prop('checked', $(this).prop("checked"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
_x000D_
<fieldset>_x000D_
<legend>Loads of checkboxes</legend>_x000D_
<p><label><input type="checkbox" /> Option 1</label></p>_x000D_
<p><label><input type="checkbox" /> Option 2</label></p>_x000D_
<p><label><input type="checkbox" /> Option 3</label></p>_x000D_
<p><label><input type="checkbox" /> Option 4</label></p>_x000D_
</fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_
PHP Redirect with POST data
I know this is an old question, but I have yet another alternative solution with jQuery:
var actionForm = $('<form>', {'action': 'nextpage.php', 'method': 'post'}).append($('<input>', {'name': 'action', 'value': 'delete', 'type': 'hidden'}), $('<input>', {'name': 'id', 'value': 'some_id', 'type': 'hidden'}));
actionForm.submit();
The above code uses jQuery to create a form tag, appending hidden fields as post fields, and submit it at last. The page will forward to the form target page with the POST data attached.
p.s. JavaScript & jQuery are required for this case. As suggested by the comments of the other answers, you can make use of <noscript>
tag to create a standard HTML form in case JS is disabled.
MyISAM versus InnoDB
In my experience, MyISAM was a better choice as long as you don't do DELETEs, UPDATEs, a whole lot of single INSERT, transactions, and full-text indexing. BTW, CHECK TABLE is horrible. As the table gets older in terms of the number of rows, you don't know when it will end.
How can I get last characters of a string
There is no need to use substr
method to get a single char of a string!
taking the example of Jamon Holmgren we can change substr method and simply specify the array position:
var id = "ctl03_Tabs1";
var lastChar = id[id.length - 1]; // => "1"