use User::get(['id', 'name', 'email'])
, it will return you a collection with the specified columns and if you want to make it an array, just use toArray()
after the get()
method like so:
User::get(['id', 'name', 'email'])->toArray()
Most of the times, you won't need to convert the collection to an array because collections are actually arrays on steroids and you have easy-to-use methods to manipulate the collection.
You can use six and abc to construct a class for both python2 and python3 efficiently as follows:
import six
import abc
@six.add_metaclass(abc.ABCMeta)
class MyClass(object):
"""
documentation
"""
@abc.abstractmethod
def initialize(self, para=None):
"""
documentation
"""
raise NotImplementedError
Use cursor.lastrowid
to get the last row ID inserted on the cursor object, or connection.insert_id()
to get the ID from the last insert on that connection.
For those that are still experiencing problems, like I have(I am using Ubuntu 16.04), I had to put in the following commands in order to get some gems like bcrypt, pg, and others installed. They are all similar to the ones above except for one.
sudo apt-get install ruby-dev -y
sudo apt-get install libpq-dev -y
sudo apt-get install libmysqlclient-dev
sudo apt-get install build-essential patch -y
This allowed me to install gems like, PG, bcrypt, and recaptcha.
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
based on this
I modified the original to this:
^(?:(?:(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec))(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:(?:0?2|(?:Feb))(\/|-|\.)(?:29)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
In PHP and phpMyAdmin
$tb = tableDataName; //Table name
$now = date('Y-m-d'); //Current date
//start and end is the fields of tabla with date format value (yyyy-m-d)
$query = "SELECT * FROM $tb WHERE start <= '".$now."' AND end >= '".$now."'";
Correct answer is simply:
SELECT a.group_id
FROM a
LEFT JOIN b ON a.group_id=b.group_id and b.user_id = 4
where b.user_id is null
and a.keyword like '%keyword%'
Here we are checking user_id = 4
(your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.
From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.
This it the best way to calculate the size of a directory. Only other way would still use recursion but be a bit easier to use and isn't as flexible.
float folderSize = 0.0f;
FileInfo[] files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories);
foreach(FileInfo file in files) folderSize += file.Length;
By default, inheritance is private. You have to explicitly use public
:
class Bar : public Foo
You could store the last insert id in a variable :
INSERT INTO table1 (title,userid) VALUES ('test', 1);
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (parentid,otherid,userid) VALUES (@last_id_in_table1, 4, 1);
Or get the max id frm table1
INSERT INTO table1 (title,userid) VALUES ('test', 1);
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(), 4, 1);
SELECT MAX(id) FROM table1;
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
To those having this issue after update to Catalina, just execute this command on your terminal
sudo rm -rf /Library/Developer/CommandLineTools; xcode-select --install;
That's the simplest way I can think for finding duplicates in a list:
my_list = [3, 5, 2, 1, 4, 4, 1]
my_list.sort()
for i in range(0,len(my_list)-1):
if my_list[i] == my_list[i+1]:
print str(my_list[i]) + ' is a duplicate'
I am not sure what the problem is, but I am pretty sure this will fix it.
for (i=0; i<arrChecks.length; i++)
{
var attribute = arrChecks[i].getAttribute("xid")
if (attribute == elementName)
{
if (arrChecks[i].checked == 0)
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
} else {
arrChecks[i].checked = 0;
}
}
As Zach explained, you can use:
xor = bool(a) ^ bool(b)
Personally, I favor a slightly different dialect:
xor = bool(a) + bool(b) == 1
This dialect is inspired from a logical diagramming language I learned in school where "OR" was denoted by a box containing =1
(greater than or equal to 1) and "XOR" was denoted by a box containing =1
.
This has the advantage of correctly implementing exclusive or on multiple operands.
You can initialize an array by writing actual values it holds in curly braces on the right hand side like:
String[] strArr = { "one", "two", "three"};
int[] numArr = { 1, 2, 3};
In the same manner two-dimensional array or array-of-arrays holds an array as a value, so:
String strArrayOfArrays = { {"a", "b", "c"}, {"one", "two", "three"} };
Your example shows exactly that
double m[][] = {
{0*0,1*0,2*0,3*0},
{0*1,1*1,2*1,3*1},
{0*2,1*2,2*2,3*2},
{0*3,1*3,2*3,3*3}
};
But also the multiplication of number will also be performed and its the same as:
double m[][] = { {0, 0, 0, 0}, {0, 1, 2, 3}, {0, 2, 4, 6}, {0, 3, 6, 9} };
This is what has to occur.
You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\
Then in the Run dialog, type this in:
C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll
and you will get the message:
DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.
To update a subset of fields, you can use update_fields
:
survey.save(update_fields=["active"])
The update_fields
argument was added in Django 1.5. In earlier versions, you could use the update()
method instead:
Survey.objects.filter(pk=survey.pk).update(active=True)
from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable
Here's a light weight way to use require and exports in your web client. It's a simple wrapper that creates a "namespace" global variable, and you wrap your CommonJS compatible code in a "define" function like this:
namespace.lookup('org.mydomain.mymodule').define(function (exports, require) {
var extern = require('org.other.module');
exports.foo = function foo() { ... };
});
More docs here:
If you are using PHP7, then you would need a PHP script like this one in order to migrate your collation:
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$mysqli = new mysqli('db',$dbuser,$dbpassword);
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$mysqli -> select_db($dbname);
$result= $mysqli->query('show tables');
while($tables = $result->fetch_array) {
foreach ($tables as $key => $value) {
$mysqli->query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
add this to you CSS:
html, body
{
height: 100%;
}
when you say to wrap
to be 100%
, 100% of what? of its parent (body), so his parent has to have some height.
and the same goes for body
, his parent his html
. html
parent his the viewport..
so, by setting them both to 100%, wrap
can also have a percentage height.
also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use
*
{
padding: 0;
margin: 0;
}
to disable that.
Look at That Fiddle
A No Framework JavaScript Approach, checks for both vertical and horizontal
/*
* hasScrollBars
*
* Checks to see if an element has scrollbars
*
* @returns {object}
*/
Element.prototype.hasScrollBars = function() {
return {"vertical": this.scrollHeight > this.style.height, "horizontal": this.scrollWidth > this.style.width};
}
Use it like this
if(document.getElementsByTagName("body")[0].hasScrollBars().vertical){
alert("vertical");
}
if(document.getElementsByTagName("body")[0].hasScrollBars().horizontal){
alert("horizontal");
}
I guess the problem is your js runs before the html is loaded.
If you are using jquery, you can use the document ready function to wrap your code:
$(function() {
var Grid = function(width, height) {
// codes...
}
});
Or simply put your js after the <canvas>
.
Indeed, the compiler doesn't know how to convert this anonymous type (the new { x.ServerName, x.ProcessID, x.Username }
part) to a PInfo object.
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new { x.ServerName, x.ProcessID, x.Username }).ToList();
This gives you a list of objects (of anonymous type) you can use afterwards, but you can't return that or pass that to another method.
If your PInfo object has the right properties, it can be like this :
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new PInfo
{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username
}).ToList();
Assuming that PInfo has at least those three properties.
Both query allow you to fetch only the wanted columns, but using an existing type (like in the second query) allows you to send this data to other parts of your app.
Import
import android.net.Uri;
Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);
or it can be done using,
TextView textView = (TextView)findViewById(R.id.yourID);
textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.typeyourURL.com"));
startActivity(intent);
} });
I see very complicated answers, all of them using code. However, if you are using Interface Builder, there is a very easy way to do this:
You could even use the same approach by code, without creating UILabels and UIImages inside as other solutions proposed. Always Keep It Simple!
EDIT: Attached a small example having the 3 things set (title, image and background) with correct insets
Use Promise.each of bluebird library.
Promise.each(
Iterable<any>|Promise<Iterable<any>> input,
function(any item, int index, int length) iterator
) -> Promise
This method iterates over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (value, index, length) where the value is the resolved value of a respective promise in the input array. Iteration happens serially. If the iterator function returns a promise or a thenable, then the result of the promise is awaited before continuing with next iteration. If any promise in the input array is rejected, then the returned promise is rejected as well.
If all of the iterations resolve successfully, Promise.each resolves to the original array unmodified. However, if one iteration rejects or errors, Promise.each ceases execution immediately and does not process any further iterations. The error or rejected value is returned in this case instead of the original array.
This method is meant to be used for side effects.
var fileNames = ["1.txt", "2.txt", "3.txt"];
Promise.each(fileNames, function(fileName) {
return fs.readFileAsync(fileName).then(function(val){
// do stuff with 'val' here.
});
}).then(function() {
console.log("done");
});
The Array.prototype.join() method:
var arr = ["Zero", "One", "Two"];_x000D_
_x000D_
document.write(arr.join(", "));
_x000D_
It will be better to use xpath
from selenium import webdriver
driver.get('www.example.com')
button = driver.find_element_by_xpath('xpath')
button.click()
Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!
var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();
This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)
BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:
var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
var shoppingCart = _dataContext.ShoppingCart
.Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
.ToList();
This will return 5 results from DB. Using 'contains' would be wrong in this case.
$sql = "select count(column_name) as count from table";
For me
document.addEventListener("mousewheel", this.mousewheel.bind(this), { passive: false });
did the trick (the { passive: false }
part).
I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap
in the css.
Here's complete working code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Something</title>
<style type="text/css">
#scrolly{
width: 1000px;
height: 190px;
overflow: auto;
overflow-y: hidden;
margin: 0 auto;
white-space: nowrap
}
img{
width: 300px;
height: 150px;
margin: 20px 10px;
display: inline;
}
</style>
</head>
<body>
<div id='scrolly'>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
<img src='img/car.jpg'></img>
</div>
</body>
</html>
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Perhaps use information_schema:
SELECT EXISTS(
SELECT *
FROM information_schema.tables
WHERE
table_schema = 'company3' AND
table_name = 'tableincompany3schema'
);
You can use 2 ways for solve this problem: 1) After the head tag
<head>
<meta http-equiv="refresh" content="600">
</head>
2) If your page hasn't head tag you must use Javascript to implement
<script type="text/javascript">
function RefreshPage()
{
window.location.reload()
}
</script>
My contact:
One can use df.insert(index_to_insert_at, column_header, init_value)
to insert new column at a specific index.
cost_tbl.insert(1, "col_name", "")
The above statement would insert an empty Column after the first column.
NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(@"There are %d days in between the two dates.", numberOfDays);
Remember, NSDate
objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter
, the NSDateFormatter
converts the time from the configured timezone. Therefore, the number of seconds between two NSDate
objects will always be time-zone-agnostic.
Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.
For create circle button you are this codes:
.circle-right-btn {
display: block;
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px solid #fefefe;
margin-top: 24px;
font-size:22px;
}
_x000D_
<input class="circle-right-btn" type="submit" value="<">
_x000D_
You can't, and you shouldn't.
Every other approach / alternative will only cause really bad user engagement.
That's my opinion.
Look at System.Reflection.AssemblyName.GetAssemblyName(string assemblyFile)
You can examine assembly metadata from the returned AssemblyName instance:
Using PowerShell:
[36] C:\> [reflection.assemblyname]::GetAssemblyName("${pwd}\Microsoft.GLEE.dll") | fl Name : Microsoft.GLEE Version : 1.0.0.0 CultureInfo : CodeBase : file:///C:/projects/powershell/BuildAnalyzer/... EscapedCodeBase : file:///C:/projects/powershell/BuildAnalyzer/... ProcessorArchitecture : MSIL Flags : PublicKey HashAlgorithm : SHA1 VersionCompatibility : SameMachine KeyPair : FullName : Microsoft.GLEE, Version=1.0.0.0, Culture=neut...
Here, ProcessorArchitecture identifies target platform.
I'm using PowerShell in this example to call the method.
$insert = $this->db->insert('email_notification', $data);
$this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");
//require ("plugins/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
),
);
$message="
Your Account Has beed created successfully by Admin:
Username: ".$this->input->post('username')." <br><br>
Email: ".$this->input->post('sender_email')." <br><br>
Regargs<br>
<div class='background-color:#666;color:#fff;padding:6px;
text-align:center;'>
Bookly Admin.
</div>
";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true;
$subject = "Hello ".$this->input->post('username');
$mail->SMTDebug=2;
$email = $this->input->post('sender_email'); //this email is user email
$from_label = "Account Creation";
$mail->Username = 'your email'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
$mail->setFrom($from_label);
$mail->addAddress($email, 'Bookly Admin');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if($mail->send()){
}
I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X}
as I find it makes it more readable.
Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:
@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*
def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
That gives me the following output on my machine:
Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
* JRE: 1.6.0_31
* Total Memory: 81.0625 MB
* Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64)
Options
=======
* Warm Up: Auto
* CPU Time Measurement: Off
String adder 539
GString template 245
Readable GString template 244
StringBuilder 318
StringBuffer 370
So with readability and speed in it's favour, I'd recommend templating ;-)
NB: If you add toString()
to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder
and StringBuffer
beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion
Adding these tests (as it has been asked in the comments)
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
Now we get the results:
String adder 514
GString template 267
Readable GString template 269
GString template toString 478
Readable GString template toString 480
StringBuilder 321
StringBuffer 369
So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...
But still lots more readable.
Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:
@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )
def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer with Allocation' {
new StringBuffer( 512 ).append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
gives
Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
* JRE: 1.7.0_21
* Total Memory: 467.375 MB
* Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 630 0 630 647
GString template 29 0 29 31
Readable GString template 32 0 32 33
GString template toString 429 0 429 443
Readable GString template toString 428 1 429 441
StringBuilder 383 1 384 396
StringBuffer 395 1 396 409
StringBuffer with Allocation 277 0 277 286
Type this in cell B1, and copy down...
="X"&A1
This would also work:
=CONCATENATE("X",A1)
And here's one of many ways to do this in VBA (Disclaimer: I don't code in VBA very often!):
Sub AddX()
Dim i As Long
With ActiveSheet
For i = 1 To .Range("A65536").End(xlUp).Row Step 1
.Cells(i, 2).Value = "X" & Trim(Str(.Cells(i, 1).Value))
Next i
End With
End Sub
const * char
is invalid C code and is meaningless. Perhaps you meant to ask the difference between a const char *
and a char const *
, or possibly the difference between a const char *
and a char * const
?
Have a look at the CleanProject, it will delete bin folders, obj folders, TestResults folders and Resharper folders. The source code is also available.
Here's how I did it:
@fake-command /u %1 /p %2
Here's what the command looks like:
test.cmd admin P@55w0rd > test-log.txt
The %1
applies to the first parameter the %2
(and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.
What Dweebo proposed works. But in my humble opinion it is unnecessary. A background drawable scales well by itself. The view should have fixed width and height, like in the following example:
< RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/black">
<LinearLayout
android:layout_width="500dip"
android:layout_height="450dip"
android:layout_centerInParent="true"
android:background="@drawable/my_drawable"
android:orientation="vertical"
android:padding="30dip"
>
...
</LinearLayout>
< / RelativeLayout>
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
While installing Netbeans itself, you will get an option which servers needs to be installed and integrated with Netbeans. First screen itself will show.
Another option is to reinstall Netbeans by closing all the open projects.
Update
As of 2019 this can be easily achieved using ProgressIndicator
, in Material Components library, used with the Widget.MaterialComponents.ProgressIndicator.Circular.Indeterminate
style.
For more details please check Gabriele Mariotti's answer below.
Old implementation
Here is an awesome implementation of the material design circular intermediate progress bar https://gist.github.com/castorflex/4e46a9dc2c3a4245a28e. The implementation only lacks the ability add various colors like in inbox by android app but this does a pretty great job.
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName'
AND TABLE_SCHEMA = SchemaName)
BEGIN
ALTER TABLE TableName DROP COLUMN ColumnName;
END;
There is a really simple way to do this in a CSS only way.
Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.
#mouse_over {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
SQlite does not have a specific datetime type. You can use TEXT
, REAL
or INTEGER
types, whichever suits your needs.
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
- TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
- REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
- INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
SQLite built-in Date and Time functions can be found here.
Another one to this list, Cinchoo ETL - an open source library to read and write CSV files
For a sample CSV file below
Id, Name
1, Tom
2, Mark
Quickly you can load them using library as below
using (var reader = new ChoCSVReader("test.csv").WithFirstLineHeader())
{
foreach (dynamic item in reader)
{
Console.WriteLine(item.Id);
Console.WriteLine(item.Name);
}
}
If you have POCO class matching the CSV file
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
You can use it to load the CSV file as below
using (var reader = new ChoCSVReader<Employee>("test.csv").WithFirstLineHeader())
{
foreach (var item in reader)
{
Console.WriteLine(item.Id);
Console.WriteLine(item.Name);
}
}
Please check out articles at CodeProject on how to use it.
Disclaimer: I'm the author of this library
try this one its worked for me
$(document).ready(function(e){_x000D_
$.ajax({_x000D_
url:"fetch",_x000D_
processData: false,_x000D_
dataType:"json",_x000D_
type: 'POST',_x000D_
cache: false,_x000D_
success: function (data, textStatus, jqXHR) {_x000D_
_x000D_
$.each(data.Table,function(i,tweet){_x000D_
$("#list").append('<option value="'+tweet.actor_id+'">'+tweet.first_name+'</option>');_x000D_
});}_x000D_
});_x000D_
});
_x000D_
I had the same requirements to create a kind of step progress tracker so I created a JavaScript plugin for that purpose. Here is the JsFiddle for the demo for this step progress tracker. You can access its code on GitHub as well.
What it basically does is, it takes the json data(in a particular format described below) as input and creates the progress tracker based on that. Highlighted steps indicates the completed steps.
It's html will somewhat look like shown below with default CSS but you can customize it as per the theme of your application. There is an option to show tool-tip text for each steps as well.
Here is some code snippet for that:
//container div
<div id="tracker1" style="width: 700px">
</div>
//sample JSON data
var sampleJson1 = {
ToolTipPosition: "bottom",
data: [{ order: 1, Text: "Foo", ToolTipText: "Step1-Foo", highlighted: true },
{ order: 2, Text: "Bar", ToolTipText: "Step2-Bar", highlighted: true },
{ order: 3, Text: "Baz", ToolTipText: "Step3-Baz", highlighted: false },
{ order: 4, Text: "Quux", ToolTipText: "Step4-Quux", highlighted: false }]
};
//Invoking the plugin
$(document).ready(function () {
$("#tracker1").progressTracker(sampleJson1);
});
Hopefully it will be useful for somebody else as well!
On UNIX Just use this:
mkdir -p $(OBJDIR)
The -p option to mkdir prevents the error message if the directory exists.
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?
If main.py
and parse_args()
is written in this way, then the parsing can be done nicely
# main.py
import argparse
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument('--input', default='my_input.txt')
return parser
def main(args):
print(args.input)
if __name__ == "__main__":
parser = parse_args()
args = parser.parse_args()
main(args)
Then you can call main()
and parse arguments with parser.parse_args(['--input', 'foobar.txt'])
to it in another python script:
# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)
Just for reference, if you are using:
$(el).offset().top
To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:
$(el).offset({top: pos});
As opposed to the CSS methods above.
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
Robocopy is designed for reliable copying with many copy options, file selection restart, etc.
/xf
to excludes files and /e
for subdirectories:
robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"
Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
//do
}
You need to use the Disposable Pattern like this:
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Dispose any managed objects
// ...
}
// Now disposed of any unmanaged objects
// ...
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Destructor
~YourClassName()
{
Dispose(false);
}
I drilled down the formation of the drop down list instead of using @Html.DropDownList()
. This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:
<select id="NewsCategoriesID" name="NewsCategoriesID">
@foreach (SelectListItem option in ViewBag.NewsCategoriesID)
{
<option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>
}
</select>
HttpClient is not supported in sdk 23 and 23+.
If you need to use into sdk 23, add below code to your gradle:
android {
useLibrary 'org.apache.http.legacy'
}
Its working for me. Hope useful for you.
It work a simple example recursive (Y)
<?php function factorial($y,$x) { if ($y < $x) { echo $y; } else { echo $x; factorial($y,$x+1); } } $y=10; $x=0; factorial($y,$x); ?>
Static member functions must refer to static variables of that class. So in your case,
static void CP_StringToPString( std::string& inString, unsigned char *outString);
Since your member function CP_StringToPstring
is static, the parameters in that function, inString
and outString
should be declared as static too.
The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.
You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.
1.Remove onclick
method from div
element
2.Remove function change()
from jQuery code and in place of that create an anonymous function like:
$(document).ready(function()
{
$('#co').click(function()
{
$('body').css('background-color','blue');
});
});
I am using something like this - codeigniter-htaccess-file, its a good article to begin with.
$config['index_page'] = "";
$route['default_controller']="home";
If you are running clean installation of CI (2.1.3) there isn't really much that could be wrong.
read
In contribution to ellabeauty's answer. you can also use this dynamic percentage values
$('.bar').css('width', function(){ return ($(this).attr('data-percentage')+'%')});
And probably add custom easing to your css
.bar {
-webkit-transition: width 2.50s ease !important;
-moz-transition: width 2.50s ease !important;
-o-transition: width 2.50s ease !important;
transition: width 2.50s ease !important;
}
As many other pointed out, arguments
contains all the arguments passed to a function.
If you want to call another function with the same args, use apply
Example:
var is_debug = true;
var debug = function() {
if (is_debug) {
console.log.apply(console, arguments);
}
}
debug("message", "another argument")
1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.
2) No. See the whatsapp security white paper.
3) See #1.
What you should be looking at is Import-Csv
Once you import the CSV you can use the column header as the variable.
Example CSV:
Name | Phone Number | Email
Elvis | 867.5309 | [email protected]
Sammy | 555.1234 | [email protected]
Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:
$Name = @()
$Phone = @()
Import-Csv H:\Programs\scripts\SomeText.csv |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
$inputNumber = Read-Host -Prompt "Phone Number"
if ($Phone -contains $inputNumber)
{
Write-Host "Customer Exists!"
$Where = [array]::IndexOf($Phone, $inputNumber)
Write-Host "Customer Name: " $Name[$Where]
}
And here is the output:
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
Try shFlags -- Advanced command-line flag library for Unix shell scripts.
http://code.google.com/p/shflags/
It is very good and very flexible.
FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.
DEFINE_string: takes any input, and intreprets it as a string.
DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.
DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.
DEFINE_integer: takes an input and intreprets it as an integer.
SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing
EXAMPLE USAGE:
-- begin hello.sh --
! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --
$ ./hello.sh -n Kate
Hello, Kate.
Note: I took this text from shflags documentation
I would suggest using conda. Conda is an anconda specific package manager. If you want to know more about conda, read the conda docs.
Using conda in the command line, the command below would install scipy 0.17.
conda install scipy=0.17.0
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
according to the mySQL reference manual this the syntax of using if and else statement :
IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list] ... [ELSE statement_list] END IF
So regarding your query :
x = IF((action=2)&&(state=0),1,2);
or you can use
IF ((action=2)&&(state=0)) then
state = 1;
ELSE
state = 2;
END IF;
There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
If you want set custom exception handling behavior for a specific controller, you can do so by overriding the controllers OnActionExecuted
method.
Remember to set the ExceptionHandled
property to true to disable default exception handling behavior.
Here is a sample from an api I'm writing, where I want to catch specific types of exceptions and return a json formatted result:
private static readonly Type[] API_CATCH_EXCEPTIONS = new Type[]
{
typeof(InvalidOperationException),
typeof(ValidationException)
};
public override void OnActionExecuted(ActionExecutedContext context)
{
base.OnActionExecuted(context);
if (context.Exception != null)
{
var exType = context.Exception.GetType();
if (API_CATCH_EXCEPTIONS.Any(type => exType == type || exType.IsSubclassOf(type)))
{
context.Result = Problem(detail: context.Exception.Message);
context.ExceptionHandled = true;
}
}
}
IP + "User Agent" could be a better for unique visitor.
Swift 3
class TwoViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.cyan
self.view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
cell.backgroundColor = UIColor.green
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 50, height: 50)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}
}
This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");
EDIT: This only applies to some versions of make
- you should check your man page.
You can also pass the -B
flag to make
. As per the man page, this does:
-B, --always-make
Unconditionally make all targets.
So make -B test
would solve your problem if you were in a situation where you don't want to edit the Makefile
or change the name of your test folder.
I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:
Option1:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
Option2:
SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson();
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();
Option 2 is twice quicker than option 1
The option 2 inconvenience is that you have to make specific code for read:
Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);
use as at end of query
Select * into #temp (select * from table1,table2) as temp_table
in bluehost i could not reset password; with this driver worked:
MAIL_DRIVER=sendmail
with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center
In C ^
is the bitwise XOR:
0101 ^ 1100 = 1001 // in binary
There's no operator for power, you'll need to use pow
function from math.h (or some other similar function):
result = pow( a, i );
The Maven Dependency Plugin will help, especially the dependency:analyze
goal:
dependency:analyze
analyzes the dependencies of this project and determines which are: used and declared; used and undeclared; unused and declared.
Another thing that might help to do some cleanup is the Dependency Convergence report from the Maven Project Info Reports Plugin.
Globally install Composer on OS X 10.11 El Capitan
This command will NOT work in OS X 10.11:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/bin --filename=composer
Instead, let's write to the /usr/local/bin path for the user:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
Now we can access the composer command globally, just like before.
you can also add inline css for adding image as a background as per below example
<div class="item active" style="background-image: url(../../foo.png);">
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Append IDs at the class declaration
.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";
public enum MyEnum {
ONE(1),
TWO(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)
As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.
Update: For strings the only difference is that your constructor argument is String
, and you declare enums with TEST("test")
For .Net 4.5+
It is not always desired to write the uncompressed file to disk. As an ASP.Net developer, I would have to fiddle with permissions to grant rights for my application to write to the filesystem. By working with streams in memory, I can sidestep all that and read the files directly:
using (ZipArchive archive = new ZipArchive(postedZipStream))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var stream = entry.Open();
//Do awesome stream stuff!!
}
}
Alternatively, you can still write the decompressed file out to disk by calling ExtractToFile()
:
using (ZipArchive archive = ZipFile.OpenRead(pathToZip))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
entry.ExtractToFile(Path.Combine(destination, entry.FullName));
}
}
To use the ZipArchive
class, you will need to add a reference to the System.IO.Compression
namespace and to System.IO.Compression.FileSystem
.
just came across while browsing, might help you javascript-getting-and-setting-caret-position-in-textarea
. You can use it for textbox also.
Whenever you change a class in your script, you could use a trigger
to raise your own event.
$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });
but otherwise, no, there's no baked-in way to fire an event when a class changes. change()
only fires after focus leaves an input whose input has been altered.
$(function() {_x000D_
var button = $('.clickme')_x000D_
, box = $('.box')_x000D_
;_x000D_
_x000D_
button.on('click', function() { _x000D_
box.removeClass('box');_x000D_
$(document).trigger('buttonClick');_x000D_
});_x000D_
_x000D_
$(document).on('buttonClick', function() {_x000D_
box.text('Clicked!');_x000D_
});_x000D_
});
_x000D_
.box { background-color: red; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="box">Hi</div>_x000D_
<button class="clickme">Click me</button>
_x000D_
If self could be nil in the closure use [weak self].
If self will never be nil in the closure use [unowned self].
The Apple Swift documentation has a great section with images explaining the difference between using strong, weak, and unowned in closures:
Apple have recently made new changes in APNs and now apple insist us to use "Token Based Authentication" instead of the traditional ways which we are using for push notification.
So does not need to worry about their expiration and this p8 certificates are for both development and production so again no need to generate 2 separate certificate for each mode.
To generate p8 just go to your developer account and select this option "Apple Push Notification Authentication Key (Sandbox & Production)"
Then will generate directly p8 file.
I hope this will solve your issue.
Read this new APNs changes from apple: https://developer.apple.com/videos/play/wwdc2016/724/
Also you can read this: https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/APNsProviderAPI.html
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>model = {{data.model}}</tt><br/>
</div>
AngularJS:
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
};
}]);
taken from AngularJS docs
This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.
HTML:
<div rel="this-should-be-the-target">
</div>
JQuery:
$(function() {
var targetElement = 'rel="this-should-be-the-target"';
initPopover(targetElement, "Test Popover Content");
// use this line if you want it to show by default
$(targetElement).popover('show');
function initPopover(target, popOverContent) {
$(target).each(function(i, obj) {
$(this).popover({
placement : 'auto',
trigger : 'hover',
"html": true,
content: popOverContent
});
});
}
});
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
Try this one using Grid Layout:
.grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: auto auto auto;_x000D_
padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
background-color: rgba(255, 255, 255, 0.8);_x000D_
border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
padding: 20px;_x000D_
font-size: 30px;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
<div class="grid-item">1</div>_x000D_
<div class="grid-item">2</div>_x000D_
<div class="grid-item">3</div> _x000D_
<div class="grid-item">4</div>_x000D_
<div class="grid-item">5</div>_x000D_
<div class="grid-item">6</div> _x000D_
<div class="grid-item">7</div>_x000D_
<div class="grid-item">8</div>_x000D_
<div class="grid-item">9</div> _x000D_
</div>
_x000D_
list1.retainAll(list2) - is intersection
union will be removeAll
and then addAll
.
Find more in the documentation of collection(ArrayList is a collection) http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collection.html
Try This
<!DOCTYPE html>
<html>
<head>
<title>Sticky Header and Footer</title>
<style type="text/css">
/* Reset body padding and margins */
body {
margin:0;
padding:0;
}
/* Make Header Sticky */
#header_container {
background:#eee;
border:1px solid #666;
height:60px;
left:0;
position:fixed;
width:100%;
top:0;
}
#header {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
/* CSS for the content of page. I am giving top and bottom padding of 80px to make sure the header and footer do not overlap the content.*/
#container {
margin:0 auto;
overflow:auto;
padding:80px 0;
width:940px;
}
#content {
}
/* Make Footer Sticky */
#footer_container {
background:#eee;
border:1px solid #666;
bottom:0;
height:60px;
left:0;
position:fixed;
width:100%;
}
#footer {
line-height:60px;
margin:0 auto;
width:940px;
text-align:center;
}
</style>
</head>
<body>
<!-- BEGIN: Sticky Header -->
<div id="header_container">
<div id="header">
Header Content
</div>
</div>
<!-- END: Sticky Header -->
<!-- BEGIN: Page Content -->
<div id="container">
<div id="content">
content
<br /><br />
blah blah blah..
...
</div>
</div>
<!-- END: Page Content -->
<!-- BEGIN: Sticky Footer -->
<div id="footer_container">
<div id="footer">
Footer Content
</div>
</div>
<!-- END: Sticky Footer -->
</body>
</html>
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
In PHP, strings are bytestreams. What exactly are you trying to do?
Re: edit
Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...
fputs
takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
We can also do in-place remove all using either del
or pop
:
import random
def remove_values_from_list(lst, target):
if type(lst) != list:
return lst
i = 0
while i < len(lst):
if lst[i] == target:
lst.pop(i) # length decreased by 1 already
else:
i += 1
return lst
remove_values_from_list(None, 2)
remove_values_from_list([], 2)
remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
lst = remove_values_from_list([random.randrange(0, 10) for x in range(1000000)], 2)
print(len(lst))
Now for the efficiency:
In [21]: %timeit -n1 -r1 x = random.randrange(0,10)
1 loop, best of 1: 43.5 us per loop
In [22]: %timeit -n1 -r1 lst = [random.randrange(0, 10) for x in range(1000000)]
g1 loop, best of 1: 660 ms per loop
In [23]: %timeit -n1 -r1 lst = remove_values_from_list([random.randrange(0, 10) for x in range(1000000)]
...: , random.randrange(0,10))
1 loop, best of 1: 11.5 s per loop
In [27]: %timeit -n1 -r1 x = random.randrange(0,10); lst = [a for a in [random.randrange(0, 10) for x in
...: range(1000000)] if x != a]
1 loop, best of 1: 710 ms per loop
As we see that in-place version remove_values_from_list()
does not require any extra memory, but it does take so much more time to run:
The right way to do it in SDK V2, without the overload of actually getting the object, is to use S3Client.headObject. Officially backed by AWS Change Log.
Example code:
public boolean exists(String bucket, String key) {
try {
HeadObjectResponse headResponse = client
.headObject(HeadObjectRequest.builder().bucket(bucket).key(key).build());
return true;
} catch (NoSuchKeyException e) {
return false;
}
}
No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate PEP-8 where it is mandated that lines should not exceed 80 characters in length.
It's also against the Zen of Python: "Readability counts". (Type import this
at the Python prompt to read the whole thing).
You can use a ternary expression in Python, but only for expressions, not for statements:
>>> a = "Hello" if foo() else "Goodbye"
Edit:
Your revised question now shows that the three statements are identical except for the value being assigned. In that case, a chained ternary operator does work, but I still think that it's less readable:
>>> i=100
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
2
>>> i=99
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
1
You could use Enumerable.Max
:
new [] { 1, 2, 3 }.Max();
I've found the same problem before, hope this solution can help you. first, add a custom attribute to your checkboxes:
<input type="checkbox" id="ans" value="1" data-unchecked="0" />
write a jQuery extension to get value:
$.fn.realVal = function(){
var $obj = $(this);
var val = $obj.val();
var type = $obj.attr('type');
if (type && type==='checkbox') {
var un_val = $obj.attr('data-unchecked');
if (typeof un_val==='undefined') un_val = '';
return $obj.prop('checked') ? val : un_val;
} else {
return val;
}
};
use code to get check-box value:
$('#ans').realVal();
you can test here
EDIT: The fetch request will still be running in the background and will most likely log an error in your console.
Indeed the Promise.race
approach is better.
See this link for reference Promise.race()
Race means that all Promises will run at the same time, and the race will stop as soon as one of the promises returns a value. Therefore, only one value will be returned. You could also pass a function to call if the fetch times out.
fetchWithTimeout(url, {
method: 'POST',
body: formData,
credentials: 'include',
}, 5000, () => { /* do stuff here */ });
If this piques your interest, a possible implementation would be :
function fetchWithTimeout(url, options, delay, onTimeout) {
const timer = new Promise((resolve) => {
setTimeout(resolve, delay, {
timeout: true,
});
});
return Promise.race([
fetch(url, options),
timer
]).then(response => {
if (response.timeout) {
onTimeout();
}
return response;
});
}
If you are using maven try to maven update all projects and force for snapshots. It will clean as well and rebuilt all classpath.. It solved my problem..
Had similar problem with the SVN 1.6.5 on Mac 10.6.5, upgraded to SVN 1.6.9 and the commit succeeded.
There is a lot of possibilities for LaFs :
Or you can just run power-shell command to append extra folder to the existing path:
$env:Path += ";C:\temp\terraform"
It's just a principle about exposure APIs.
Using python, It's a good idea to avoid exposure API in outer space(module or class), function is a good encapsulation place.
It could be a good idea. when you ensure
Even though, Abuse this technique may cause problems and implies a design flaw.
Just from my exp, Maybe misunderstand your question.
There is also another easy way to check the latest version without going to NPM if you are using VS Code.
In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions
Or, if you want to use minimal "powers" (e.g. if you don't want a cascade delete) to achieve what you want, use
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
...
@Cascade({CascadeType.SAVE_UPDATE})
private Set<Child> children;
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
You need to use the autoGenerate
property
Your primary key annotation should be like this:
@PrimaryKey(autoGenerate = true)
Reference for PrimaryKey.
The Mono project dropped Windows XP support and "forgot" to mention it. Although they still claim Windows XP SP2 is the minimum supported version, it is actually Windows Vista.
The last version of Mono to support Windows XP was 3.2.3.
As of C++11, the standard C++ library provides the function std::to_string(arg)
with various supported types for arg
.
git archive --format=tar --remote=<repository URL> HEAD | tar xf -
taken from here
Here's a simple function. It generates a data frame and automatically uses the names of the vectors as values for the first column.
myfunc <- function(a, b, names = NULL) {
setNames(data.frame(c(rep(deparse(substitute(a)), length(a)),
rep(deparse(substitute(b)), length(b))), c(a, b)), names)
}
An example:
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
myfunc(x, y, c(x_name, y_name))
cond rating
1 x 1
2 x 2
3 x 3
4 y 100
5 y 200
6 y 300
I used org.json built-in methods to pretty-print the data.
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
The order of fields in JSON is random per definition. A specific order is subject to parser implementation.
function listCookies() {
let cookies = document.cookie.split(';')
cookies.map((cookie, n) => console.log(`${n}:`, decodeURIComponent(cookie)))
}
function findCookie(e) {
let cookies = document.cookie.split(';')
cookies.map((cookie, n) => cookie.includes(e) && console.log(decodeURIComponent(cookie), n))
}
This is specifically for the window you're in. Tried to keep it clean and concise.
I used ADAL.NET/ Microsoft Identity Platform to achieve this. The advantage of using it was that we get a nice wrapper around the code to acquire AccessToken
and we get additional features like Token Cache
out-of-the-box. From the documentation:
Why use ADAL.NET ?
ADAL.NET V3 (Active Directory Authentication Library for .NET) enables developers of .NET applications to acquire tokens in order to call secured Web APIs. These Web APIs can be the Microsoft Graph, or 3rd party Web APIs.
Here is the code snippet:
// Import Nuget package: Microsoft.Identity.Client
public class AuthenticationService
{
private readonly List<string> _scopes;
private readonly IConfidentialClientApplication _app;
public AuthenticationService(AuthenticationConfiguration authentication)
{
_app = ConfidentialClientApplicationBuilder
.Create(authentication.ClientId)
.WithClientSecret(authentication.ClientSecret)
.WithAuthority(authentication.Authority)
.Build();
_scopes = new List<string> {$"{authentication.Audience}/.default"};
}
public async Task<string> GetAccessToken()
{
var authenticationResult = await _app.AcquireTokenForClient(_scopes)
.ExecuteAsync();
return authenticationResult.AccessToken;
}
}
It's new to SQL 2005 and offers a simplified way to group objects, especially for the purpose of securing the objects in that "group".
The following link offers a more in depth explanation as to what it is, why we would use it:
Understanding the Difference between Owners and Schemas in SQL Server
Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.
random_int(100000, 999999)
Note that here we use random_int
, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes
was also introduced in PHP 7 and likewise uses a cryptographic random generator.
Many other solutions for random value generation, including those involving time()
, microtime()
, uniqid()
, rand()
, mt_rand()
, str_shuffle()
, and array_rand()
, are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int
or random_bytes
rather than rand()
, mt_rand()
, str_shuffle()
, etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?
I also list other things to keep in mind when generating unique identifiers, especially random ones.
In my case setting width to all divs helped:
.page-content div {
width: auto !important;
max-width: 99%;
}
See my comment on Ctford's reply.
I'd think the easy way to lighten a color would be to take each of the RGB components, add to 0xff and divide by 2. If that doesn't give the exact results you want, take 0xff minus the current value times some constant and then add back to the current value. For example if you want to shift 1/3 of the way toward white, take (0xff - current)/3+current.
You'd have to play with it to see what results you got. I would worry that with this simple a formula, a factor big enough to make dark colors fade nicely might make light colors turn completely white, while a factor small enough to make light colors only lighten a little might make dark colors not lighten enough.
Still, I think going by a fraction of the distance to white is more promising than a fixed number of steps.
In some cases you may need to move the focus to the next field manually :
focusSearch(FOCUS_DOWN).requestFocus();
You might need this if, for example, you have a text field that opens a date picker on click, and you want the focus to automatically move to the next input field once a date is selected by the user and the picker closes. There's no way to handle this in XML, it has to be done programmatically.
You could wrap your return value in the Boolean function
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
I had same problem with 'parallax' plugin.
I changed jQuery librery version to *jquery-1.6.4*
from *jquery-1.10.2*.
And error cleared.
Oracle SQL Developer doesn't support connections to PostgreSQL. Use pgAdmin to connect to PostgreSQL instead, you can get it from the following URL http://www.pgadmin.org/download/windows.php
This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.
The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string
is not the same type as string
so the declaration's signature differed from the definition's and this message was spit out.
As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.
Without java-8, you'll be able to do this in one line Commons collections, and the Closure class
List<Item> list;
@SuppressWarnings("unchecked")
Map<Key, Item> map = new HashMap<Key, Item>>(){{
CollectionUtils.forAllDo(list, new Closure() {
@Override
public void execute(Object input) {
Item item = (Item) input;
put(i.getKey(), item);
}
});
}};
I needed a multilevel dropdown menu in css. I couldn't find an error-free menu that I searched. Then I created a menu instance using the Css hover transition effect.I hope it will be useful for users.
#AnaMenu {
width: 920px; /* Menu width */
height: 30px; /* Menu height */
position: relative;
background: #0080ff;
margin:0 0 0 -30px;
padding: 10px 0 0 15px;
border: 0;
}
#nav { display:block;background:transparent;
margin:0;padding: 0;border: 0 }
#nav ul { float: none; display:block;
height:35px;
margin:16px 0 0 0;border:0;
padding: 15px 0 3px 0;
overflow: visible;
}
#nav ul li{border:0;}
#nav li a, #nav li a:link, #nav li a:visited {height:23px;
-webkit-transition: background-color 1s ease-out;
-moz-transition: background-color 1s ease-out;
-o-transition: background-color 1s ease-out;
transition: background-color 1s ease-out;
color: #fff; /* Change colour of link */
display: block;border:0;border-right:1px solid #efefef;text-decoration:none;
margin: 0;letter-spacing:0.6px;
padding: 2px 10px 2px 10px;
}
#nav li a:hover, #nav li a:active {
color: #fff;
margin: 0;background:#6ab5ff;border:0;
padding: 2px 10px 2px 10px;
}
#nav li li a, #nav li li a:link, #nav li li a:visited {
background: #fafafa;
width: 200px;
color: #05429b; /* Link text color */
float: none;
margin: 0;border-bottom:1px solid #9be6e9;
padding: 8px 15px;
}
#nav li li a:hover, #nav li li a:active {
background: #2793ff; /* Mouse hover color */
color: #fff;
padding: 8px 15px;border:0 ;text-decoration:none}
#nav li {float: none; display: inline-block;margin: 0; padding: 0; border: 0 }
#nav li ul { z-index: 9999; position: absolute; left: -999em; height: auto; width: 200px; margin: 0; padding: 0;background:transparent}
#nav li ul a { width: 170px;border:0;text-decoration:none;font-size:14px }
#nav li ul ul { margin: -40px 0 0 230px }
#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li.sfhover ul ul, #nav li.sfhover ul ul ul {left: -999em; }
#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul { left: auto; }
#nav li:hover, #nav li.sfhover {position: static;}
Multilevel dropdown menu can be used in Blogger blogs. Details at : Css multilevel dropdown menu
I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
php.net: http://php.net/manual/pt_BR/function.error-reporting.php
Parameters are a copy of the original reference. So, you can change values, but cannot change the original reference.
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
I did all the changes mentioned in every other answer and none worked. What did I learn? Enable and Continue exists in both the Tools > Options > Debugging menu and also in the Project settings. After I checked both, Enable and Continue worked for me.
The easiest way would be to use the readme.html
file that comes with every WordPress installation (unless you deleted it).
http://example.com/readme.html
Note: it looks like the readme.html
file no longer outputs the current WordPress version. So, there is no way, for now, to see the current WordPress version without logging into the dashboard.
CSS is the styling language that any browser understands to style webpages.
SCSS is a special type of file for SASS
, a program written in Ruby that assembles CSS
style sheets for a browser, and for information, SASS
adds lots of additional functionality to CSS
like variables, nesting and more which can make writing CSS
easier and faster.
SCSS files are processed by the server running a web app to output a traditional CSS
that your browser can understand.
Variant of Tim's one, good only on some implementations of Regex: ^.*?_
var subjectString = "3.04_somename.jpg";
var resultString = Regex.Replace(subjectString,
@"^ # Match start of string
.*? # Lazily match any character, trying to stop when the next condition becomes true
_ # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
OK I have answered my own question (but is it the best way?)
This is how to run a method when you click or tap on some text in a TextView:
package com.textviewy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class TextyView extends Activity implements OnClickListener {
TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.TextView01);
t.setOnClickListener(this);
}
public void onClick(View arg0) {
t.setText("My text on click");
}
}
and my main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<TextView android:text="This is my first text"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:textStyle="bold"
android:textSize="28dip"
android:editable = "true"
android:clickable="true"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
If you have configuration like this:
<VirtualHost *:80>
ServerName example.com
DocumentRoot "/var/www/example.com"
<FilesMatch "\.php$">
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
</VirtualHost>
Uncomment next lines in your httpd.conf
LoadModule proxy_module lib/httpd/modules/mod_proxy.so
LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so
It works for me
The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).
In almost all cases I suggest using an EnumMap
instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).
private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
pageIndexes.put(Page.SIGN_CREATE, 1);
//etc., ...
int createIndex = pageIndexes.get(Page.SIGN_CREATE);
It's typically incredibly efficient, too.
Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.
Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap
instead of ordinal indexing.
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
in ActivitySaludo
, this line,
setContentView(txtCambiado);
you must set the content view for the activity only once.
Swift 5:
func open(scheme: String) {
if let url = URL(string: scheme) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],
completionHandler: {
(success) in
print("Open \(scheme): \(success)")
})
} else {
let success = UIApplication.shared.openURL(url)
print("Open \(scheme): \(success)")
}
}
}
Usage:
open(scheme: "http://www.bing.com")
Reference:
Remove the semi-colons from your if
statements, otherwise the code that follows will be free standing and will always execute:
if (operation == "+");
^
Also use .equals
for Strings
, ==
compares Object
references:
if (operation.equals("+")) {
As per the DOM structure you can use below code:
var x = document.getElementById('mySelect');
var txt = "";
var val = "";
for (var i = 0; i < x.length; i++) {
txt +=x[i].text + ",";
val +=x[i].value + ",";
}
If you have large dataset which cannot be easily put to the script using dput()
,
post your data to pastebin and load them using read.table
:
d <- read.table("http://pastebin.com/raw.php?i=m1ZJuKLH")
Inspired by @Henrik.
I used the code below to add a certain time interval to the current time.
int interval = 30;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Calendar time = Calendar.getInstance();
Log.i("Time ", String.valueOf(df.format(time.getTime())));
time.add(Calendar.MINUTE, interval);
Log.i("New Time ", String.valueOf(df.format(time.getTime())));
The problem is that you are setting the Content-Type
by yourself, let it be blank. Google Chrome will do it for you. The multipart Content-Type
needs to know the file boundary, and when you remove the Content-Type
, Postman will do it automagically for you.
let originalString = "http://www.ihtc.cc?name=htc&title=iOS?????"
1. encodingQuery:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
result:
"http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
2. encodingURL:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
result:
"http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
I believe my answer covers your new concerns about handling any type of line endings since both "\r\n"
and "\r"
are converted to Linux standard "\n"
before parsing the lines.
To support the "\r"
EOL character along with the regular "\n"
, and "\r\n"
from Windows, here's what I would do:
line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
print "#{line_num += 1} #{line}"
end
Of course this could be a bad idea on very large files since it means loading the whole file into memory.
If you want to do it in the adapter, you can simply do this:
itemView.setOnLongClickListener(new View.OnLongClickListener()
{
@Override
public boolean onLongClick(View v) {
Toast.makeText(mContext, "Long pressed on item", Toast.LENGTH_SHORT).show();
}
});
Try this code:
Bitmap bitmap = null;
File f = new File(_path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
public ActionResult ViewNextItem(int? id)
makes the id
integer a nullable type, no need for string<->int conversions.
I had a similar problem. I had to schedule bunch of tasks that should be executed during a day using ScheduledExecutorService
.
This was solved by one task starting at 3:30 AM scheduling all other tasks relatively to his current time. And rescheduling himself for the next day at 3:30 AM.
With this scenario daylight savings are not an issue anymore.
PyCharm Version 3.4.1(For all files in the project):
File -> Preferences -> Editor (IDE Settings) -> Appearance -> mark 'Show line numbers'
PyCharm Version 3.4.1(only for existing file in the project):
View -> Active Editor -> Show Line Numbers
I was not satisfied with @Abhrabm answer because:
It was only preventing negative numbers from being entered from up/down arrows, whereas user can type negative number from keyboard.
Solution is to prevent with key code:
// Select your input element._x000D_
var number = document.getElementById('number');_x000D_
_x000D_
// Listen for input event on numInput._x000D_
number.onkeydown = function(e) {_x000D_
if(!((e.keyCode > 95 && e.keyCode < 106)_x000D_
|| (e.keyCode > 47 && e.keyCode < 58) _x000D_
|| e.keyCode == 8)) {_x000D_
return false;_x000D_
}_x000D_
}
_x000D_
<form action="" method="post">_x000D_
<input type="number" id="number" min="0" />_x000D_
<input type="submit" value="Click me!"/>_x000D_
</form>
_x000D_
Clarification provided by @Hugh Guiney:
What key codes are being checked:
So this script is preventing invalid key from being entered in input.
The named ones are all raster graphics, but beside that don't forget the more and more important vectorgraphics. There are compressed and uncompressed types (in a more or less way), but they're all lossless. Most important are:
var x = from row in table
where row.ID == 0
select row
Supposing you have a DataTable that knows about the rows, other wise you'll need to use the row index:
where row[rowNumber] == 0
In this instance you'd also want to use the select to place the row data into an anonymous class or a preprepared class (if you want to pass it to another method)
ANSWER TO OWN QUESTION: I thought it would be useful to answer my own question as I have learnt a lot from the answers. This answer is intended to help those - like me - who do not have a complete understanding of the issues. If I use incorrect language please correct me.
true
and false
. It is the absence of a pointer to objects. Therefore to think that Boolean is 3-valued is fundamentally wrongThe syntax for Boolean is abbreviated and conceals the fact that the reference points to Objects:
Boolean a = true;
conceals the fact that true
is an object. Other equivalent assignments might be:
Boolean a = Boolean.TRUE;
or
Boolean a = new Boolean(true);
The abbreviated syntax
if (a) ...
is different from most other assignments and conceals the fact that a might be an object reference or a primitive. If an object it is necessary to test for null
to avoid NPE. For me it is psychologically easier to remember this if there is an equality test:
if (a == true) ...
where we might be prompted to test for null. So the shortened form is only safe when a
is a primitive.
For myself I now have the recommendations:
Boolean
from a method as it could be null
. Only return boolean
.Boolean
for wrapping elements in containers, or arguments to methods where objects are requiredFile.open("my/file/path", "r") do |f|
f.each_line do |line|
puts line
end
end
# File is closed automatically at end of block
It is also possible to explicitly close file after as above (pass a block to open
closes it for you):
f = File.open("my/file/path", "r")
f.each_line do |line|
puts line
end
f.close
Here is what worked here: Simulates Excel 2003 (Save as CSV format)
SELECT
REPLACE( IFNULL(notes, ''), '\r\n' , '\n' ) AS notes
FROM sometables
INTO OUTFILE '/tmp/test.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';
Your fundamental problem is that grep
works one line at a time - so it cannot find a SELECT statement spread across lines.
Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.
I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.
In outline, for a single file:
$/ = "\n\n"; # Paragraphs
while (<>)
{
if ($_ =~ m/SELECT.*customerName.*FROM/mi)
{
printf file name
go to next file
}
}
That needs to be wrapped into a sub that is then invoked by the methods of File::Find.
If possible you should change the data type of the column to a number if you only store numbers anyway.
If you can't do that then cast your column value to an integer
explicitly with
select col from yourtable
order by cast(col as unsigned)
or implicitly for instance with a mathematical operation which forces a conversion to number
select col from yourtable
order by col + 0
BTW MySQL converts strings from left to right. Examples:
string value | integer value after conversion
--------------+--------------------------------
'1' | 1
'ABC' | 0 /* the string does not contain a number, so the result is 0 */
'123miles' | 123
'$123' | 0 /* the left side of the string does not start with a number */
Aggregate used to sum columns in a multi dimensional integer array
int[][] nonMagicSquare =
{
new int[] { 3, 1, 7, 8 },
new int[] { 2, 4, 16, 5 },
new int[] { 11, 6, 12, 15 },
new int[] { 9, 13, 10, 14 }
};
IEnumerable<int> rowSums = nonMagicSquare
.Select(row => row.Sum());
IEnumerable<int> colSums = nonMagicSquare
.Aggregate(
(priorSums, currentRow) =>
priorSums.Select((priorSum, index) => priorSum + currentRow[index]).ToArray()
);
Select with index is used within the Aggregate func to sum the matching columns and return a new Array; { 3 + 2 = 5, 1 + 4 = 5, 7 + 16 = 23, 8 + 5 = 13 }.
Console.WriteLine("rowSums: " + string.Join(", ", rowSums)); // rowSums: 19, 27, 44, 46
Console.WriteLine("colSums: " + string.Join(", ", colSums)); // colSums: 25, 24, 45, 42
But counting the number of trues in a Boolean array is more difficult since the accumulated type (int) differs from the source type (bool); here a seed is necessary in order to use the second overload.
bool[][] booleanTable =
{
new bool[] { true, true, true, false },
new bool[] { false, false, false, true },
new bool[] { true, false, false, true },
new bool[] { true, true, false, false }
};
IEnumerable<int> rowCounts = booleanTable
.Select(row => row.Select(value => value ? 1 : 0).Sum());
IEnumerable<int> seed = new int[booleanTable.First().Length];
IEnumerable<int> colCounts = booleanTable
.Aggregate(seed,
(priorSums, currentRow) =>
priorSums.Select((priorSum, index) => priorSum + (currentRow[index] ? 1 : 0)).ToArray()
);
Console.WriteLine("rowCounts: " + string.Join(", ", rowCounts)); // rowCounts: 3, 1, 2, 2
Console.WriteLine("colCounts: " + string.Join(", ", colCounts)); // colCounts: 3, 2, 1, 2
You could use lsof
to see what application is listening on port 80:
sudo lsof -i TCP:80
Use Time YYYYDDDD
(Year + Day of Year) as prefix. This decreases database fragmentation in tables and indexes. This method returns byte[40]
. I used it in a hybrid environment where the Active Directory SID (varbinary(85)
) is the key for LDAP users and an application auto-generated ID is used for non-LDAP Users. Also the large number of transactions per day in transactional tables (Banking Industry) cannot use standard Int
types for Keys
private static final DecimalFormat timeFormat4 = new DecimalFormat("0000;0000");
public static byte[] getSidWithCalendar() {
Calendar cal = Calendar.getInstance();
String val = String.valueOf(cal.get(Calendar.YEAR));
val += timeFormat4.format(cal.get(Calendar.DAY_OF_YEAR));
val += UUID.randomUUID().toString().replaceAll("-", "");
return val.getBytes();
}
Authentication
is a process of verification:
digital signature
[About]Authorization
is the next step after Authentication
. It is about permissions/roles/privileges to resources. OAuth
(Open Authorization) is an example of Authorization
To be clearer (as i read this thread but didn't SEE the solution, also if it was here!), I have the same problem and found the cause: I were modifying the wrong php.ini!
Yes, there are 2 php.ini files in MAMP:
The right php.ini file is the second: Applications/MAMP/bin/php/php5.5.10/conf/php.ini
To prove this, create a .php file (call it as you like, for example "info.php") and put into it a simple phpinfo()
<?php
echo phpinfo();
Open it in your browser and search for "Loaded Configuration File": mine is "/Applications/MAMP/bin/php/php5.5.10/conf/php.ini"
The error was here; i edited Applications/MAMP/conf/php5.5.10/php.ini but this is the wrong file to modify! Infact, the right php.ini file is the one in the bin directory.
Take care of this so small difference that caused me literally 1 and a half hours of headaches!
Check your MySQL Port number 3306.
Is there any other MySQL Install in your system on same port ?
If any installation found the change the port number to any number between 3301-3309 (except 3306)
user name : root
password : ' ' (Empty)
If you want to downgrade php version, just simply edit yout .htaccess file. Like you want to downgrade any php version to 5.6, just add this into .htaccess file
<FilesMatch "\.(php4|php5|php7|php3|php2|php|phtml)$">
etHandler application/x-lsphp56
</FilesMatch>
You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.
The following would work.
<td colspan="2" class="cell">
<asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>
</td>
In your CSS file:
.cell
{
text-align:left;
}
.righttextbox
{
float:right;
}
grep -nr search_string search_dir
will do a RECURSIVE (meaning the directory and all it's sub-directories) search for the search_string. (as correctly answered by usta).
The reason you were not getting any anwers with your friend's suggestion of:
grep -nr string
is because no directory was specified. If you are in the directory that you want to do the search in, you have to do the following:
grep -nr string .
It is important to include the '.' character, as this tells grep to search THIS directory.
I had an issue when using @Configuration, @EnableAutoConfiguration and @ComponentScan while trying to exclude specific configuration classes, the thing is it didn't work!
Eventually I solved the problem by using @SpringBootApplication, which according to Spring documentation does the same functionality as the three above in one annotation.
Another Tip is to try first without refining your package scan (without the basePackages filter).
@SpringBootApplication(exclude= {Foo.class})
public class MySpringConfiguration {}
If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available
and /etc/nginx/sites-enabled
, do the following:
/etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
This tells nginx to pull in any files in the conf.d
directory that end in .conf
. (I know: it's weird that a directory can have a .
in it.)conf.d
directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data. /etc/nginx/sites-available
) into the directory conf.d
.Any .conf
files that you put into the conf.d
directory from here on out will become active as long as you reload/restart nginx after.
Note: You can use the conf.d
and sites-enabled
+ sites-available
method concurrently if you wish. I like to test on my dev box using conf.d
. Feels faster than symlinking and unsymlinking.
IF privileges are given to a user through some roles, then below SQL can be used
select * from ROLE_ROLE_PRIVS where ROLE = 'ROLE_NAME';
select * from ROLE_TAB_PRIVS where ROLE = 'ROLE_NAME';
select * from ROLE_SYS_PRIVS where ROLE = 'ROLE_NAME';
i would do this:
<li *ngFor="let item of data" (click)='onclick(item)'>{{item.picture.url}}</li>
http://www.w3schools.com/tags/tag_ul.asp
ul {
display: block;
list-style-type: disc;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 0;
margin-right: 0;
padding-left: 40px;
}
in case the above does not work for you. for me this did not for some reasons;
the UNIX numbers i am working on are from the Mozilla place.sqlite dates.
to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)
Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked
I've used Perfect Full Page Background Image to accomplish this on a previous site.
You can use background-size: cover; if you only need to support modern browsers.