Open your PDF in Google Chrome. Edit the PDF as you want. Hit ctrl + p. Save as PDF to your desktop.
I simplify the code a little bit.
from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))
use OTHER OPEN memorystream:
example for lauch pdf and send pdf in MVC4 C# Controller
public void ToPdf(string uco, int idAudit)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename= Document.pdf");
Response.Buffer = true;
Response.Clear();
//get the memorystream pdf
var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.OutputStream.Flush();
}
public ActionResult ToMail(string uco, string filter, int? page, int idAudit, int? full)
{
//get the memorystream pdf
var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();
using (var stream = new MemoryStream(bytes))
using (var mailClient = new SmtpClient("**YOUR SERVER**", 25))
using (var message = new MailMessage("**SENDER**", "**RECEIVER**", "Just testing", "See attachment..."))
{
stream.Position = 0;
Attachment attach = new Attachment(stream, new System.Net.Mime.ContentType("application/pdf"));
attach.ContentDisposition.FileName = "test.pdf";
message.Attachments.Add(attach);
mailClient.Send(message);
}
ViewBag.errMsg = "Documento enviado.";
return Index(uco, filter, page, idAudit, full);
}
Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:
NameVirtualHost *:80
).Add your virtual host (~line 36):
<VirtualHost *:80>
DocumentRoot C:\Projects\transitCalculator\trunk
ServerName transitcalculator.localhost
<Directory C:\Projects\transitCalculator\trunk>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Open your hosts file (C:\Windows\System32\drivers\etc\hosts).
Add
127.0.0.1 transitcalculator.localhost #transitCalculator
to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).
Now you can access that directory by browsing to http://transitcalculator.localhost/.
Starting ~line 200 of your http.conf
file, copy everything between <Directory "C:/xampp/htdocs">
and </Directory>
(~line 232) and paste it immediately below with C:/xampp/htdocs
replaced with your desired directory (in this case C:/Projects
) to give your server the correct permissions for the new directory.
Find the <IfModule alias_module></IfModule>
section (~line 300) and add
Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
(or whatever is relevant to your desires) below the Alias
comment block, inside the module tags.
Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs"
to #DocumentRoot "C:/Projects"
(or whatever you want).
Edit ~line 203 to match your new location (in this case C:/Projects
).
Notes:
How about
^[A-Za-z]\S*
a letter followed by 0 or more non-space characters (will include all special symbols).
str1 = "test123.00";
str2 = "yes50.00";
intStr1 = str1.replace(/[A-Za-z$-]/g, "");
intStr2 = str2.replace(/[A-Za-z$-]/g, "");
total = parseInt(intStr1)+parseInt(intStr2);
alert(total);
working Jsfiddle
When you draw to a canvas
element, you are simply drawing a bitmap in immediate mode.
The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.
Therefore, to get a click event on a canvas
element (shape), you need to capture click events on the canvas
HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.
To add a click
event to your canvas
element, use...
canvas.addEventListener('click', function() { }, false);
To determine which element was clicked...
var elem = document.getElementById('myCanvas'),
elemLeft = elem.offsetLeft + elem.clientLeft,
elemTop = elem.offsetTop + elem.clientTop,
context = elem.getContext('2d'),
elements = [];
// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
// Collision detection between clicked offset and element.
elements.forEach(function(element) {
if (y > element.top && y < element.top + element.height
&& x > element.left && x < element.left + element.width) {
alert('clicked an element');
}
});
}, false);
// Add element.
elements.push({
colour: '#05EFFF',
width: 150,
height: 100,
top: 20,
left: 15
});
// Render elements.
elements.forEach(function(element) {
context.fillStyle = element.colour;
context.fillRect(element.left, element.top, element.width, element.height);
});?
This code attaches a click
event to the canvas
element, and then pushes one shape (called an element
in my code) to an elements
array. You could add as many as you wish here.
The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.
When the click
event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements
array. If so, it fires an alert()
, which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas
.
For completeness, why your attempts didn't work...
elem.onClick = alert("hello world"); // displays alert without clicking
This is assigning the return value of alert()
to the onClick
property of elem
. It is immediately invoking the alert()
.
elem.onClick = alert('hello world'); // displays alert without clicking
In JavaScript, the '
and "
are semantically identical, the lexer probably uses ['"]
for quotes.
elem.onClick = "alert('hello world!')"; // does nothing, even with clicking
You are assigning a string to the onClick
property of elem
.
elem.onClick = function() { alert('hello world!'); }; // does nothing
JavaScript is case sensitive. The onclick
property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.
elem.onClick = function() { alert("hello world!"); }; // does nothing
Again, ' === "
.
After countless attempts, I found the following quote:
If you are using My KNOX, you cannot enable USB debugging mode while the container is installed. Unfortunately, you have to root your device ... - continue reading
Furthermore make sure:
I switched to another device without KNOX (not rooted as well) to save time. Maybe this quote will save someone some time. It was the only explanation to me in this case.
Cheers!
Download the source .less
files and make the .border-radius()
mixin blank.
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
Simply add this to your java module's build.gradle. It will include dependent libraries in archive.
mainClassName = "com.company.application.Main"
jar {
manifest {
attributes "Main-Class": "$mainClassName"
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
This will result in [module_name]/build/libs/[module_name].jar file.
Please give a try:
\Q and \E as anchors
Put an Or condition to match either a full word or regex.
Ref Link : How to match a whole word that includes special characters in regex
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
If you want "physical" access, we're developing this API that will eventually allows you to communicate with storage devices. It's open source and you can see the current code for some information. Check back for more features: https://github.com/virtium/vtStor
My favoured technique:
signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;
I usually extend this with a finished
signal to allow me to stop the clock:
clk <= not clk after half_period when finished /= '1' else '0';
Gotcha alert:
Care needs to be taken if you calculate half_period
from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2
comes out to be 2 ns
so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)
Here is a solution using dplyr >= 0.5
.
library(dplyr)
set.seed(123)
df <- data.frame(
x = sample(0:1, 10, replace = T),
y = sample(0:1, 10, replace = T),
z = 1:10
)
> df %>% distinct(x, y, .keep_all = TRUE)
x y z
1 0 1 1
2 1 0 2
3 1 1 4
(adapted from Duggu)
public static Date addOneMonth(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
return cal.getTime();
}
I have a better solution that you should add a UIButton into section header and set this button's size equal to section size, but make it hidden by clear background color, after that you are easily to check which section is clicked to expand or collapse
From a quick google search it seems that the problem is a file or url couldn't be found be the HTTPservice.
Here are the links where I found this information:
http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/
I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.
In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.
Right-click the domain when it appears under the Sites list, and choose Edit Permissions
Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS
is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.
Click the Edit button, then Add...
In the text box, type IIS AppPool\MyApplicationPoolName
, substituting MyApplicationPoolName
with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com
Press the Check Names button. The text you typed will transform (notice the underline):
Press OK to add the user
With the new user (your domain) selected, now you can safely provide any Modify or Write permissions
I agree with Ken's answer as being the most dynamic and I like to take it a step further. If it's a function that you call multiple times with different arguments - I use Ken's design but then add default values:
function load(context) {
var defaults = {
parameter1: defaultValue1,
parameter2: defaultValue2,
...
};
var context = extend(defaults, context);
// do stuff
}
This way, if you have many parameters but don't necessarily need to set them with each call to the function, you can simply specify the non-defaults. For the extend method, you can use jQuery's extend method ($.extend()
), craft your own or use the following:
function extend() {
for (var i = 1; i < arguments.length; i++)
for (var key in arguments[i])
if (arguments[i].hasOwnProperty(key))
arguments[0][key] = arguments[i][key];
return arguments[0];
}
This will merge the context object with the defaults and fill in any undefined values in your object with the defaults.
Use USE
. This will enable you to select the database.
USE photogallery;
You can also specify the database you want when connecting:
$ mysql -u user -p photogallery
Unless you're really worried about older browsers, you could just use the new html5 placeholder
attribute like so:
<input type="text" name="email" placeholder="Email address" class="input" />
Your for loop is not right, if you need the index in the for loop use:
for index, item in enumerate(emails):
# whatever (but you can't remove element while iterating)
In your case, Bogdan solution is ok, but your data structure choice is not so good. Having to maintain these two lists with data from one related to data from the other at same index is clumsy.
A list of tupple (email, otherdata) may be better, or a dict with email as key.
Think about it as array of array.
If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n
For this your declaration looks like
String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];
etc..
try this:
return $this->db->query("
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
")->result_array();
Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html see Standard Query With Multiple Results (Array Version) section
Thanks to your comments. I've made a function that give an error message when it happens:
/**
* Replaces a string in a file
*
* @param string $FilePath
* @param string $OldText text to be replaced
* @param string $NewText new text
* @return array $Result status (success | error) & message (file exist, file permissions)
*/
function replace_in_file($FilePath, $OldText, $NewText)
{
$Result = array('status' => 'error', 'message' => '');
if(file_exists($FilePath)===TRUE)
{
if(is_writeable($FilePath))
{
try
{
$FileContent = file_get_contents($FilePath);
$FileContent = str_replace($OldText, $NewText, $FileContent);
if(file_put_contents($FilePath, $FileContent) > 0)
{
$Result["status"] = 'success';
}
else
{
$Result["message"] = 'Error while writing file';
}
}
catch(Exception $e)
{
$Result["message"] = 'Error : '.$e;
}
}
else
{
$Result["message"] = 'File '.$FilePath.' is not writable !';
}
}
else
{
$Result["message"] = 'File '.$FilePath.' does not exist !';
}
return $Result;
}
I recommend this solution :
Don't use response.End();
Declare this global var : bool isFileDownLoad;
Just after your (response.Write(sw.ToString());) set ==> isFileDownLoad = true;
Override your Render like :
/// AEG : Very important to handle the thread aborted exception
override protected void Render(HtmlTextWriter w)
{
if (!isFileDownLoad) base.Render(w);
}
In JavaScript, null
is an object. There's another value for things that don't exist, undefined
. The DOM returns null
for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined
is the value used.
Second, no, there is not a direct equivalent. If you really want to check for specifically for null
, do:
if (yourvar === null) // Does not execute if yourvar is `undefined`
If you want to check if a variable exists, that can only be done with try
/catch
, since typeof
will treat an undeclared variable and a variable declared with the value of undefined
as equivalent.
But, to check if a variable is declared and is not undefined
:
if (yourvar !== undefined) // Any scope
Previously, it was necessary to use the typeof
operator to check for undefined safely, because it was possible to reassign undefined
just like a variable. The old way looked like this:
if (typeof yourvar !== 'undefined') // Any scope
The issue of undefined
being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use ===
and !==
to test for undefined
without using typeof
as undefined
has been read-only for some time.
If you want to know if a member exists independent but don't care what its value is:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
If you want to to know whether a variable is truthy:
if (yourvar)
Based on muhuk answer I did this simple tag encapsulating python string.format
method.
templatetags
at your's application folder. format.py
file on it.Add this to it:
from django import template
register = template.Library()
@register.filter(name='format')
def format(value, fmt):
return fmt.format(value)
{% load format %}
{{ some_value|format:"{:0.2f}" }}
Using a text editor, check for ^M
(control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line.
sed -i 's|^M||g' ips.txt
sed -i 's|$|:80|g' ips.txt
The above answers will position the inner element at the top of the overflow element even if it's in view inside the overflow element. I didn't want that so I modified it to not change the scroll position if the element is in view.
jQuery.fn.scrollTo = function(elem, speed) {
var $this = jQuery(this);
var $this_top = $this.offset().top;
var $this_bottom = $this_top + $this.height();
var $elem = jQuery(elem);
var $elem_top = $elem.offset().top;
var $elem_bottom = $elem_top + $elem.height();
if ($elem_top > $this_top && $elem_bottom < $this_bottom) {
// in view so don't do anything
return;
}
var new_scroll_top;
if ($elem_top < $this_top) {
new_scroll_top = {scrollTop: $this.scrollTop() - $this_top + $elem_top};
} else {
new_scroll_top = {scrollTop: $elem_bottom - $this_bottom + $this.scrollTop()};
}
$this.animate(new_scroll_top, speed === undefined ? 100 : speed);
return this;
};
It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4
These arguments are passed to the program as an array of strings.
string[] args
// Array of Strings containing arguments.
@dibrovsd: Solution will not work if the xml have more than one tag with same name
On your line of thought, I have modified the code a bit and written it for general node instead of root:
from collections import defaultdict
def xml2dict(node):
d, count = defaultdict(list), 1
for i in node:
d[i.tag + "_" + str(count)]['text'] = i.findtext('.')[0]
d[i.tag + "_" + str(count)]['attrib'] = i.attrib # attrib gives the list
d[i.tag + "_" + str(count)]['children'] = xml2dict(i) # it gives dict
return d
Actually, all the other answers have flaws. The most reliable way is:
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
Detailed Explanation:
Using "%1"=="-b"
will flat out crash if passing argument with spaces and quotes. This is the least reliable method.
IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "a b"
b""=="-b" was unexpected at this time.
Using [%1]==[-b]
is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.
IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat "-b"
(does not match, and jumps to UNKNOWN instead of SPECIFIC)
Using "%~1"=="-b"
is the most reliable. %~1
will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.
IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)
C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"
(all of the above tests work correctly)
You can either use (on the h4 elements, as they are block by default)
display: inline-block;
Or you can float the elements to the left/rght
float: left;
Just don't forget to clear the floats after
clear: left;
More visual example for the float left/right option as shared below by @VSB:
<h4> _x000D_
<div style="float:left;">Left Text</div>_x000D_
<div style="float:right;">Right Text</div>_x000D_
<div style="clear: left;"/>_x000D_
</h4>
_x000D_
That's:
SELECT * FROM Header
WHERE (userID LIKE '%''%')
you can use the identity
log[a]x
log[b]x = ---------
log[a]b
so this would be applicable for log2.
log[10]x
log[2]x = ----------
log[10]2
just plug this into the java Math log10 method....
Create an array of size 100. If you need the List interface, then call Arrays.asList on it. It'll return a fixed-size list backed by the array.
I do it on the server side, at the begining of my init file, works like a charm and you don't have to do anything in angular or existing php code:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
$_POST = json_decode(file_get_contents('php://input'), true);
The problem is that you are using a lower case v.
You need to set it to Value and it should fix your issue:
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
Hi Actually this is my same question but I didn't get anything.Now I got mobile number and his email-Id from particular Android real device(Android Mobile).Now a days 90% people using what's App application on Android Mobile.And now I am getting Mobile no and email-ID Through this What's app API.Its very simple to use see this below code.
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
for (Account ac : accounts)
{
acname = ac.name;
if (acname.startsWith("91")) {
mobile_no = acname;
}else if(acname.endsWith("@gmail.com")||acname.endsWith("@yahoo.com")||acname.endsWith("@hotmail.com")){
email = acname;
}
// Take your time to look at all available accounts
Log.i("Accounts : ", "Accounts : " + acname);
}
and import this API
import android.accounts.Account;
import android.accounts.AccountManager;
Try this:
^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$
This regular expression works for me perfectly.
function myFunction() {
var str = "c1TTTTaTTT@";
var patt = new RegExp("^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[a-zA-Z0-9@#$%^&+=]*$");
var res = patt.test(str);
console.log("Is regular matches:", res);
}
That depends. If that definition is global (outside any function) then num
will be initialized to zero. If it's local (inside a function) then its value is indeterminate. In theory, even attempting to read the value has undefined behavior -- C allows for the possibility of bits that don't contribute to the value, but have to be set in specific ways for you to even get defined results from reading the variable.
following command will download pyyaml
, which also includes yaml
pip install pyYaml
Modern answer (only relevant after Mercurial 2.1):
Use Phases and mark the revision(s) that you don't want to share as secret (private). That way when you push they won't get sent.
In TortoiseHG you can right click on a commit to change its phase.
Also: You can also use the extension "rebase" to move your local commits to the head of the shared repository after you pull.
Maybe this will help.
var inputVal = $(this).closest('tr').find("td:eq(x) input").val();
\w
matches a word character. \b
is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)
\w
matches a
, b
, c
, d
, e
, and f
in "abc def"
\b
matches the (zero-width) position before a
, after c
, before d
, and after f
in "abc def"
var x = $('#container').get(0).outerHTML;
UPDATE : This is now supported by Firefox as of FireFox 11 (March 2012)
As others have pointed out, this will not work in FireFox. If you need it to work in FireFox, then you might want to take a look at the answer to this question : In jQuery, are there any function that similar to html() or text() but return the whole content of matched component?
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button
Simplest Answer is "No Direct method of getting it because there is no pre-compiler"
But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class
My bad, in trying to simplify it, I went too far, actually stuffs
is a record of all kinds of info, I just want the id in it.
stuffs = [[123, first, last], [456, first, last]]
I want my_sting
to be
my_sting = '123, 456'
My original code should have looked like this:
{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}
Thinking about it, stuffs
is probably a dictionary, but you get the gist.
Yes I found the join
filter, and was going to approach it like this:
{% set my_string = [] %}
{% for stuff in stuffs %}
{% do my_string.append(stuff.id) %}
{% endfor%}
{% my_string|join(', ') %}
But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.
process.on('warning', function(e) {
'use strict';
console.warn(e.stack);
});
process.on('uncaughtException', function(e) {
'use strict';
console.warn(e.stack);
});
add this lines to at the starting point of your file
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
key = "".join( chr( val ) for val in myList )
I think the most significant problem is that you're incrementing code
as you read stuff in, and then returning the final value of code
, i.e. you'll be returning a pointer to the end of the string. You probably want to make a copy of code
before the loop, and return that instead.
Also, C strings need to be null-terminated. You need to make sure that you place a '\0'
directly after the final character that you read in.
Note: You could just use fgets()
to get the entire line in one hit.
I suspect wpis.entry.lastChangeDate
has been somehow transformed into a string in the view, before arriving to the template.
In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper
, and then see if the template crashes.
You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.
On an unrelated notice, why don't you use models.DateTimeField(
auto_now_add
=True)
to set the datetime on creation?
This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find()
and matches()
methods. find()
succeeds if a match can be found anywhere in the target string, while matches()
expects the regex to match the entire string.
Pattern p = Pattern.compile("xyz");
Matcher m = p.matcher("123xyzabc");
System.out.println(m.find()); // true
System.out.println(m.matches()); // false
Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true
Furthermore, MULTILINE
doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^
and $
.
Normally ^
matches the very beginning of the target string, and $
matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^
and $
to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.
So forget about what MULTILINE
means and just remember what it does: changes the behavior of the ^
and $
anchors. DOTALL
mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.
In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.
The inflect package can do this.
https://pypi.python.org/pypi/inflect
$ pip install inflect
and then:
>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine
I had a similar problem. As you increase the line-height the space above the text increases. It's not padding but it will affect the vertical space between content. I found that adding a -ve top margin seemed to do the trick. It had to be done for all of the different instances of line-height and it varies with font-family too. Maybe this is something which designers need to be more aware of when passing design requirements (?) So for a particular instance of font-family and line-height:
h1 {
font-family: 'Garamond Premier Pro Regular';
font-size: 24px;
color: #001230;
line-height: 29px;
margin-top: -5px; /* CORRECTION FOR LINE-HEIGHT */
}
I find marking the property
as readonly
cleaner than the above answers. I believe vb14 is required.
Private _Name As String
Public ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property
This can be condensed to
Public ReadOnly Property Name As String
https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396
State machines are not something that inherently needs a tutorial to be explained or even used. What I suggest is that you take a look at the data and how it needs to be parsed.
For example, I had to parse the data protocol for a Near Space balloon flight computer, it stored data on the SD card in a specific format (binary) which needed to be parsed out into a comma seperated file. Using a state machine for this makes the most sense because depending on what the next bit of information is we need to change what we are parsing.
The code is written using C++, and is available as ParseFCU. As you can see, it first detects what version we are parsing, and from there it enters two different state machines.
It enters the state machine in a known-good state, at that point we start parsing and depending on what characters we encounter we either move on to the next state, or go back to a previous state. This basically allows the code to self-adapt to the way the data is stored and whether or not certain data exists at all even.
In my example, the GPS string is not a requirement for the flight computer to log, so processing of the GPS string may be skipped over if the ending bytes for that single log write is found.
State machines are simple to write, and in general I follow the rule that it should flow. Input going through the system should flow with certain ease from state to state.
You can use IterableOf
from Cactoos:
Iterable<String> names = new IterableOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Then, you can turn it into a list using ListOf
:
List<String> names = new ListOf<>(
new IterableOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
)
);
Or simply this:
List<String> names = new ListOf<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
Here is a simple approach:
#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no [email protected]'
FILE_NAME=/home/user/file.txt
SSH_PASS='sshpass -p password-for-remote-machine'
if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
then
echo "File exists"
else
echo "File does not exist"
fi
You need to install sshpass on your machine to work it.
modify your bash profile as follows <>$vim ~/.bash_profile export PATH=/usr/local/mysql/bin:$PATH Once its saved you can type in mysql to bring mysql prompt in your terminal.
I think you are looking for text-overflow: ellipsis
in combination with white-space: nowrap
See some more details here
bar
is your static variable and you can access it using Foo.bar
.
Basically, you need to qualify your static variable with Class name.
In Swift3
For ex: a variable "Duke James Thomas", we need to get "James".
let name = "Duke James Thomas"
let range: Range<String.Index> = name.range(of:"James")!
let lastrange: Range<String.Index> = img.range(of:"Thomas")!
var middlename = name[range.lowerBound..<lstrange.lowerBound]
print (middlename)
<?php
session_start();
session_unset();
session_destroy();
header("location:home.php");
exit();
?>
You have two options.
<colspan>
in your header to stretch a cell for two or more columns.<table>
with 2 columns inside the td
you want extra columns in.well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.
The problem with all of these answers for me was they weren't responsive. I had to have a fixed height for a parent div which i didn't want. I also didn't want to spend a ton of time dinking around with media queries. If you are using angular, you can use bootstraps tabset and it will do all of the hard work for you. You'll be able to scroll the inner content and it will be responsive. When you setup the tab, do it like this: $scope.tab = { title: '', url: '', theclass: '', ative: true };
... the point is, you don't want a title or image icon. then hide the outline of the tab in cs like this:
.nav-tabs {
border-bottom:none;
}
and also this .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {border:none;}
and finally to remove the invisible tab that you can still click on if you don't implement this: .nav > li > a {padding:0px;margin:0px;}
You cannot use the add method on an array in Java.
To add things to the array do it like this
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++){
int neki = Integer.parseInt(s);
num[i] = neki;
}
If you really want to use an add() method, then consider using an ArrayList<Integer>
instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.
ArrayList Example
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<Integer>();
for (String s : args){
Integer neki = new Integer(Integer.parseInt(s));
num.add(s);
}
Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
If you want to read the file abc.txt
, you can write the code as:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Now txt
contains the contents of the file abc.txt.
When I enter on a page that haves this code:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
This error occurs: Error. An error occurred while processing your request.
And this exception are recorded on my logs:
System.Web.HttpException (0x80004005): The controller for path '/bundles/jqueryval' was not found or does not implement IController.
em System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
...
I have tried all tips on this page and none of them solved for me. So I have looked on my Packages folder and noticed that I have two versions for System.Web.Optmization.dll:
My project was referencing to the older beta version. I only changed the reference to the newer version (69KB) and eveything worked fine.
I think it might help someone.
This can also be caused if you include bootstrap.js
before jquery.js
.
Others might have the same problem I did.
Include jQuery
before bootstrap
.
adapter.remove(arraylist.get(position));
adapter.notifyDataSetChanged();
or you can call again
setListAdapter(adapter)
This is something that is done by Django itself when building a form from a model. It is using the _meta attribute, but as Bernhard noted, it uses both _meta.fields and _meta.many_to_many. Looking at django.forms.models.fields_for_model, this is how you could do it:
opts = model._meta
for f in sorted(opts.fields + opts.many_to_many):
print '%s: %s' % (f.name, f)
You can try the Boost Tokenizer library, in particular the Escaped List Separator
This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :
ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...
maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.
To write inline styling use:
<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>
Inline styling serves a purpose however, it is not recommended in most situations.
The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.
if you have the file structure:
index.html
>>/css/
>>/css/styles.css
Then in your HTML document between <head>
and </head>
write:
<link href="css/styles.css" rel="stylesheet" />
Then, change your div structure to be:
<div id="someidname" class="someclassname">
asdfashdjkfhaskjdf
</div>
In css, you can reference your div from the ID or the CLASS.
To do so write:
.someclassname { height: 100px; }
OR
#someidname { height: 100px; }
Note that if you do both, the one that comes further down the file structure will be the one that actually works.
For example... If you have:
.someclassname { height: 100px; }
.someclassname { height: 150px; }
Then in this situation the height will be 150px.
EDIT:
To answer your secondary question from your edit, probably need overflow: hidden;
or overflow: visible;
. You could also do this:
<div class="span12">
<div style="height:100px;">
asdfashdjkfhaskjdf
</div>
</div>
In C# you can use the following to replace the single quote with a double quote:
string sample = "St. Mary's";
string escapedSample = sample.Replace("'", "''");
And the output will be:
"St. Mary''s"
And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:
private static string MySqlEscape(Object usString)
{
if (usString is DBNull)
{
return "";
}
string sample = Convert.ToString(usString);
return sample.Replace("'", "''");
}
The solution (http://expressjs.com/en/starter/static-files.html).
once done this the image folder no longer shalt put it. only be
background-image: url ( "/ image.png");
carpera that the image is already in the static files
I had very similar situation (had a project on another machine and cloned it to my laptop and saw the same issue) and I looked in it.
Error message was coming from Sdk.groovy
of Android gradle plugin:
https://android.googlesource.com/platform/tools/build/+/master/gradle/src/main/groovy/com/android/build/gradle/internal/Sdk.groovy
By looking at code, its findLocation
needs to set androidSdkDir
variable and there are only three ways to do it:
local.properties
file and have either sdk.dir
or android.dir
line.ANDROID_HOME
environment variable defined.While your Android Studio knows that the SDK is at that place, I doubt that Android Studio is passing that information to gradle and thus we're seeing that error.
I created local.properties
file at the project root and put the following line and it compiled the code successfully.
sdk.dir = /Applications/Android Studio.app/sdk/
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
I did not like the Javascript Solution I saw above. Here is the one I build using partial applying, closures and recursion:
Ok, I was mainly concern about, if the combinations array could satisfy the target requirement, hopefully this approached you will start to find the rest of combinations
Here just set the target and pass the combinations array.
function main() {
const target = 10
const getPermutationThatSumT = setTarget(target)
const permutation = getPermutationThatSumT([1, 4, 2, 5, 6, 7])
console.log( permutation );
}
the currently implementation I came up with
function setTarget(target) {
let partial = [];
return function permute(input) {
let i, removed;
for (i = 0; i < input.length; i++) {
removed = input.splice(i, 1)[0];
partial.push(removed);
const sum = partial.reduce((a, b) => a + b)
if (sum === target) return partial.slice()
if (sum < target) permute(input)
input.splice(i, 0, removed);
partial.pop();
}
return null
};
}
mysqld --help --verbose will find only location of default configuration file. What if you use 2 MySQL instances on the same server? It's not going to help.
Good article about figuring it out:
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
As workmad3 says, you need the jar file to be in your classpath. If you're compiling from the commandline, that will mean using the -classpath flag. (Avoid the CLASSPATH environment variable; it's a pain in the neck IMO.)
If you're using an IDE, please let us know which one and we can help you with the steps specific to that IDE.
If your data is base64 encoded.
if ( dataObj != nil ) {
let encryptedDataText = dataObj!.base64EncodedString(options: NSData.Base64EncodingOptions())
NSLog("Encrypted with pubkey: %@", encryptedDataText)
}
First of let's your image name is myimage. So what you have to do is that go to Drawable and save the image name myimage.
Now assume you know only image name and you need to access it. Use below snippet to access it,
what you did is correct , ensure you saved image name you are going to use inside coding.
public static int getResourceId(Context context, String name, String resourceType) {
return context.getResources().getIdentifier(toResourceString(name), resourceType, context.getPackageName());
}
private static String toResourceString(String name) {
return name.replace("(", "")
.replace(")", "")
.replace(" ", "_")
.replace("-", "_")
.replace("'", "")
.replace("&", "")
.toLowerCase();
}
In addition to it you should ensure that there is no empty spaces and case sensitives
foreach
:
foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
Alternatively, because it is a List<T>
.. which implements an indexer method []
, you can use a normal for
loop as well.. although its less readble (IMO):
for (var i = 0; i < myMoney.Count; i++) {
Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.
You can just use the attribute selector and then test the length:
$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0 // --> not ok
In addition to what TaskManager shows, if you use ProcessExplorer from Sysinternals, you can tell when you right-click on the process name and select Properties. In the Image tab, there is a field toward the bottom that says Image. It says 32-bit for a 32 bit application and 64 bit for the 64 bit application.
You're getting HTTP 415 "The request entity's media type 'multipart/form-data' is not supported for this resource." because you haven't mention the correct content type in your request.
Why not use globalize? This is only one of the issues that you can run in to when you don't use the english language:
Globalize.parseFloat('0,04'); // 0.04
Some links on stackoverflow to look into:
There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.
With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.
Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s
br {
content: "";
margin: 2em;
display: block;
margin-bottom: -20px;
}
Works in Firefox, Chrome & Safari. Haven't tested in Explorer. (Windows-tablet is out of power.)
Line-breaks, font-size works differently in Firefox & Safari.
Try this:
if(myString != "-1")
The opperand is !=
and not =!
You can also use Equals
if(!myString.Equals("-1"))
Note the !
before myString
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
You could use a function similar to:
function redirect($url) {
ob_start();
header('Location: '.$url);
ob_end_flush();
die();
}
Worth noting, you should always use either ob_flush()
or ob_start()
at the beginning of your header('location: ...');
functions, and you should always follow them with a die()
or exit()
function to prevent further code execution.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die()
/ exit()
functions in your redirects, as well as when to use ob_flush()
vs ob_start()
, and some potential errors that the others answers have left out at this point.
var stringDate = "Sunday, February 28, 2010";
var months = ["January", "February", "March"]; // You add the rest :-)
var m = /(\w+) (\d+), (\d+)/.exec(stringDate);
var date = new Date(+m[3], months.indexOf(m[1]), +m[2]);
The indexOf
method on arrays is only supported on newer browsers (i.e. not IE). You'll need to do the searching yourself or use one of the many libraries that provide the same functionality.
Also the code is lacking any error checking which should be added. (String not matching the regular expression, non existent months, etc.)
The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';
Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.
I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.
I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.
In iOS 6.0 and above, things have changed with the new dequeueReusableHeaderFooterViewWithIdentifier
API.
I have written a guide (tested on iOS 9), which can be summarised as such:
UITableViewHeaderFooterView
viewDidLoad
viewForHeaderInSection
and use dequeueReusableHeaderFooterViewWithIdentifier
to get back the header/footerin my case, I must to set path in properties file, in many hours I find the way:
webdriver.gecko.driver="/lib/geckodriver-v0.26.0-win64/geckodriver.exe"
in java code:
private static final Logger log = Logger.getLogger(Login.class.getName());
private FirefoxDriver driver;
private FirefoxProfile firefoxProfile;
private final String BASE_URL = "https://www.myweb.com/";
private static final String RESOURCE_NAME = "main/resources/application.properties"; // could also be a constant
private Properties properties;
public Login() {
init();
}
private void init() {
properties = new Properties();
try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
properties.load(resourceStream);
} catch (IOException e) {
System.err.println("Could not open Config file");
log.log(Level.SEVERE, "Could not open Config file", e);
}
// open incognito tab by default
firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
// geckodriver driver path to run
String gekoDriverPath = properties.getProperty("webdriver.gecko.driver");
log.log(Level.INFO, gekoDriverPath);
System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + gekoDriverPath);
log.log(Level.INFO, System.getProperty("webdriver.gecko.driver"));
System.setProperty("webdriver.gecko.driver", System.getProperty("webdriver.gecko.driver").replace("\"", ""));
if (driver == null) {
driver = new FirefoxDriver();
}
}
I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.
I "fixed" the problem by adding another line:
plt.plot([],[])
The entire code snippet becomes:
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
# plot
plt.plot([],[])
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.show()
plt.close()
This produces an image with the bubbles distributed as desired.
I would like to add to the answer provided by Sangam Belose. Here's his code:
select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM sensor
However, if you have not set up your "secure_file_priv"
within the variables, it may not work. For that, check the folder set on that variable by:
SHOW VARIABLES LIKE "secure_file_priv"
The output should look like this:
mysql> show variables like "%secure_file_priv%";
+------------------+------------------------------------------------+
| Variable_name | Value |
+------------------+------------------------------------------------+
| secure_file_priv | C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ |
+------------------+------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
You can either change this variable or change the query to output the file to the default path showing.
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
Consider if your file is read only, then the extra parameters may help with FileStream
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
Well, I was suffering with this Issue but finally I found the solution.
Problem Starts Here: ["Install missing platform(s) and sync project" (link) doesn't work & gradle sync failed]
Problem Source: Just check out the app -> src-build.gradle
and you will find the parameters
compileSdkVersion 25
buildToolsVersion "25.0.1"
targetSdkVersion 25
Note: You might find these parameters with different values e.g
compileSdkVersion 23
etc.
These above parameters in build.gradle
creates error because their values are not compatible with your current SDK version.
The solution to This error is simple, just open a new project in your Android Studio, In that new project goto app -> src-build.gradle
.
In build.gradle
file of new project find these parameters:
In my case these are:
compileSdkVersion "26"
buildToolsVersion "26.0.1"
targetSdkVersion 26
Now copy these parameters from your new project build.gradle
file and post them in the same file of the other project(having Error).
I believe this is the simplest example:
header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
You can also add a header for Access-Control-Max-Age
and of course you can allow any headers and methods that you wish.
Finally you want to respond to the initial request:
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.
Old Middleware Recommendation below: Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.
I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...
git add <your different stuff>
git commit --amend --author="author name <[email protected]>"-m "new message"
Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.
The question now referes to Starting a shell in the Docker Alpine container which implies using sh
or ash
or /bin/sh
or /bin/ash/
.
Based on the OP's question:
docker run image sh -c "cd /path/to/somewhere && python a.py"
Code coverage basically tells you how much of your code is covered under tests. For example, if you have 90% code coverage, it means 10% of the code is not covered under tests.
I know you might be thinking that if 90% of the code is covered, it's good enough, but you have to look from a different angle. What is stopping you from getting 100% code coverage?
A good example will be this:
if(customer.IsOldCustomer())
{
}
else
{
}
Now, in the code above, there are two paths/branches. If you are always hitting the "YES" branch, you are not covering the "else" part and it will be shown in the Code Coverage results. This is good because now you know that what is not covered and you can write a test to cover the "else" part. If there was no code coverage, you are just sitting on a time bomb, waiting to explode.
NCover is a good tool to measure code coverage.
You might want to consider NULL values as well. In your example, if the column notes has a null value, then the resulting value will be NULL. If you want the null values to behave as empty strings (so that the answer comes out 'SomeText'), then use the IsNull function:
Select IsNull(Cast(notes as nvarchar(4000)),'') + 'SomeText' From NotesTable a
For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
#!/usr/bin/env python
import inspect
called=lambda: inspect.stack()[1][3]
def caller1():
print "inside: ",called()
def caller2():
print "inside: ",called()
if __name__=='__main__':
caller1()
caller2()
shahid@shahid-VirtualBox:~/Documents$ python test_func.py
inside: caller1
inside: caller2
shahid@shahid-VirtualBox:~/Documents$
update addresses set cid=id where id in (select id from customers)
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
simplest way is to use from
CardView and its card:cardCornerRadius
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/cardlist_item"
android:layout_width="match_parent"
android:layout_height="130dp"
card:cardCornerRadius="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="@color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="12sp"
android:orientation="vertical"
android:weightSum="1">
</RelativeLayout>
</android.support.v7.widget.CardView>
And when you are creating your Dialog
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Just incase this helps anyone else also, I was signed into the mac app, command line working fine, but because I then turned on 2FA, my commands were returning the error. I had to sign out of the app, then I could use my Personal access token in my commands as per ele's answer here.
Hopefully that helps someone!
You need to convert the column into a 'TemplateField'.
In Designer View, click the smart tag of the GridView, select-> 'Edit columns'. Select your column you wish to modify and press the hyperlink converting it to a template. See screenshot: Converting column to template.
Note: Modifying your datasource might regenerate the columns again, so it might make changes to your template columns.
Just an update to the 'no exceptions on resources' problem as pointed to by @jarmod (do please feel free to update your answer if below seems applicable)
I have tested the below code and it runs fine. It uses 'resources' for doing things, but catches the client.exceptions
- although it 'looks' somewhat wrong... it tests good, the exception classes are showing and matching when looked into using debugger at exception time...
It may not be applicable to all resources and clients, but works for data folders (aka s3 buckets).
lab_session = boto3.Session()
c = lab_session.client('s3') #this client is only for exception catching
try:
b = s3.Bucket(bucket)
b.delete()
except c.exceptions.NoSuchBucket as e:
#ignoring no such bucket exceptions
logger.debug("Failed deleting bucket. Continuing. {}".format(e))
except Exception as e:
#logging all the others as warning
logger.warning("Failed deleting bucket. Continuing. {}".format(e))
Hope this helps...
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()
For your new question, not much harder either, just need to find the bar from your axis, an example:
>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>,
<matplotlib.axis.YAxis object at 0x78460d0>,
<matplotlib.patches.Rectangle object at 0x733cc50>,
<matplotlib.patches.Rectangle object at 0x733cdd0>,
<matplotlib.patches.Rectangle object at 0x777f290>,
<matplotlib.patches.Rectangle object at 0x777f710>,
<matplotlib.text.Text object at 0x7836450>,
<matplotlib.patches.Rectangle object at 0x7836390>,
<matplotlib.spines.Spine object at 0x6529950>,
<matplotlib.spines.Spine object at 0x69aef50>,
<matplotlib.spines.Spine object at 0x69ae310>,
<matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r')
#You can also try to locate the first patches.Rectangle object
#instead of direct calling the index.
If you have a complex plot and want to identify the bars first, add those:
>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>,
<matplotlib.patches.Rectangle object at 0x3103810>,
<matplotlib.patches.Rectangle object at 0x3129850>,
<matplotlib.patches.Rectangle object at 0x3129cd0>,
<matplotlib.patches.Rectangle object at 0x3112ad0>]
Try this:
$("#datepicker").datepicker({ minDate: 0 });
Remove the quotes from 0
.
You might find it useful to extend the Storage object with these handy methods:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
return JSON.parse(this.getItem(key));
}
This way you get the functionality that you really wanted even though underneath the API only supports strings.
There is no correct answer, since it depends on what the definition of "syntax" is for your request. The most important thing is that you:
Before everyone jumps all over me for saying that there is no right or wrong answer here, let me explain a bit about how I came to the conclusion.
In this specific example, the OP's question is about a JSON request that contains a different key than expected. Now, the key name received is very similar, from a natural language standpoint, to the expected key, but it is, strictly, different, and hence not (usually) recognized by a machine as being equivalent.
As I said above, the deciding factor is what is meant by syntax. If the request was sent with a Content Type of application/json
, then yes, the request is syntactically valid because it's valid JSON syntax, but not semantically valid, since it doesn't match what's expected. (assuming a strict definition of what makes the request in question semantically valid or not).
If, on the other hand, the request was sent with a more specific custom Content Type like application/vnd.mycorp.mydatatype+json
that, perhaps, specifies exactly what fields are expected, then I would say that the request could easily be syntactically invalid, hence the 400 response.
In the case in question, since the key was wrong, not the value, there was a syntax error if there was a specification for what valid keys are. If there was no specification for valid keys, or the error was with a value, then it would be a semantic error.
Also: Python: How to get PID by process name?
Adaptation to previous posted answers.
def getpid(process_name):
import os
return [item.split()[1] for item in os.popen('tasklist').read().splitlines()[4:] if process_name in item.split()]
getpid('cmd.exe')
['6560', '3244', '9024', '4828']
In my case, I just needed to install oracle 10g client on the server, becase there there was the 11g version.
Ps: I don't needed unistall nothing, I just install the 10g version and updated the tnsnames file (C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN)
With Xcode 9 - Simulator, you can pick & drag any corner of simulator to resize it and set according to your requirement.
Look at this snapshot.
Note: With Xcode 9.1+, Simulator scale options are changed.
Keyboard short-keys:
According to Xcode 9.1+
Physical Size ? 1 command + 1
Pixel Accurate ? 2 command + 2
According to Xcode 9
50% Scale ? 1 command + 1
100% Scale ? 2 command + 2
200% Scale ? 3 command + 3
Simulator scale options from Xcode Menu:
Xcode 9.1+:
Menubar ? Window ? "Here, options available change simulator scale" (Physical Size & Pixel Accurate)
Pixel Accurate: Resizes your simulator to actual (Physical) device's pixels, if your mac system display screen size (pixel) supports that much high resolution, else this option will remain disabled.
Tip: rotate simulator ( ? + ? or ? + ? ), if Pixel Accurate is disabled. It may be enabled (if it fits to screen) in landscape.
Xcode 9.0
Menubar ? Window ? Scale ? "Here, options available change simulator scale"
Tip: How do you get screen shot with 100% (a scale with actual device size) that can be uploaded on AppStore?
Disable 'Optimize Rendering for Window scale' from Debug
menu, before you take a screen shot (See here: How to take screenshots in the iOS simulator)
There is an option
Menubar ? Debug ? Disable "Optimize Rendering for Window scale"
Here is Apple's document: Resize a simulator window
here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* @author TIAGO.MEDICI
*
*/
public class JsonUtils {
public static boolean isJSONValid(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringWriter sw = new StringWriter();
objMapper.writeValue(sw, object);
return sw.toString();
}
public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
if (indent == true) {
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
StringWriter stringWriter = new StringWriter();
objMapper.writeValue(stringWriter, object);
return stringWriter.toString();
}
public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper objMapper = new ObjectMapper();
obj = objMapper.readValue(content, clazz);
return obj;
}
@SuppressWarnings("rawtypes")
public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(content, new TypeReference<List>() {
});
return obj;
}
public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
return obj;
}
Inside container(in docker, not in VM), by default these are not installed. Even apt-get, wget will not work. My VM is running on Ubuntu 17.10. For me yum package manaager worked.
Yum is not part of debian or ubuntu. It is part of red-hat. But, it works in Ubuntu and it is installed by default like apt-get
Tu install vim, use this command
yum install -y vim-enhanced
To uninstall vim :
yum uninstall -y vim-enhanced
Similarly,
yum install -y wget
yum install -y sudo
-y is for assuming yes if prompted for any qustion asked after doing yum install packagename
I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.
HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:
<div id="wrapper">
<div id="scroller">
... my scrollable content
</div>
</div>
CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).
.touch #wrapper {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: hidden;
}
.touch #scroller {
position: absolute;
z-index: 1;
width: 100%;
}
JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.
# coffeescript
if Modernizr.touch
myScroller = new IScroll('#wrapper', probeType: 3)
myScroller.on 'scroll', updatePosition
myScroller.on 'scrollEnd', updatePosition
You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)
function getScroll(elem, iscroll) {
var x, y;
if (Modernizr.touch && iscroll) {
x = iscroll.x * -1;
y = iscroll.y * -1;
} else {
x = elem.scrollTop;
y = elem.scrollLeft;
}
return {x: x, y: y};
}
The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.
EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.
Two of them always produce the same answer:
COUNT(*)
counts the number of rowsCOUNT(1)
also counts the number of rowsAssuming the pk
is a primary key and that no nulls are allowed in the values, then
COUNT(pk)
also counts the number of rowsHowever, if pk
is not constrained to be not null, then it produces a different answer:
COUNT(possibly_null)
counts the number of rows with non-null values in the column possibly_null
.
COUNT(DISTINCT pk)
also counts the number of rows (because a primary key does not allow duplicates).
COUNT(DISTINCT possibly_null_or_dup)
counts the number of distinct non-null values in the column possibly_null_or_dup
.
COUNT(DISTINCT possibly_duplicated)
counts the number of distinct (necessarily non-null) values in the column possibly_duplicated
when that has the NOT NULL
clause on it.
Normally, I write COUNT(*)
; it is the original recommended notation for SQL. Similarly, with the EXISTS
clause, I normally write WHERE EXISTS(SELECT * FROM ...)
because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.
Shallow copy:
Some members of the copy may reference the same objects as the original:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(copy.pi)
{ }
};
Here, the pi
member of the original and copied X
object will both point to the same int
.
Deep copy:
All members of the original are cloned (recursively, if necessary). There are no shared objects:
class X
{
private:
int i;
int *pi;
public:
X()
: pi(new int)
{ }
X(const X& copy) // <-- copy ctor
: i(copy.i), pi(new int(*copy.pi)) // <-- note this line in particular!
{ }
};
Here, the pi
member of the original and copied X
object will point to different int
objects, but both of these have the same value.
The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.
Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.
Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:
The implicitly defined copy constructor for class
X
performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.
Use Google AJAX Feed API unless your RSS data is private. It's fast, of course.
Do you have a file called __init__.py
in the foo directory? If not then python won't recognise foo as a python package.
See the section on packages in the python tutorial for more information.
In modern browsers you can use Object.getOwnPropertyNames
to get all properties (both enumerable and non-enumerable) on an object. For instance:
function Person ( age, name ) {
this.age = age;
this.name = name;
}
Person.prototype.greet = function () {
return "My name is " + this.name;
};
Person.prototype.age = function () {
this.age = this.age + 1;
};
// ["constructor", "greet", "age"]
Object.getOwnPropertyNames( Person.prototype );
Note that this only retrieves own-properties, so it will not return properties found elsewhere on the prototype chain. That, however, doesn't appear to be your request so I will assume this approach is sufficient.
If you would only like to see enumerable properties, you can instead use Object.keys
. This would return the same collection, minus the non-enumerable constructor
property.
If you don't want duplicates in a list, use a HashSet
. That way it will be clear to anyone else reading your code what your intention was and you'll have less code to write since HashSet
already handles what you are trying to do.
It may be effective to assign to the events 'touchstart mousedown'
or 'touchend mouseup'
to avoid undesired side-effects of using click
.
I got this error because on Windows the Zend Studio Icon in the Start Menu was still pointing at the previous version of Zend Studio. Once I changed the target to the new path, the error went away.
This question is now a bit old... but I'll throw my hat into the ring.
I personally find an algorithm of the form find_paths[s, t, d, k]
useful, where:
Using your programming language's form of infinity for d
and k
will give you all paths§.
§ obviously if you are using a directed graph and you want all undirected paths between s
and t
you will have to run this both ways:
find_paths[s, t, d, k] <join> find_paths[t, s, d, k]
I personally like recursion, although it can difficult some times, anyway first lets define our helper function:
def find_paths_recursion(graph, current, goal, current_depth, max_depth, num_paths, current_path, paths_found)
current_path.append(current)
if current_depth > max_depth:
return
if current == goal:
if len(paths_found) <= number_of_paths_to_find:
paths_found.append(copy(current_path))
current_path.pop()
return
else:
for successor in graph[current]:
self.find_paths_recursion(graph, successor, goal, current_depth + 1, max_depth, num_paths, current_path, paths_found)
current_path.pop()
With that out of the way, the core function is trivial:
def find_paths[s, t, d, k]:
paths_found = [] # PASSING THIS BY REFERENCE
find_paths_recursion(s, t, 0, d, k, [], paths_found)
First, lets notice a few thing:
[]
is an uninitialized list, replace this with the equivalent for your programming language of choicepaths_found
is passed by reference. It is clear that the recursion function doesn't return anything. Handle this appropriately.graph
is assuming some form of hashed
structure. There are a plethora of ways to implement a graph. Either way, graph[vertex]
gets you a list of adjacent vertices in a directed graph - adjust accordingly.It is much faster to issue 1 query which returns 100 results than to issue 100 queries which each return 1 result.
In SQL Server you can turn on and off identity insert like this:
SET IDENTITY_INSERT table_name ON
-- run your queries here
SET IDENTITY_INSERT table_name OFF
The var
keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var
keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var
keyword has a type. For instance, you'll find that the following code outputs "String".
var myString = "";
Console.Write(myString.GetType().Name);
Furthermore, the code above is equivalent to:
String myString = "";
Console.Write(myString.GetType().Name);
The var
keyword is simply C#'s way of saying "I can figure out the type for myString
from the context, so don't worry about specifying the type."
var myVariable = (MyType)null
or MyType myVariable = null
should work because you are giving the C# compiler context to figure out what type myVariable
should will be.
For more information:
Go to file Global.asax.cs in your project and add the following code.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
Response.Cache.SetNoStore();
}
It worked for me..! Reference link Clear session on Logout MVC 4
There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.
See here for details:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
I think its already elegant way for comparing range. But, this approach cause you to write extra unit tests to satisfy all &&
cases.
So, you can use any of the below approach to avoid writing extra unit tests.
Using Java 8 Streams:
if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))
Using Math class:
if(Math.max(0, i) == Math.min(i, 100))
Personally I recommend the second approach because it won't end up creating an Array of the size equal to the range you want to check.
NOTE: This is true for the version mentioned in the question, 4.1.1.RELEASE.
Spring MVC handles a ResponseEntity
return value through HttpEntityMethodProcessor
.
When the ResponseEntity
value doesn't have a body set, as is the case in your snippet, HttpEntityMethodProcessor
tries to determine a content type for the response body from the parameterization of the ResponseEntity
return type in the signature of the @RequestMapping
handler method.
So for
public ResponseEntity<Void> taxonomyPackageExists( @PathVariable final String key ) {
that type will be Void
. HttpEntityMethodProcessor
will then loop through all its registered HttpMessageConverter
instances and find one that can write a body for a Void
type. Depending on your configuration, it may or may not find any.
If it does find any, it still needs to make sure that the corresponding body will be written with a Content-Type that matches the type(s) provided in the request's Accept
header, application/xml
in your case.
If after all these checks, no such HttpMessageConverter
exists, Spring MVC will decide that it cannot produce an acceptable response and therefore return a 406 Not Acceptable HTTP response.
With ResponseEntity<String>
, Spring will use String
as the response body and find StringHttpMessageConverter
as a handler. And since StringHttpMessageHandler
can produce content for any media type (provided in the Accept
header), it will be able to handle the application/xml
that your client is requesting.
Spring MVC has since been changed to only return 406 if the body in the ResponseEntity
is NOT null
. You won't see the behavior in the original question if you're using a more recent version of Spring MVC.
In iddy85's solution, which seems to suggest ResponseEntity<?>
, the type for the body will be inferred as Object
. If you have the correct libraries in your classpath, ie. Jackson (version > 2.5.0) and its XML extension, Spring MVC will have access to MappingJackson2XmlHttpMessageConverter
which it can use to produce application/xml
for the type Object
. Their solution only works under these conditions. Otherwise, it will fail for the same reason I've described above.
jQuery recently started using source maps.
For example, let's look at the minified jQuery 2.0.3 file's first few lines.
/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
Excerpt from Introduction to JavaScript Source Maps:
Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.
emphasis mine
It's incredibly useful, and will only download if the user opens dev tools.
Remove the source mapping line, or do nothing. It isn't really a problem.
Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.
I had the same problem in Visual Studio. You have to use:
yourClass->classMethod();
rather than:
yourClass.classMethod();
As @Mr_and_Mrs_D suggested:
String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;
Using the hyperref
package, you could also declare a new command by using \newcommand{\secref}[1]{\autoref{#1}. \nameref{#1}}
in the pre-amble. Placing \secref{section:my}
in the text generates: 1. My section.
Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.
Hope this helps to those who come searching here.
You want to use the Integer.parseInt(String) method.
try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}
Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse
It says:
Other parameters included in the response include
expires_in
andtoken_type
. These parameters describe the lifetime of the token in seconds...
longButton.setOnClickListener {
show(
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1234567890-12345678901234567890123456789012345678901234567890"
)
}
shortButton.setOnClickListener {
show(
"1234567890\n" +
"1234567890-12345678901234567890123456789012345678901234567890"
)
}
private fun show(msg: String) {
val builder = AlertDialog.Builder(this).apply {
setPositiveButton(android.R.string.ok, null)
setNegativeButton(android.R.string.cancel, null)
}
val dialog = builder.create().apply {
setMessage(msg)
}
dialog.show()
dialog.window?.decorView?.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
val displayRectangle = Rect()
val window = dialog.window
v.getWindowVisibleDisplayFrame(displayRectangle)
val maxHeight = displayRectangle.height() * 0.6f // 60%
if (v.height > maxHeight) {
window?.setLayout(window.attributes.width, maxHeight.toInt())
}
}
}
In Some cases, you need to increase the maximum execution time.
max_execution_time=30
I made it
max_execution_time=600000
then I was happy.
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
First, you need to have a clear understanding of scope
and behaviour of this
keyword in the context of scope
.
this
& scope
:
there are two types of scope in javascript. They are :
1) Global Scope
2) Function Scope
in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.this
keyword in global scope refers to the window object.this
inside function also refers to the window object.So this
will always refer to the window until we find a way to manipulate this
to indicate a context of our own choosing.
--------------------------------------------------------------------------------
- -
- Global Scope -
- ( globally "this" refers to window object) -
- -
- function outer_function(callback){ -
- -
- // outer function scope -
- // inside outer function"this" keyword refers to window object - -
- callback() // "this" inside callback also refers window object -
- } -
- -
- function callback_function(){ -
- -
- // function to be passed as callback -
- -
- // here "THIS" refers to window object also -
- -
- } -
- -
- outer_function(callback_function) -
- // invoke with callback -
--------------------------------------------------------------------------------
Different ways to manipulate this
inside callback functions:
Here I have a constructor function called Person. It has a property called name
and four method called sayNameVersion1
,sayNameVersion2
,sayNameVersion3
,sayNameVersion4
. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.
function Person(name){
this.name = name
this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}
this.sayNameVersion3 = function(callback){
callback.call(this)
}
this.sayNameVersion4 = function(callback){
callback.apply(this)
}
}
function niceCallback(){
// function to be used as callback
var parentObject = this
console.log(parentObject)
}
Now let's create an instance from person constructor and invoke different versions of sayNameVersionX
( X refers to 1,2,3,4 ) method with niceCallback
to see how many ways we can manipulate the this
inside callback to refer to the person
instance.
var p1 = new Person('zami') // create an instance of Person constructor
What bind do is to create a new function with the this
keyword set to the provided value.
sayNameVersion1
and sayNameVersion2
use bind to manipulate this
of the callback function.
this.sayNameVersion1 = function(callback){
callback.bind(this)()
}
this.sayNameVersion2 = function(callback){
callback()
}
first one bind this
with callback inside the method itself.And for the second one callback is passed with the object bound to it.
p1.sayNameVersion1(niceCallback) // pass simply the callback and bind happens inside the sayNameVersion1 method
p1.sayNameVersion2(niceCallback.bind(p1)) // uses bind before passing callback
The first argument
of the call
method is used as this
inside the function that is invoked with call
attached to it.
sayNameVersion3
uses call
to manipulate the this
to refer to the person object that we created, instead of the window object.
this.sayNameVersion3 = function(callback){
callback.call(this)
}
and it is called like the following :
p1.sayNameVersion3(niceCallback)
Similar to call
, first argument of apply
refers to the object that will be indicated by this
keyword.
sayNameVersion4
uses apply
to manipulate this
to refer to person object
this.sayNameVersion4 = function(callback){
callback.apply(this)
}
and it is called like the following.Simply the callback is passed,
p1.sayNameVersion4(niceCallback)
This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.
Had a situation where having FK of dependent must be it's PK
was not feasible.
E.g., Foo
already has one-to-many relationship with Bar
.
public class Foo {
public Guid FooId;
public virtual ICollection<> Bars;
}
public class Bar {
//PK
public Guid BarId;
//FK to Foo
public Guid FooId;
public virtual Foo Foo;
}
Now, we had to add another one-to-one relationship between Foo and Bar.
public class Foo {
public Guid FooId;
public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
public virtual Bar PrimaryBar;
public virtual ICollection<> Bars;
}
public class Bar {
public Guid BarId;
public Guid FooId;
public virtual Foo PrimaryBarOfFoo;
public virtual Foo Foo;
}
Here is how to specify one-to-one relationship using fluent api:
modelBuilder.Entity<Bar>()
.HasOptional(p => p.PrimaryBarOfFoo)
.WithOptionalPrincipal(o => o.PrimaryBar)
.Map(x => x.MapKey("PrimaryBarId"));
Note that while adding PrimaryBarId
needs to be removed, as we specifying it through fluent api.
Also note that method name [WithOptionalPrincipal()][1]
is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
You can also try this:
ini_set("max_execution_time", "-1");
ini_set("memory_limit", "-1");
ignore_user_abort(true);
set_time_limit(0);
You can use oraji. It can install/uninstall both JDK or JRE from oracle java (.tar.gz).
sudo oraji '/path/to/the/jdk_or_jre_archive'
oraji -u
and confirm the version number.To use the fastboot command you first need to put your device in fastboot mode:
$ adb reboot bootloader
Once the device is in fastboot mode, you can boot it with your own kernel, for example:
$ fastboot boot myboot.img
The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:
$ fastboot flash boot myboot.img
Hope that helps.
I would suggest that you use atop. You can find everything about it on this page. It is capable of providing all the necessary KPI for your processes and it can also capture to a file.
Actually, there are two foreign_key_checks
variables: a global variable and a local (per session) variable. Upon connection, the session variable is initialized to the value of the global variable.
The command SET foreign_key_checks
modifies the session variable.
To modify the global variable, use SET GLOBAL foreign_key_checks
or SET @@global.foreign_key_checks
.
Consult the following manual sections:
http://dev.mysql.com/doc/refman/5.7/en/using-system-variables.html
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html
I just want to be sure that the float number will also have 2 decimal places after converting that string.
You can't, because floating point numbers don't have decimal places. They have binary places, which aren't commensurate with decimal places.
If you want decimal places, use a decimal radix.
I'm using constraint layout mostly.
1) android:layout_width="match_parent"
= tries to stretch to meet edges
2) android:layout_width="wrap_content"
= based solely on the input text without regard for other views nearby. for example adding android:textAlignment="center"
will change the shape of the text
3) android:padding="12dp"
android:layout_width="0dp"
android:layout_weight="1"
android:singleLine="false"
= The text will fold to accommodate nearby layouts without regard to the text itself
The last index of a C-String is always the integer value 0, hence the phrase "null terminated string". Since integer 0 is the same as the Boolean value false in C, you can use that to make a simple while clause for your for loop. When it hits the last index, it will find a zero and equate that to false, ending the for loop.
for(int i = 0; string[i]; i++) { printf("Char at position %d is %c\n", i, string[i]); }
The code provided is correct, I don't see any reason why it wouldn't work.
You could also try if (string1.Equals(string2))
as suggested.
To do if (something OR something else)
, use ||
:
if (condition_1 || condition_2) { ... }
I had this problem I received a ">" like prompt and I couldn't commit. I replace the " in the comment with ' and it works.
I hope this help someone!
For new XAMPP-VM
for Mac OS X,
I change the ownership to daemon
user and solve the problem.
For example,
$ chown -R daemon:daemon /opt/lampp/htdocs/hello-laravel/storage
I've found a great example using javax.websocket
here:
http://www.programmingforliving.com/2013/08/jsr-356-java-api-for-websocket-client-api.html
Here the code based on the example linked above:
TestApp.java
:
package testapp;
import java.net.URI;
import java.net.URISyntaxException;
public class TestApp {
public static void main(String[] args) {
try {
// open websocket
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://real.okcoin.cn:10440/websocket/okcoinapi"));
// add listener
clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) {
System.out.println(message);
}
});
// send message to websocket
clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");
// wait 5 seconds for messages from websocket
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}
}
WebsocketClientEndpoint.java
:
package testapp;
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
/**
* ChatServer Client
*
* @author Jiji_Sasidharan
*/
@ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Callback hook for Connection open events.
*
* @param userSession the userSession which is opened.
*/
@OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
/**
* Callback hook for Connection close events.
*
* @param userSession the userSession which is getting closed.
* @param reason the reason for connection close
*/
@OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}
/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* @param message The text message
*/
@OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
/**
* register message handler
*
* @param msgHandler
*/
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
/**
* Send a message.
*
* @param message
*/
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
/**
* Message handler.
*
* @author Jiji_Sasidharan
*/
public static interface MessageHandler {
public void handleMessage(String message);
}
}
Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.
You can do it like this and you mod function will work perfect let me know if you want a code pen
<div ng-repeat="icon in icons">
<div class="row" ng-if="$index % 3 == 0 ">
<i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
<i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
<i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>
</div>
</div>
Here's how you do it.
First, decorate your list this way:
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
Add this CSS:
.p {
position: relative;
margin: 20px;
margin-left: 50px;
}
.text-bullet-centered {
position: absolute;
left: -40px;
top: 50%;
transform: translate(0%,-50%);
font-weight: bold;
}
And voila, it works. Resize a window, to see that it indeed works.
As a bonus, you can easily change font and color of bullets, which is very hard to do with normal lists.
.p {_x000D_
position: relative;_x000D_
margin: 20px;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
.text-bullet-centered {_x000D_
position: absolute;_x000D_
left: -40px;_x000D_
top: 50%;_x000D_
transform: translate(0%, -50%);_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>
_x000D_
MDPI - 32px
HDPI - 48px
XHDPI- 64px
This Cheat Sheet might be handy for you. check the image :-)
One way to do this is to insert a dummy column with the sums in order to sort:
In [10]: sum_B_over_A = df.groupby('A').sum().B
In [11]: sum_B_over_A
Out[11]:
A
bar 0.253652
baz -2.829711
foo 0.551376
Name: B
in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)
In [13]: df
Out[13]:
A B C sum_B_over_A
0 foo 1.624345 False 0.551376
1 bar -0.611756 True 0.253652
2 baz -0.528172 False -2.829711
3 foo -1.072969 True 0.551376
4 bar 0.865408 False 0.253652
5 baz -2.301539 True -2.829711
In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]:
A B C sum_B_over_A
5 baz -2.301539 True -2.829711
2 baz -0.528172 False -2.829711
1 bar -0.611756 True 0.253652
4 bar 0.865408 False 0.253652
3 foo -1.072969 True 0.551376
0 foo 1.624345 False 0.551376
and maybe you would drop the dummy row:
In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;
We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);
Before C++20 we need to pass lambda as argument to set constructor
Make comparator as usual boolean function
bool cmp(int a, int b) {
return ...;
}
Then use it, either this way:
std::set<int, decltype(cmp)*> s(cmp);
or this way:
std::set<int, decltype(&cmp)> s(&cmp);
()
operatorstruct cmp {
bool operator() (int a, int b) const {
return ...
}
};
// ...
// later
std::set<int, cmp> s;
Take boolean function
bool cmp(int a, int b) {
return ...;
}
And make struct from it using std::integral_constant
#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;
Finally, use the struct as comparator
std::set<X, Cmp> set;
In the case of Android projects, you can fix this error by changing the project/module gradle file (build.gradle) as follows:
dependencies { implementation 'com.android.support:support-annotations:24.2.0' }
For more informations, please refer here.
You can use this by php function with substr function
<?php
function removeChar($value) {
$value2 = substr($value, 4);
return $value2;
}
echo removeChar("Dummy Text. Sample Text.");
?>
You get this result: " y Text. Sample Text. "
Simpler and Easy fix to avoid confusions..
For Windows users to use multiple or different git accounts for different projects.
Following steps: Go Control Panel and Search for Credential Manager. Then Go to Credential Manager -> Windows Credentials
Now remove the git:https//github.com node under Generic Credentials Heading
This will remove the current credentials. Now you can add any project through git pull it will ask for username and password.
When you face any issue with other account do the same process.
Thanks
I use the following trap code, it also allows errors to be traced through pipes and 'time' commands
#!/bin/bash
set -o pipefail # trace ERR through pipes
set -o errtrace # trace ERR through 'time command' and other functions
function error() {
JOB="$0" # job name
LASTLINE="$1" # line of error occurrence
LASTERR="$2" # error code
echo "ERROR in ${JOB} : line ${LASTLINE} with exit code ${LASTERR}"
exit 1
}
trap 'error ${LINENO} ${?}' ERR
These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.
function isURL(str) {
var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
var url = new RegExp(urlRegex, 'i');
return str.length < 2083 && url.test(str);
}
For Ubuntu 16.04.5, it is noticed that MongoDB installations does not auto enable the mongod.service file after installation in my case after I have installed on several servers, so we need to enable it like below:
Issue below to check whether mongod is enabled
systemctl list-unit-files --type=service
If it shows as "disabled", then you need to enable it.
sudo systemctl enable mongod.service
If we want to see whether mongod.service file exists in case this file is missing, check in
ls /lib/systemd/system
You will see a file
/lib/systemd/system/mongod.service
I adapted this from http://snook.ca/archives/html_and_css/css-text-rotation :
<style> .Rotate-90 { display: block; position: absolute; right: -5px; top: 15px; -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); } </style> <!--[if IE]> <style> .Rotate-90 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); right:-15px; top:5px; } </style> <![endif]-->
The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.
Another way is to use tidy evaluation
approach. It is pretty straightforward to pass columns of a data frame either as strings or bare column names. See more about tidyeval
here.
library(rlang)
library(tidyverse)
set.seed(123)
df <- data.frame(B = rnorm(10), D = rnorm(10))
Use column names as strings
fun3 <- function(x, ...) {
# capture strings and create variables
dots <- ensyms(...)
# unquote to evaluate inside dplyr verbs
summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}
fun3(df, "B")
#> B
#> 1 1.715065
fun3(df, "B", "D")
#> B D
#> 1 1.715065 1.786913
Use bare column names
fun4 <- function(x, ...) {
# capture expressions and create quosures
dots <- enquos(...)
# unquote to evaluate inside dplyr verbs
summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}
fun4(df, B)
#> B
#> 1 1.715065
fun4(df, B, D)
#> B D
#> 1 1.715065 1.786913
#>
Created on 2019-03-01 by the reprex package (v0.2.1.9000)
action=""
will resolve to the page's address. action="#"
will resolve to the page's address + #
, which will mean an empty fragment identifier.
Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.
Usually, authors just put #
in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action=""
(or omit it if validation allows).
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
var objectUrl = _URL.createObjectURL(file);
img.onload = function () {
alert(this.width + " " + this.height);
_URL.revokeObjectURL(objectUrl);
};
img.src = objectUrl;
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
P.S. The URL.createObjectURL()
method has been removed from the MediaStream
interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject
. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL()
to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.
For more information, please refer here.
Why nobody mentions matchMedia?
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Did not test that much, but tested with android default and android chrome browsers, desktop chrome, so far it looks like it works well.
Of course it does not return number value, but returns boolean - if matches or not, so might not exactly fit the question but that's what we want anyway and probably the author of question wants.
Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.
To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.
Edit: I've copied the steps below - kudos to the original author of the link above.