Change the number of @grid-columns
. Then use -offset
. Changing the number of columns will allow you to control the amount of space between columns. E.g.
variables.less (approx line 294).
@grid-columns: 20;
someName.html
<div class="row">
<div class="col-md-4 col-md-offset-1">First column</div>
<div class="col-md-13 col-md-offset-1">Second column</div>
</div>
Mongoose Model
s inherit from Document
s, which have a toObject()
method. I believe what you're looking for should be the result of doc.toObject()
.
http://mongoosejs.com/docs/api.html#document_Document-toObject
OK so I created a static async method. That disabled the control that launches the action and changes the application cursor. It runs the action as a task and waits for to finish. Control returns to the caller while it waits. So the application remains responsive, even while the busy icon spins.
async public static void LengthyOperation(Control control, Action action)
{
try
{
control.Enabled = false;
Application.UseWaitCursor = true;
Task doWork = new Task(() => action(), TaskCreationOptions.LongRunning);
Log.Info("Task Start");
doWork.Start();
Log.Info("Before Await");
await doWork;
Log.Info("After await");
}
finally
{
Log.Info("Finally");
Application.UseWaitCursor = false;
control.Enabled = true;
}
Here's the code form the main form
private void btnSleep_Click(object sender, EventArgs e)
{
var control = sender as Control;
if (control != null)
{
Log.Info("Launching lengthy operation...");
CursorWait.LengthyOperation(control, () => DummyAction());
Log.Info("...Lengthy operation launched.");
}
}
private void DummyAction()
{
try
{
var _log = NLog.LogManager.GetLogger("TmpLogger");
_log.Info("Action - Sleep");
TimeSpan sleep = new TimeSpan(0, 0, 16);
Thread.Sleep(sleep);
_log.Info("Action - Wakeup");
}
finally
{
}
}
I had to use a separate logger for the dummy action (I am using Nlog) and my main logger is writing to the UI (a rich text box). I wasn't able to get the busy cursor show only when over a particular container on the form (but I didn't try very hard.) All controls have a UseWaitCursor property, but it doesn't seem have any effect on the controls I tried (maybe because they weren't on top?)
Here's the main log, which shows things happening in the order we expect:
16:51:33.1064 Launching lengthy operation...
16:51:33.1215 Task Start
16:51:33.1215 Before Await
16:51:33.1215 ...Lengthy operation launched.
16:51:49.1276 After await
16:51:49.1537 Finally
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
F function keys (F1,F2,F3,F4,F5 etc.) can be assigned to macros with the following codes :
Sub A_1()
Call sndPlaySound32(ThisWorkbook.Path & "\a1.wav", 0)
End Sub
Sub B_1()
Call sndPlaySound32(ThisWorkbook.Path & "\b1.wav", 0)
End Sub
Sub C_1()
Call sndPlaySound32(ThisWorkbook.Path & "\c1.wav", 0)
End Sub
Sub D_1()
Call sndPlaySound32(ThisWorkbook.Path & "\d1.wav", 0)
End Sub
Sub E_1()
Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
End Sub
Sub auto_open()
Application.OnKey "{F1}", "A_1"
Application.OnKey "{F2}", "B_1"
Application.OnKey "{F3}", "C_1"
Application.OnKey "{F4}", "D_1"
Application.OnKey "{F5}", "E_1"
End Sub
You can do one of two things:
Call getResources()
and iterate through the returned collection of URLs, reading them as manifests until you find yours:
Enumeration<URL> resources = getClass().getClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
try {
Manifest manifest = new Manifest(resources.nextElement().openStream());
// check that this is your manifest and do what you need or get the next one
...
} catch (IOException E) {
// handle
}
}
You can try checking whether getClass().getClassLoader()
is an instance of java.net.URLClassLoader
. Majority of Sun classloaders are, including AppletClassLoader
.
You can then cast it and call findResource()
which has been known - for applets, at least - to return the needed manifest directly:
URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
// do stuff with it
...
} catch (IOException E) {
// handle
}
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
Yes you can:
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table1;
TRUNCATE table2;
SET FOREIGN_KEY_CHECKS = 1;
With these statements, you risk letting in rows into your tables that do not adhere to the FOREIGN KEY
constraints.
When you want to show years and the remaining days:
var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
Here's a way!
<?php
$url = "http://www.google.com";
if(@file_get_contents($url)){
echo "Url Exists!";
} else {
echo "Url Doesn't Exist!";
}
?>
This simple script simply makes a request to the URL for its source code. If the request is completed successfully, it will output "URL Exists!". If not, it will output "URL Doesn't Exist!".
I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).
So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec()
built-in function on the decoded message. If I remember correctly my one-liner for this was:
stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]
It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.
The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.
For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.
In case someone needs ternary operator with implicit casting:
/**'[_t]' for ternary operator*/
@Suppress("FunctionName")
@OptIn(ExperimentalContracts::class)
fun <T> _t(bool: Boolean, onTrue: T, onFalse: T): T
{
contract { returns() implies bool }
return if (bool) onTrue else onFalse
}
Although not sure how useful this is
In my case, I had to delete all remotes (there were multiple for some unexplained reason), add the remote again, and commit with -f.
$ git remote
origin
upstream
$ git remote remove upstream
$ git remote remove origin
$ git remote add origin <my origin>
$ git push -u -f origin main
I don't know if the -u
flag contributed anything, but it doesn't hurt either.
In Notepad++ v7.8.9 you can use the Tab
key to increase the indention level, and use Shift + Tab
to decrease the indentation level.
from the current directory provide the full path to the script directory to execute the command
/root/server/user/home/bin/script.sh
Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.
I'm surprised in a TypeScript thread no one gave valid TypeScript function with typing supported. Here's variation of @user8363 solution:
const isStringNumber = (value: string) => isNaN(Number(value)) === false;
function enumToArray<T extends {}>(givenEnum: T) {
return (Object.keys(givenEnum).filter(isStringNumber) as (keyof T)[]).map(
(key) => givenEnum[key]
);
}
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = a + b;
alert(sum);
}
</script>
Just put the initial value into a data attribute when you create the textbox, eg
HTML
<input id="my-textbox" type="text" data-initial-value="6" value="6" />
JQuery
$("#my-textbox").change(function () {
var oldValue = $(this).attr("data-initial-value");
var newValue = $(this).val();
});
You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.
shorter way ....
var a = new Test { Id = 1 , Name = "A" , date = DateTime.Now};
var b = new Test { Id = 1 , Name = "AXXX", date = DateTime.Now };
var compare = string.Join("",a.GetType().GetProperties().Select(x => x.GetValue(a)).ToArray())==
string.Join("",b.GetType().GetProperties().Select(x => x.GetValue(b)).ToArray());
The difference is that in the first example, the program will block in the first line. The next line (console.log
) will have to wait.
In the second example, the console.log
will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.
So, in a nutshell: The first example will block, while the second won't.
The output of the following two examples:
// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");
Would be:
Query finished
Next line
Next line
Query finished
Note
While Node itself is single threaded, there are some task that can run in parallel. For example, File System operations occur in a different process.
That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code. In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data.
You can read more about this here: How the single threaded non blocking IO model works in Node.js
keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]]
means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]]
)
You must convert your actual label (e.g. 'cancer', 'not cancer'
) into binary encoding (0
for 'cancer', 1
for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]]
as having class label 'cancer'
For me its now :
docker restart $(docker ps -a -q)
EDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.
If you use "Git for Windows"
>cd c:\Program Files\Git\etc\ssh\
add to ssh_config following:
AddKeysToAgent yes
IdentityFile ~/.ssh/id_rsa
IdentityFile ~/.ssh/id_rsa_test
ps. you need ssh version >= 7.2 (date of release 2016-02-28)
16kb is about right; if you're using gigabit ethernet, each packet could be 9kb in size.
Not only does it depend on what keeps your users happy, but how much development time do you have? What kind of resources can you throw at the problem (software, hardware, and people)?
I don't mind a couple-few second delay for hosted applications if they're doing something "complex". If it's really simple, delays bother me.
In my case the problem was that one of the queries included in the transaction was raising an exception, and even though the exception was "gracefully" handled, it still managed to roll back the entire transaction.
My pseudo-code was like:
var transaction = connection.BeginTransaction();
for(all the lines in a file)
{
try{
InsertLineInTable(); // INSERT statement might fail and throw an exception
}
catch {
// notify the user about the error on line x and continue
}
}
// Commit and Rollback will fail if one of the queries
// in InsertLineInTable threw an exception
if(CheckTableForErrors())
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
StringBuilder is a better option to concat a huge data string because the StringBuilder is a mutable string type and StringBuilder object is an immutable type, that means StringBuilder never create a new instance of object while concat the string.
If we are using string instead of StringBuilder to achieve for concatenation then it will create new instance in memory every time.
This happens when you add a framework to your project and unintentionally copy the framework into your project directory.
The fix is to check your project directory (where you store your project on disk) for any iphone SDK *.Framework files and delete them.
Project will build fine afterwards.
You can try this:
SELECT EXTRACT(YEAR FROM field) FROM table WHERE id=1
You can create a camera intent and call it as startActivityForResult(intent).
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Yes, we do have a clean way in ruby.
discount.to_f.zero?
This check handles good amount of cases i.e. discount may be nil, discount may be int 0, discount may be float 0.0, discount may be string "0.0", "0".
%W
and %w
allow you to create an Array of strings without using quotes and commas.
Problem Cause : The process of the current program is still running without interuption. (This is the reason why you haven't got this issue after a restart)
The fix is simple : Go to cmd and type the command taskkill -im process-name.exe -f
Eg:
taskkill -im demo.exe -f
here,
demo - is my program name
Change your linter to - flake8 and problem will go away.
you need to use getResources() method, try to use following code
View someView = findViewById(R.id.screen);
View root = someView.getRootView();
root.setBackgroundColor(getResources().getColor(color.white));
Edit::
getResources.getColor() is deprecated so, use like below
root.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal
I got this error the very first time I tried to make a provisioning profile by following the Provisioning Assistant and it turns out they fail to mention the WWDR Intermediate Certificate
. I installed it and it worked fine for me.
Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.
This error indicates your package_name
in your google-services.json
might be wrong. I personally had this issue when I used
buildTypes {
...
debug {
applicationIdSuffix '.debug'
}
}
in my build.gradle
. So, when I wanted to debug, the name of the application was ("all of a sudden") app.something.debug
instead of app.something
. I was able to run the debug when I changed the said package_name
...
You can set a default style for the entire workbook (all worksheets):
$objPHPExcel->getDefaultStyle()
->getBorders()
->getTop()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getBottom()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getLeft()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getRight()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
or
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);
And this can be used for all style properties, not just borders.
But column autosizing is structural
rather than stylistic
, and has to be set for each column on each worksheet individually.
EDIT
Note that default workbook style only applies to Excel5 Writer
First install beautiful soup version 4. write command in the terminal window:
pip install beautifulsoup4
then import the BeutifulSoup library
In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':
', exe: F:
, which will take you to the drive named 'F' on your machine. Then using the command cd
to navigate your way inside that drive as you normally would.
@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg')
before importing matplotlib.pyplot
, and then continue as normal.
E.g.
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')
You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.
Alternately, you can just set the backend parameter in your .matplotlibrc
file to automatically have matplotlib.pyplot
use the given renderer.
In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below
val MY_CONSTANT = "Constants"
And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.
companion object{
const val MY_CONSTANT = "Constants"
}
** Sub queries may have a bad impact on performance when used with large datasets **
Original query
SELECT wp_posts.*
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
GROUP BY wp_posts.post_author
ORDER BY wp_posts.post_date DESC;
Modified query
SELECT p.post_status,
p.post_type,
Max(p.post_date),
p.post_author
FROM wp_posts P
WHERE p.post_status = "publish"
AND p.post_type = "post"
GROUP BY p.post_author
ORDER BY p.post_date;
becasue i'm using max
in the select clause
==> max(p.post_date)
it is possible to avoid sub select queries and order by the max column after the group by.
Your GetHashCode
implementation always returns the same value. Distinct
relies on a good hash function to work efficiently because it internally builds a hash table.
When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1
In your code, the solution is to forward GetHashCode
to Class_reglement.Numf.GetHashCode
and implement it appropriately there.
Apart from that, your Equals
method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):
public bool Equals(Class_reglement x, Class_reglement y)
{
return x.Numf == y.Numf;
}
Lastly, the ToList
call is unnecessary and time-consuming: AddRange
accepts any IEnumerable
so conversion to a List
isn’t required. AsEnumerable
is also redundant here since processing the result in AddRange
will cause this anyway.
1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.
Try like this:
from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
return Response(xml, mimetype='text/xml')
The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8).
Response (and request) objects are documented here: http://werkzeug.pocoo.org/docs/wrappers/
In Swift 4 you can set the border color and width to UIControls using below code.
let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0
< Swift 4, You can set UIView's border width and border color using the below code.
yourView.layer.borderWidth = 1
yourView.layer.borderColor = UIColor.red.cgColor
Direct answer: No
But you can simulate reference with wrappers.
And do the following:
void changeString( _<String> str ) {
str.s("def");
}
void testRef() {
_<String> abc = new _<String>("abc");
changeString( abc );
out.println( abc ); // prints def
}
Out
void setString( _<String> ref ) {
str.s( "def" );
}
void testOut(){
_<String> abc = _<String>();
setString( abc );
out.println(abc); // prints def
}
And basically any other type such as:
_<Integer> one = new <Integer>(1);
addOneTo( one );
out.println( one ); // May print 2
Deleting the .git
folder is probably the easiest path since you don't want/need the history (as Stephan said).
So you can create a new repo from your latest commit: (How to clone seed/kick-start project without the whole history?)
git clone <git_url>
then delete .git
, and afterwards run
git init
Or if you want to reuse your current repo: Make the current commit the only (initial) commit in a Git repository?
Follow the above steps then:
git add .
git commit -m "Initial commit"
Push to your repo.
git remote add origin <github-uri>
git push -u --force origin master
Instead of doing all these.. cant you use a simpler approach as shown below.
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
You can get the entire walkthrough here
For complex splitting you could use a regex creating a match collection.
I would add mnoGoSearch to the list. Extremely performant and flexible solution, which works as Google : indexer fetches data from multiple sites, You could use basic criterias, or invent Your own hooks to have maximal search quality. Also it could fetch the data directly from the database.
The solution is not so known today, but it feets maximum needs. You could compile and install it or on standalone server, or even on Your principal server, it doesn't need so much ressources as Solr, as it's written in C and runs perfectly even on small servers.
In the beginning You need to compile it Yourself, so it requires some knowledge. I made a tiny script for Debian, which could help. Any adjustments are welcome.
As You are using Django framework, You could use or PHP client in the middle, or find a solution in Python, I saw some articles.
And, of course mnoGoSearch is open source, GNU GPL.
I made a small library that lets you easily use a throbber without images.
It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.
// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);
// Start the throbber.
throbber.play();
// Pause the throbber.
throbber.pause();
I was so confusing first time, but I propose you final working solution for Windows:
1) Open cmd and go to your Java/jdk/bin directory (just press cd ..
to go one folder back and cd NAME_FOLDER
to go one folder forward), in my case, final folder: C:\Program Files\Java\jdk1.8.0_73\bin>
2) Now type this command keytool -list -v -keystore C:\Users\YOUR_WINDOWS_USER\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
In Swift 4.2:
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)
I had to do this in that order:
Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD
These appear to be seconds since epoch.
In [20]: df = DataFrame(data['values'])
In [21]: df.columns = ["date","price"]
In [22]: df
Out[22]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date 358 non-null values
price 358 non-null values
dtypes: float64(1), int64(1)
In [23]: df.head()
Out[23]:
date price
0 1349720105 12.08
1 1349806505 12.35
2 1349892905 12.15
3 1349979305 12.19
4 1350065705 12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')
In [26]: df.head()
Out[26]:
date price
0 2012-10-08 18:15:05 12.08
1 2012-10-09 18:15:05 12.35
2 2012-10-10 18:15:05 12.15
3 2012-10-11 18:15:05 12.19
4 2012-10-12 18:15:05 12.15
In [27]: df.dtypes
Out[27]:
date datetime64[ns]
price float64
dtype: object
IEnumerable<string> e = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());
Then you can call ToList()
:
List<string> l = (from char c in source
select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();
The composer documentation mentions that you can prevent it from using the GitHub API, so that it acts like git clone
:
If you set the
no-api
key totrue
on a GitHub repository it will clone the repository as it would with any other Git repository instead of using the GitHub API. But unlike using thegit
driver directly, composer will still attempt to use GitHub's zip files.
So the section would look like this:
"repositories": [
{
"type": "vcs",
"no-api": true,
"url": "https://github.com/your/repo"
}
],
Keep in mind that the API is there for a reason. So it this should be a method of last resort regarding the increased load on github.com.
Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.
Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.
Use:
import matplotlib.pyplot as plt
plt.gcf().subplots_adjust(bottom=0.15)
to make room for the label.
Edit:
Since i gave the answer, matplotlib
has added the tight_layout()
function.
So i suggest to use it:
plt.tight_layout()
should make room for the xlabel.
I think You are using //--style="display:none"--//
for hiding the div.
Use this code:
<script>
function klikaj(i) {
document.getElementById(i).style.display = 'block';
}
</script>
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">Click Me..!</div>
<div id="rad1" class="thumbs" style="display:none">Helloooooo</div>
There's nothing wrong with include file in head. It seems you forgot to add;
. Please try this one:
<body onload="imageRefreshBig();">
But as per my knowledge semicolons are optional. You can try with ;
but better debug code and see if chrome console gives any error.
I hope this helps.
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
my recommendation is
hikari > druid > UCP > c3p0 > DBCP
It's based on what I have tested - 20190202, in my local test environment(4GB mac/mysql in docker/pool minSize=1, maxSize=8), hikari can serve 1024 threads x 1024 times to get connections, average time for each thread to finish is 1 or 2 million seconds, while c3p0 can only serve 256 threads x 1024 times and average time for each thread is already 21 million seconds. (512 threads failed).
A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.
For example, see: Application Scripting Framework
Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:
A subscriptable object is any object that implements the __getitem__
special method (think lists, dictionaries).
We can implement ajax request by using http service in AngularJs, which helps to read/load data from remote server.
$http service methods are listed below,
$http.get()
$http.post()
$http.delete()
$http.head()
$http.jsonp()
$http.patch()
$http.put()
One of the Example:
$http.get("sample.php")
.success(function(response) {
$scope.getting = response.data; // response.data is an array
}).error(){
// Error callback will trigger
});
If you have incsearch.vim plugin installed, then there is a setting to automatically clear highlight after searching:
let g:incsearch#auto_nohlsearch = 1
Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.
NB - You need to do this first on a test copy of your table!
When I did it, I found that unless I also included AND n1.id <> n2.id
, it deleted every row in the table.
If you want to keep the row with the lowest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
If you want to keep the row with the highest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
I used this method in MySQL 5.1
Not sure about other versions.
Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE
, please be advised that using INSERT
and DISTINCT
is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE
, it took more than 2 hours and yet didn't complete.
INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
SELECT DISTINCT cellId,attributeId,entityRowId,value
FROM tableName;
How about this? Here you split the array using the length you want to have.
a = np.random.randint(0,10,[4,4])
a
Out[27]:
array([[1, 5, 8, 7],
[3, 2, 4, 0],
[7, 7, 6, 2],
[7, 4, 3, 0]])
a[0:2,:]
Out[28]:
array([[1, 5, 8, 7],
[3, 2, 4, 0]])
a[2:4,:]
Out[29]:
array([[7, 7, 6, 2],
[7, 4, 3, 0]])
Use Mail::factory in the Mail PEAR package. Example.
It's worth noting that the QuerySet.values_list()
method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet
, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__
method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse
object, which, apparently, should have a Content-Type
of application/json
, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
And build yet more on the previous answer, this version of routes/index.js will ignore any files not ending in .js (and itself)
var fs = require('fs');
module.exports = function(app) {
fs.readdirSync(__dirname).forEach(function(file) {
if (file === "index.js" || file.substr(file.lastIndexOf('.') + 1) !== 'js')
return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
public static List<HtmlNode> GetTagsWithClass(string html,List<string> @class)
{
// LoadHtml(html);
var result = htmlDocument.DocumentNode.Descendants()
.Where(x =>x.Attributes.Contains("class") && @class.Contains(x.Attributes["class"].Value)).ToList();
return result;
}
Try this maybe :
Bootply : http://www.bootply.com/106527
Js :
$('input').on('click', function(){
var valeur = 0;
$('input:checked').each(function(){
if ( $(this).attr('value') > valeur )
{
valeur = $(this).attr('value');
}
});
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
});
HTML :
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<div class="row tasks">
<div class="col-md-6">
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
</div>
<div class="col-md-2">
<label>2014-01-29</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="10">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="20">
</div>
</div><!-- tasks -->
<div class="row tasks">
<div class="col-md-6">
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
</div>
<div class="col-md-2">
<label>2014-01-25</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="30">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="40">
</div>
</div><!-- tasks -->
Css
.tasks{
background-color: #F6F8F8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
}
.tasks span{
font-weight: bold;
}
.tasks input{
display: block;
margin: 0 auto;
margin-top: 10px;
}
.tasks a{
color: #000;
text-decoration: none;
border:none;
}
.tasks a:hover{
border-bottom: dashed 1px #0088cc;
}
.tasks label{
display: block;
text-align: center;
}
$(function(){_x000D_
$('input').on('click', function(){_x000D_
var valeur = 0;_x000D_
$('input:checked').each(function(){_x000D_
if ( $(this).attr('value') > valeur )_x000D_
{_x000D_
valeur = $(this).attr('value');_x000D_
}_x000D_
});_x000D_
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur); _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
background-color: #F6F8F8;_x000D_
padding: 10px;_x000D_
border-radius: 5px;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
display: block;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="progress progress-striped active">_x000D_
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
</div>_x000D_
</div>_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-29</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="10">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="20">_x000D_
</div>_x000D_
</div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-25</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="30">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="40">_x000D_
</div>_x000D_
</div><!-- tasks -->
_x000D_
the path effect is set on the paint object
Paint fgPaintSel = new Paint();
fgPaintSel.setARGB(255, 0, 0,0);
fgPaintSel.setStyle(Style.STROKE);
fgPaintSel.setPathEffect(new DashPathEffect(new float[] {10f,20f}, 0f));
you can create all sorts of dotted patterns by supplying more numbers in the int[] array it specifies the ratios of dash and gap. This is a simple, equally dashed, line.
I am using below code for today and database date.
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
According to the documentation, the first argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
Complete example based on the excellent @Hackaholic's answer:
def get_process_id(name):
"""Return process ids found by (partial) name or regex.
>>> get_process_id('kthreadd')
[2]
>>> get_process_id('watchdog')
[10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61] # ymmv
>>> get_process_id('non-existent process')
[]
"""
child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
return [int(pid) for pid in response.split()]
double a_nan = strtod("NaN", NULL);
double a_inf = strtod("Inf", NULL);
When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.
By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs:
To fix this issue add following lines After Return and Before Begin statement:
READS SQL DATA
DETERMINISTIC
For Example :
CREATE FUNCTION f2()
RETURNS CHAR(36) CHARACTER SET utf8
/*ADD HERE */
READS SQL DATA
DETERMINISTIC
BEGIN
For more detail about this issue please read Here
Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.
From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.
I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as "MISSING" in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.
The error you get is a complete red herring (as pointed out by divo).
Fortunately I wasn't using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo' suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).
compileSdkVersion 17
targetSdkVersion 17
change the compile version from 18 to 17
compile "com.android.support:support-v4:17.0.+"
compile "com.android.support:appcompat-v7:17.0.+"
Check this one out http://codepen.io/GianlucaGuarini/pen/Hzrhf Seems like it does the effect without duplication the background image of the element under itself. See texts are blurring also in the example.
Vague.js
var vague = $blurred.find('iframe').Vague({
intensity:5 //blur intensity
});
vague.blur();
Explain only shows how the optimizer thinks the query will execute.
To show the real plan, you will need to run the sql once. Then use the same session run the following:
@yoursql
select * from table(dbms_xplan.display_cursor())
This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".
Your Comparator would look like this:
public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
public int compare(GraduationCeremony o1, GraduationCeremony o2) {
int value1 = o1.campus.compareTo(o2.campus);
if (value1 == 0) {
int value2 = o1.faculty.compareTo(o2.faculty);
if (value2 == 0) {
return o1.building.compareTo(o2.building);
} else {
return value2;
}
}
return value1;
}
}
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0
).
pylab.show()
works but blocks (you need to close the window).
A much more convenient solution is to do pylab.ion()
(interactive mode on) when you start: all (the pylab equivalents of) pyplot.*
commands display their plot immediately. More information on the interactive mode can be found on the official web site.
I also second using the even more convenient ipython -pylab
(--pylab
, in newer versions), which allows you to skip the from … import …
part (%pylab
works, too, in newer IPython versions).
Recursion is an expression directly or indirectly referencing itself.
Consider recursive acronyms as a simple example:
Just replace color atributtes with your color
background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke android:width="1dp" android:color="#D9D9D9"/>
<corners android:radius="1dp" />
</shape>
progress.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke android:width="1dp" android:color="#2EA5DE"/>
<corners android:radius="1dp" />
</shape>
style.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@android:id/background"
android:drawable="@drawable/seekbar_background"/>
<item android:id="@android:id/progress">
<clip android:drawable="@drawable/seekbar_progress" />
</item>
</layer-list>
thumb.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size android:height="30dp" android:width="30dp"/>
<stroke android:width="18dp" android:color="#882EA5DE"/>
<solid android:color="#2EA5DE" />
<corners android:radius="1dp" />
</shape>
The error you are getting is in line 3. i.e. it is not in
CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)
but earlier:
CREATE TABLE tags
(
(question_id, tag_id) NOT NULL,
Correct table definition is like pilcrow showed.
And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
UNIQUE (tag1, tag2, tag3)
);
or, if you want to have the constraint named according to your wish:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);
Replace
Into seems like an option. Or you can check with
IF NOT EXISTS(QUERY) Then INSERT
This will insert or delete then insert. I tend to go for a IF NOT EXISTS
check first.
I'm surprised nobody has warned about the risk of regex injection by using /^bar$/i
if bar is a password or an account id search. (I.e. bar => .*@myhackeddomain.com
e.g., so here comes my bet: use \Q
\E
regex special chars! provided in PERL
db.stuff.find( { foo: /^\Qbar\E$/i } );
You should escape bar variable \
chars with \\
to avoid \E
exploit again when e.g. bar = '\E.*@myhackeddomain.com\Q'
Another option is to use a regex escape char strategy like the one described here Javascript equivalent of Perl's \Q ... \E or quotemeta()
As my previous answer appeared not to be very popular, I will give this another go.
You are mostly on a right track. The shortest code to get to your desired output I could come up with is this:
things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.findFirst()
.flatMap( Function.identity() );
This will fit all your requirements:
Optional<Result>
this::resolve
lazily as neededthis::resolve
will not be called after first non-empty resultOptional<Result>
The only modification compared to OP initial version was that I removed .map(Optional::get)
before call to .findFirst()
and added .flatMap(o -> o)
as the last call in the chain.
This has a nice effect of getting rid of the double-Optional, whenever stream finds an actual result.
You can't really go any shorter than this in Java.
The alternative snippet of code using the more conventional for
loop technique is going to be about same number of lines of code and have more or less same order and number of operations you need to perform:
this.resolve
, Optional.isPresent
Just to prove that my solution works as advertised, I wrote a small test program:
public class StackOverflow {
public static void main( String... args ) {
try {
final int integer = Stream.of( args )
.peek( s -> System.out.println( "Looking at " + s ) )
.map( StackOverflow::resolve )
.filter( Optional::isPresent )
.findFirst()
.flatMap( o -> o )
.orElseThrow( NoSuchElementException::new )
.intValue();
System.out.println( "First integer found is " + integer );
}
catch ( NoSuchElementException e ) {
System.out.println( "No integers provided!" );
}
}
private static Optional<Integer> resolve( String string ) {
try {
return Optional.of( Integer.valueOf( string ) );
}
catch ( NumberFormatException e )
{
System.out.println( '"' + string + '"' + " is not an integer");
return Optional.empty();
}
}
}
(It does have few extra lines for debugging and verifying that only as many calls to resolve as needed...)
Executing this on a command line, I got the following results:
$ java StackOferflow a b 3 c 4
Looking at a
"a" is not an integer
Looking at b
"b" is not an integer
Looking at 3
First integer found is 3
I just downloaded xlrd, created an excel document (excel 2007) for testing and got the same error (message says 'found PK\x03\x04\x14\x00\x06\x00'). Extension is a xlsx. Tried saving it to an older .xls format and error disappears .....
re.findall(r"[-+]?\d*\.?\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
as described above, works really well! One suggestion though:
re.findall(r"[-+]?\d*\.?\d+|[-+]?\d+", "Current Level: -13.2 db or 14.2 or 3 or -3")
will also return negative int values (like -3 in the end of this string)
Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.
Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Example::Scheduling a Job For a Specific Time
The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.
Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.
30 08 10 06 * /home/yourname/full-backup
In your case, for 2.30PM
,
30 14 * * * YOURCMD
To know more about cron, visit this website.
Try moving the lapsList
function out of your class and into your render function:
render() {
const lapsList = this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
return (
<View style={styles.container}>
<View style={styles.footer}>
<View><Text>coucou test</Text></View>
{lapsList}
</View>
</View>
)
}
select COUNT(*)
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5
Its problem at bitbucket's end.
You can check status of their services at http://status.bitbucket.org/
Currently there is HTTPS
outage at bitbucket. see below
You can use SSH
option. I just used SSH
option with sourcetree
.
Since you are using features of ES6 (arrow functions), you may also simply use a for loop like this:
for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {_x000D_
console.log(child)_x000D_
}
_x000D_
CASE LEN('TestPerson')
WHEN 0 THEN co.personentered = co.personentered ELSE co.personentered LIKE '%TestPerson'
Try the following:
... and (
(LEN('TestPerson') = 0 and co.personentered = co.personentered) or
(LEN('TestPerson') <> 0 and co.personentered LIKE '%TestPerson') ) and ...
If you are using Java, have a look at JDBC.
http://msdn.microsoft.com/en-us/library/ms378672(SQL.90).aspx
For a efficient solution, you can use .values() function to get a list of dict objects and then dump it to json response by using i.e. JsonResponse (remember to set safe=False
).
Once you have your desired queryset object, transform it to JSON response like this:
...
data = list(queryset.values())
return JsonResponse(data, safe=False)
You can specify field names in .values()
function in order to return only wanted fields (the example above will return all model fields in json objects).
Another option is to use
$_SERVER['REQUEST_METHOD'] == 'POST'
I collected many topics to make universal function with many outputs (years, months, days, hours, minutes, seconds) with string or parse to int and direction +- if you need to know what side is direction of the difference.
Use example:
$date1='2016-05-27 02:00:00';
$format='Y-m-d H:i:s';
echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format);
#1 years 3 months 2 days 22 hours 1 minutes 59 seconds (string)
echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format,false, '%a days %h hours');
#459 days 22 hours (string)
echo timeDifference('2016-05-27 00:00:00', $format, '2017-08-30 00:01:59', $format,true, '%d days -> %H:%I:%S', true);
#-3 days -> 00:01:59 (string)
echo timeDifference($date1, $format, '2016-05-27 00:05:51', $format, false, 'seconds');
#9 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, false, 'hours');
#5 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours');
#-5 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours',true);
#-5 (int)
Function
function timeDifference($date1_pm_checked, $date1_format,$date2, $date2_format, $plus_minus=false, $return='all', $parseInt=false)
{
$strtotime1=strtotime($date1_pm_checked);
$strtotime2=strtotime($date2);
$date1 = new DateTime(date($date1_format, $strtotime1));
$date2 = new DateTime(date($date2_format, $strtotime2));
$interval=$date1->diff($date2);
$plus_minus=(empty($plus_minus)) ? '' : ( ($strtotime1 > $strtotime2) ? '+' : '-'); # +/-/no_sign before value
switch($return)
{
case 'y';
case 'year';
case 'years';
$elapsed = $interval->format($plus_minus.'%y');
break;
case 'm';
case 'month';
case 'months';
$elapsed = $interval->format($plus_minus.'%m');
break;
case 'a';
case 'day';
case 'days';
$elapsed = $interval->format($plus_minus.'%a');
break;
case 'd';
$elapsed = $interval->format($plus_minus.'%d');
break;
case 'h';
case 'hour';
case 'hours';
$elapsed = $interval->format($plus_minus.'%h');
break;
case 'i';
case 'minute';
case 'minutes';
$elapsed = $interval->format($plus_minus.'%i');
break;
case 's';
case 'second';
case 'seconds';
$elapsed = $interval->format($plus_minus.'%s');
break;
case 'all':
$parseInt=false;
$elapsed = $plus_minus.$interval->format('%y years %m months %d days %h hours %i minutes %s seconds');
break;
default:
$parseInt=false;
$elapsed = $plus_minus.$interval->format($return);
}
if($parseInt)
return (int) $elapsed;
else
return $elapsed;
}
You can't have optional arguments that default to a certain value in Java. The nearest thing to what you are talking about is java varargs whereby you can pass an arbitrary number of arguments (of the same type) to a method.
This is the code I wound up with, based upon the other answers here. This is for an HttpPost that receives and responds with complex types:
Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(
strMyHttpPostURL,
new MyComplexObject { Param1 = param1, Param2 = param2}).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
//debug:
//String s = response.Result.Content.ReadAsStringAsync().Result;
MyOtherComplexType moct = (MyOtherComplexType)JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result, typeof(MyOtherComplexType));
prefetch_related
use for prefetch data for Many to many and many to one relationship data.
select_related
is to select data from a single value relationship. Both of these are used to fetch data from their relationships from a model. For example, you build a model and a model that has a relationship with other models. When a request comes you will also query for their relationship data and Django has very good mechanisms To access data from their relationship like book.author.name
but when you iterate a list of models for fetching their relationship data Django create each request for every single relationship data. To overcome this we do have prefetchd_related
and selected_related
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
This one uses the method RandomAccessFile.readFully
, it seems to be available from JDK 1.0 !
public static String readFileContent(String filename, Charset charset) throws IOException {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filename, "r");
byte[] buffer = new byte[(int)raf.length()];
raf.readFully(buffer);
return new String(buffer, charset);
} finally {
closeStream(raf);
}
}
private static void closeStream(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ex) {
// do nothing
}
}
}
List<String> al=new ArrayList<string>();
al.add("One");
al.add("Two");
al.add("Three");
for(String al1:al) //for each construct
{
System.out.println(al1);
}
O/p will be
One
Two
Three
<script type="text/javascript">
$(document).ready(function(e) {
$(".mqimg").mouseover(function()
{
$("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />");
})
$(".mqimg").mouseout(function()
{
$("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
})
});
</script>
<style>
.mqimg{ cursor:pointer;}
</style>
<div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
<div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />
.push()
is a method of the Built-in Array Object
It is not related to jQuery in any way.
You are defining a literal Object with
// Object
var stuff = {};
You can define a literal Array like this
// Array
var stuff = [];
then
stuff.push(element);
Arrays actually get their bracket syntax stuff[index]
inherited from their parent, the Object. This is why you are able to use it the way you are in your first example.
This is often used for effortless reflection for dynamically accessing properties
stuff = {}; // Object
stuff['prop'] = 'value'; // assign property of an
// Object via bracket syntax
stuff.prop === stuff['prop']; // true
public void ChargingArraySelect()
{
int loop = 0;
int registros = 0;
OdbcConnection conn = WebApiConfig.conn();
OdbcCommand query = conn.CreateCommand();
query.CommandText = "select dataA, DataB, dataC, DataD FROM table where dataA = 'xpto'";
try
{
conn.Open();
OdbcDataReader dr = query.ExecuteReader();
//take the number the registers, to use into next step
registros = dr.RecordsAffected;
//calls an array to be populated
Global.arrayTest = new string[registros, 4];
while (dr.Read())
{
if (loop < registros)
{
Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]);
Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]);
Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]);
Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]);
}
loop++;
}
}
}
//Declaration the Globais Array in Global Classs
private static string[] uso_internoArray1;
public static string[] arrayTest
{
get { return uso_internoArray1; }
set { uso_internoArray1 = value; }
}
The Immediate Window can also be used to execute commands. Just type a >
followed by the command.
For example >shell cmd
will start a command shell (this can be useful to check what environment variables were passed to Visual Studio, for example). >cls
will clear the screen.
Here is a list of commands that are so commonly used that they have their own aliases: https://msdn.microsoft.com/en-us/library/c3a0kd3x.aspx
I added it for all fieldsets with
fieldset {
border: 1px solid lightgray;
}
I didnt work if I set it separately using for example
border-color : red
. Then a black line was drawn next to the red line.
You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:
#include <atlconv.h>
...
std::string str = "Hello, world!";
CA2W pszWide(str.c_str());
loadU(pszWide);
You can also specify a code page, so if your std::string contains UTF-8 chars you can use:
CA2W pszWide(str.c_str(), CP_UTF8);
Very useful but Windows only.
call.request().toString();
I think this is what your looking for:
var objs= (from c in List_Objects
orderby c.TypeID select c).GroupBy(g=>g.TypeID).Select(x=>x.FirstOrDefault());
Similar to this Returning a Distinct IQueryable with LINQ?
I did a small demo for you. Demonstrating how to display long text.
In this example there is a column Name which may contain very long text. The boundField will display all content in a table cell and therefore the cell will expand as needed (because of the content)
The TemplateField will also be rendered as a cell BUT it contains a div which limits the width of any contet to eg 40px. So this column will have some kind of max-width!
<asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Name (long)" DataField="Name">
<ItemStyle Width="40px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Name (short)">
<ItemTemplate>
<div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
<%# Eval("Name") %>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my demo codeBehind
public partial class gridViewLongText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region init and bind data
List<Person> list = new List<Person>();
list.Add(new Person(1, "Sam"));
list.Add(new Person(2, "Max"));
list.Add(new Person(3, "Dave"));
list.Add(new Person(4, "TabularasaVeryLongName"));
gvPersons.DataSource = list;
gvPersons.DataBind();
#endregion
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Person(int _ID, string _Name)
{
ID = _ID;
Name = _Name;
}
}
I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).
None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle
file :
sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]
It tells Gradle to look for resources in the src
folder, and ask it to include only PNG files.
EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found
error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/
for example, and to set it as srcDirs
instead of src/
.
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
Suppose you worked in feature/task1 with multiple commits.
Go to your project branch (project/my_project)
git checkout project/my_project
Create a new branch (feature/task1_bugfix)
git checkout -b feature/task1_bugfix
Marge with the --squash
option
git merge --squash feature/task1
Create a single commit
git commit -am "add single comments"
Push your branch
git push --set-upstream origin feature/task1_bugfix
Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);
Something like:
>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']
Power is **
and e^
is math.exp
:
x.append(1 - math.exp(-0.5 * (value1*value2)**2))
See the below example
CREATE TABLE users (
-- make the "id" column a primary key; this also creates
-- a UNIQUE constraint and a b+-tree index on the column
id SERIAL PRIMARY KEY,
name TEXT,
age INT4
);
INSERT INTO users (name, age) VALUES ('Mozart', 20);
Then for getting last inserted id use this for table "user" seq column name "id"
SELECT currval(pg_get_serial_sequence('users', 'id'));
All the answers given using LIKE
are totally valid, but as all of them noted will be slow. So if you have a lot of queries and not too many changes in the list of keywords, it pays to build a structure that allows for faster querying.
Here are some ideas:
If all you are looking for is the letters a-z and you don't care about uppercase/lowercase, you can add columns containsA .. containsZ and prefill those columns:
UPDATE table
SET containsA = 'X'
WHERE UPPER(your_field) Like '%A%';
(and so on for all the columns).
Then index the contains.. columns and your query would be
SELECT
FROM your_table
WHERE containsA = 'X'
AND containsB = 'X'
This may be normalized in an "index table" iTable with the columns your_table_key
, letter, index the letter-column and your query becomes something like
SELECT
FROM your_table
WHERE <key> in (select a.key
From iTable a join iTable b and a.key = b.key
Where a.letter = 'a'
AND b.letter = 'b');
All of these require some preprocessing (maybe in a trigger or so), but the queries should be a lot faster.
This worked for me:
http://codepen.io/anon/pen/qNbWwK
Hide the default buttons in CSS and use:
<!-- In HTML: -->
<p class="left">left</p>
<p class="right">right</p>
/* In the JS file */
$('.slider').slick({
arrows: false
})
$('.left').click(function(){
$('.slider').slick('slickPrev');
})
$('.right').click(function(){
$('.slider').slick('slickNext');
})
You just need to add a jquery selector after the url.
See: http://api.jquery.com/load/
Example straight from the API:
$('#result').load('ajax/test.html #container');
So what that does is it loads the #container element from the specified url.
The answer below comes from here(with old javascript syntax(no arrow function, support IE 10+)): https://stackoverflow.com/a/52809105/9168962
(function() {
if (typeof window.CustomEvent === "function") return false; // If not IE
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: null};
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
window.CustomEvent = CustomEvent;
})();
(function() {
history.pushState = function (f) {
return function pushState() {
var ret = f.apply(this, arguments);
window.dispatchEvent(new CustomEvent("pushState"));
window.dispatchEvent(new CustomEvent("locationchange"));
return ret;
};
}(history.pushState);
history.replaceState = function (f) {
return function replaceState() {
var ret = f.apply(this, arguments);
window.dispatchEvent(new CustomEvent("replaceState"));
window.dispatchEvent(new CustomEvent("locationchange"));
return ret;
};
}(history.replaceState);
window.addEventListener("popstate", function() {
window.dispatchEvent(new CustomEvent("locationchange"));
});
})();
Per pierce.jason's answer above, I had luck with:
Just create a new DWORD(32) under the Fusion key. Name the DWORD to LogFailures, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.
<input type="text" disabled="disabled" />
is the valid markup.<input type="text" disabled />
is valid and used by W3C on their samples.I had the same problem while installing numpy
with pip install numpy
.
Then I tried
sudo -H pip3 install --upgrade pip
sudo -H pip3 install numpy
It worked well for me.
Explanation :
The -H
(HOME) option with sudo
sets the HOME environment variable to the home directory of the target user (root by default). By default, sudo does not modify HOME.
We can easily do it by using groupby and count. But, we should remember to use reset_index().
df[['col1','col2','col3','col4']].groupby(['col1','col2']).count().\
reset_index()
Firstly, I would try a non-secure websocket connection. So remove one of the s
's from the connection address:
conn = new WebSocket('ws://localhost:8080');
If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080
both in TCP_IN
and TCP_OUT
.
In default I didn't have this problem. So what I did is chmod -R 644 sessions
to replicate the problem.
Afterwards I gave permissions to sessions folder by chmod -R 755 sessions
now my project code works again.
Reason it happens is you store your cache on file with lack of writing permissions.
The session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. In production applications, you may consider using the memcached or redis drivers for even faster session performance.
Solutions:
1 - As I have fixed above you can give 755 permission to sessions folder. 2 - You can use another session driver configuration.
file - sessions are stored in storage/framework/sessions. cookie - sessions are stored in secure, encrypted cookies. database - sessions are stored in a relational database. memcached / redis - sessions are stored in one of these fast, cache based stores. array - sessions are stored in a PHP array and will not be persisted.
Bear in mind; If you want to use memcached/redis you need to have them installed on your server or your docker redis container must be running.
String s = new String("FFFF")
creates 2 objects: "FFFF"
string and String
object, which point to "FFFF"
string, so it is like pointer to pointer (reference to reference, I am not keen with terminology).
It is said you should never use new String("FFFF")
(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).
There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.
For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).
$ create table foo (bar int);
CREATE TABLE
$ select avg(bar) from foo;
avg
-----
(1 row)
$ select coalesce(avg(bar), 0) from foo;
coalesce
----------
0
(1 row)
$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
coalesce
--------------------
6.0000000000000000
(1 row)
of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"
Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
coalesce
--------------------
4.0000000000000000
(1 row)
You are almost there, all you need is start anchor (^
) and end anchor ($
):
^[0-9]{1,45}$
\d
is short for the character class [0-9]
. You can use that as:
^\d{1,45}$
The anchors force the pattern to match entire input, not just a part of it.
Your regex [0-9]{1,45}
looks for 1 to 45 digits, so string like foo1
also get matched as it contains 1
.
^[0-9]{1,45}
looks for 1 to 45 digits but these digits must be at the beginning of the input. It matches 123
but also 123foo
[0-9]{1,45}$
looks for 1 to 45 digits but these digits must be at the end of the input. It matches 123
but also foo123
^[0-9]{1,45}$
looks for 1 to 45 digits but these digits must be both at the start and at the end of the input, effectively it should be entire input.
Imports System.IO
Public Class Form1
Public line, counter As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter += 1
If TextBox1.Text = "" Then
MsgBox("Enter a DNS address to ping")
Else
'line = ":start" + vbNewLine
'line += "ping " + TextBox1.Text
'MsgBox(line)
Dim StreamToWrite As StreamWriter
StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
StreamToWrite.Write(":start" + vbNewLine + _
"Ping -t " + TextBox1.Text)
StreamToWrite.Close()
Dim p As New System.Diagnostics.Process()
p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
p.Start()
End If
End Sub
End Class
This works as well
You can consider using memory-mapped files, via FileChannels .
Generally a lot faster for large files. There are performance trade-offs that could make it slower, so YMMV.
Related answer: Java NIO FileChannel versus FileOutputstream performance / usefulness
In Linq-to-SQL if you try to get the first element on a query with no results you will get sequence contains no elements
error. I can assure you that the mentioned error is not equal to object reference not set to an instance of an object
.
in conclusion no, it won't return null since null can't say sequence contains no elements
it will always say object reference not set to an instance of an object
;)
You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!
make sure you have these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then make some activity and register a LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParameters,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(httpParameters, true);
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 35 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
In the layout set your input method options to search.
<EditText
android:imeOptions="actionSearch"
android:inputType="text" />
In the java add the editor action listener.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));
But if you have to use older version - instead of bugged empty()
you could use:
hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan;
or
import static org.hamcrest.Matchers.greaterThan;
)
Example:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));
The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.
Ultimate Solution: The only safe way is to use regex:
echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3
it will work for any case
If you execute the following example, you will know the difference between a Throw and a Catch block.
In general terms:
The catch block will handle the Exception
throws will pass the error to his caller.
In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().
public class CatchThrow {
private static void throwsMethod() throws NumberFormatException {
String intNumber = "5A";
Integer.parseInt(intNumber);
}
private static void catchMethod() {
try {
throwsMethod();
} catch (NumberFormatException e) {
System.out.println("Convertion Error");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
catchMethod();
}
}
I have faced similar problem, 'int' object has no attribute 'DataFrame',
This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.
I realized this, and changed my variable to something else, and fixed the error.
You can use Paros to sniff the network traffic from your iPhone. See this excellent step by step post for more information: http://blog.jerodsanto.net/2009/06/sniff-your-iphones-network-traffic/. Also, look in the comments for some advice for using other proxies to get the same job done.
One caveat is that Paras only sniffs HTTP GET/POST requests using the method above, so to sniff all network traffic, try the following:
- Just turn on network sharing over WiFi and run a packet sniffer like Cocoa Packet Analyzer (in OSX).
- Then connect to the new network from iPhone over WiFi. (SystemPreferences->Sharing->InternetSharing)
If you're after sniffing these packets on Windows, connect to the internet using Ethernet, share your internet connection, and use the Windows computer as your access point. Then, just run Wireshark as normal and intercept the packets flowing through, filtering by their startpoints. Alternatively, try using a network hub as Wireshark can trace all packets flowing through a network if they are using the same router endpoint address (as in a hub).
Try this:
export const isEmpty = string => (!string || !string.length);
Use something such as the following:
if (String.IsNullOrEmpty(MaterialTextBox.Text))
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
Trying to fix this answer in How do I convert array of Objects into one Object in JavaScript?,
this should do it:
var array = [_x000D_
{key:'k1',value:'v1'},_x000D_
{key:'k2',value:'v2'},_x000D_
{key:'k3',value:'v3'}_x000D_
];_x000D_
var mapped = array .map(item => ({ [item.key]: item.value }) );_x000D_
var newObj = Object.assign({}, ...mapped );_x000D_
console.log(newObj );
_x000D_
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));
CSS:
tr {
width: 100%;
display: inline-table;
height:60px; // <-- the rows height
}
table{
height:300px; // <-- Select the height of the table
display: -moz-groupbox; // For firefox bad effect
}
tbody{
overflow-y: scroll;
height: 200px; // <-- Select the height of the body
width: 100%;
position: absolute;
}
Bootply : http://www.bootply.com/AgI8LpDugl
This will generate 4 MB text file with random characters in current directory and its name "4mb.txt" You can change parameters to generate different sizes and names.
base64 /dev/urandom | head -c 4000000 > 4mb.txt
yes, simply use colspan.
I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:
mySID, mySID.whereever.com =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = mySID.whereever.com)
(SID = mySID)
(SERVER = DEDICATED)
)
)
I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.
karim79's get_headers() solution didn't worked for me as I gotten crazy results with Pinterest.
get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Array
(
[url] => https://www.pinterest.com/jonathan_parl/
[exists] =>
)
get_headers(): Failed to enable crypto
Array
(
[url] => https://www.pinterest.com/jonathan_parl/
[exists] =>
)
get_headers(https://www.pinterest.com/jonathan_parl/): failed to open stream: operation failed
Array
(
[url] => https://www.pinterest.com/jonathan_parl/
[exists] =>
)
Anyway, this developer demonstrates that cURL is way faster than get_headers():
http://php.net/manual/fr/function.get-headers.php#104723
Since many people asked for karim79 to fix is cURL solution, here's the solution I built today.
/**
* Send an HTTP request to a the $url and check the header posted back.
*
* @param $url String url to which we must send the request.
* @param $failCodeList Int array list of code for which the page is considered invalid.
*
* @return Boolean
*/
public static function isUrlExists($url, array $failCodeList = array(404)){
$exists = false;
if(!StringManager::stringStartWith($url, "http") and !StringManager::stringStartWith($url, "ftp")){
$url = "https://" . $url;
}
if (preg_match(RegularExpression::URL, $url)){
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_HEADER, true);
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_USERAGENT, true);
$headers = curl_exec($handle);
curl_close($handle);
if (empty($failCodeList) or !is_array($failCodeList)){
$failCodeList = array(404);
}
if (!empty($headers)){
$exists = true;
$headers = explode(PHP_EOL, $headers);
foreach($failCodeList as $code){
if (is_numeric($code) and strpos($headers[0], strval($code)) !== false){
$exists = false;
break;
}
}
}
}
return $exists;
}
Let me explains the curl options:
CURLOPT_RETURNTRANSFER: return a string instead of displaying the calling page on the screen.
CURLOPT_SSL_VERIFYPEER: cUrl won't checkout the certificate
CURLOPT_HEADER: include the header in the string
CURLOPT_NOBODY: don't include the body in the string
CURLOPT_USERAGENT: some site needs that to function properly (by example : https://plus.google.com)
Additional note: In this function I'm using Diego Perini's regex for validating the URL before sending the request:
const URL = "%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu"; //@copyright Diego Perini
Additional note 2: I explode the header string and user headers[0] to be sure to only validate only the return code and message (example: 200, 404, 405, etc.)
Additional note 3: Sometime validating only the code 404 is not enough (see the unit test), so there's an optional $failCodeList parameter to supply all the code list to reject.
And, of course, here's the unit test (including all the popular social network) to legitimates my coding:
public function testIsUrlExists(){
//invalid
$this->assertFalse(ToolManager::isUrlExists("woot"));
$this->assertFalse(ToolManager::isUrlExists("https://www.facebook.com/jonathan.parentlevesque4545646456"));
$this->assertFalse(ToolManager::isUrlExists("https://plus.google.com/+JonathanParentL%C3%A9vesque890800"));
$this->assertFalse(ToolManager::isUrlExists("https://instagram.com/mariloubiz1232132/", array(404, 405)));
$this->assertFalse(ToolManager::isUrlExists("https://www.pinterest.com/jonathan_parl1231/"));
$this->assertFalse(ToolManager::isUrlExists("https://regex101.com/546465465456"));
$this->assertFalse(ToolManager::isUrlExists("https://twitter.com/arcadefire4566546"));
$this->assertFalse(ToolManager::isUrlExists("https://vimeo.com/**($%?%$", array(400, 405)));
$this->assertFalse(ToolManager::isUrlExists("https://www.youtube.com/user/Darkjo666456456456"));
//valid
$this->assertTrue(ToolManager::isUrlExists("www.google.ca"));
$this->assertTrue(ToolManager::isUrlExists("https://www.facebook.com/jonathan.parentlevesque"));
$this->assertTrue(ToolManager::isUrlExists("https://plus.google.com/+JonathanParentL%C3%A9vesque"));
$this->assertTrue(ToolManager::isUrlExists("https://instagram.com/mariloubiz/"));
$this->assertTrue(ToolManager::isUrlExists("https://www.facebook.com/jonathan.parentlevesque"));
$this->assertTrue(ToolManager::isUrlExists("https://www.pinterest.com/"));
$this->assertTrue(ToolManager::isUrlExists("https://regex101.com"));
$this->assertTrue(ToolManager::isUrlExists("https://twitter.com/arcadefire"));
$this->assertTrue(ToolManager::isUrlExists("https://vimeo.com/"));
$this->assertTrue(ToolManager::isUrlExists("https://www.youtube.com/user/Darkjo666"));
}
Great success to all,
Jonathan Parent-Lévesque from Montreal
You can use to automate this, you could define the foreign key constraint with ON DELETE CASCADE
.
I quote the the manual of foreign key constraints:
CASCADE
specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.
As KhAn SaAb has stated, you need to set your path.
But in order for your JDK to take advantage of tools such as Maven in the future, I would assign a JAVA_HOME
path to point to your JDK folder and then just add the %JAVA_HOME%\bin
directory to your PATH
.
JAVA_HOME = "C:\Program Files\Java\jdk1.8.0"
PATH = %PATH%\%JAVA_HOME%\bin
In Windows:
blah;blah;blah;
C:\Program Files\Java\jdk1.8.0\bin;blah,blah;blah
to:
blah;blah;blah;
%JAVA_HOME%\bin;blah,blah;blah
string pass = "";
Console.WriteLine("Enter your password: ");
ConsoleKeyInfo key;
do {
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace) {
pass += key.KeyChar;
Console.Write("*");
} else {
Console.Write("\b \b");
char[] pas = pass.ToCharArray();
string temp = "";
for (int i = 0; i < pass.Length - 1; i++) {
temp += pas[i];
}
pass = temp;
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
Console.WriteLine("The Password You entered is : " + pass);
I'm using this tutorial and it works nicely for my application.
In my activity I put this code:
GPSTracker tracker = new GPSTracker(this);
if (!tracker.canGetLocation()) {
tracker.showSettingsAlert();
} else {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
}
also check if your emulator runs with Google API
You may use DateInterval for this purpose;
$currentDate = new \DateTime(); //creates today timestamp
$currentDate->add(new \DateInterval('P5Y')); //this means 5 Years
and you can now format it;
$currentDate->format('Y-m-d');
Make the DropDownStyle to DropDownList
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.
My project is now behaving as I would expect.
You don't need jQuery to do this. Here's an ES2015 solution:
// Get all input fields
const inputs = document.querySelectorAll('#register input');
// Get only the required ones
const requiredFields = Array.from(inputs).filter(input => input.required);
// Do your stuff with the required fields
requiredFields.forEach(field => /* do what you want */);
Or you could just use the :required
selector:
Array.from(document.querySelectorAll('#register input:required'))
.forEach(field => /* do what you want */);
This is because label
is an inline element, and is therefore only as big as the text it contains.
The possible is to display your label
as a block element like this:
#formItem label {
display: block;
text-align: center;
line-height: 150%;
font-size: .85em;
}
However, if you want to use the label on the same line with other elements, you either need to set display: inline-block;
and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div
and do the alignment in the div
.
In ruby https://github.com/RiotGames/nexus_cli A CLI wrapper around Sonatype Nexus REST calls.
Usage Example:
nexus-cli push_artifact com.mycompany.artifacts:myartifact:tgz:1.0.0 ~/path/to/file/to/push/myartifact.tgz
Configuration is done via the .nexus_cli
file.
url: "http://my-nexus-server/nexus/"
repository: "my-repository-id"
username: "username"
password: "password"
There's another layout manager that may be of interest here: Overlay Layout Here's a simple tutorial: OverlayLayout: for layout management of components that lie on top of one another. Overlay Layout allows you to position panels on top of one another, and set a layout inside each panel. You are also able to set size and position of each panel separately.
(The reason I'm answering this question from years ago is because I have stumbled upon the same problem, and I have seen very few mentions of the Overlay Layout on StackOverflow, while it seems to be pretty well documented. Hopefully this may help someone else who keeps searching for it.)
You are probably looking for get_attribute()
. An example is shown here as well
def test_chart_renders_from_url(self):
url = 'http://localhost:8000/analyse/'
self.browser.get(url)
org = driver.find_element_by_id('org')
# Find the value of org?
val = org.get_attribute("attribute name")
In my view, the best way to do this is via an API so that you do not add a large and complex dependency into your app that runs unmanaged code, that needs to be frequently updated.
Here is a simple way to do this, which is free for 800 requests/month:
var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';
var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();
var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
input.Html = "<b>Hello, world!</b>";
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.convertWebHtmlToPdf(input, callback);
With the above approach you can also install the API on-premises or on your own infrastructure if you prefer.
I was having trouble with the autoplay from waldir's solution... using autoplay, the video was playing when the page loaded, not when the div got displayed.
This solution worked for me except I replaced
<a class="introVid" href="#video">Watch the video</a></p>
with
<a class="introVid" href="#video"><img src="images/NEWTHUMB.jpg" style="cursor:pointer" /></a>
so that it would use my thumbnail in place of the text link.
Simply call test2
from test1
like:
EXEC test2 @newId, @prod, @desc;
Make sure to get @id
using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT @newId = SCOPE_IDENTITY()
Since we can have pointers to int, and pointers to char, and pointers to any structures we've defined, and in fact pointers to any type in C, it shouldn't come as too much of a surprise that we can have pointers to other pointers.
Got to
gradle-wrapper.properties
Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip
Your property file location is classpath:idm.properties
This is rather unusual, it means that idm.properties
must be located either at the top level of WEB-INF/classes
or at the top-level of one of the jars inside WEB-INF/lib
. Usually it's good practice to either use a dedicated folder for properties or keep them close to the context files that use them.
So my suggestion is this: Is your properties file perhaps next to your context file? If so, it's not on the classpath (see this question: Is WEB-INF in the CLASSPATH?).
The classpath:
prefix maps to a ClassPathResource
, but you probably need a ServletContextResource
, and you'll get that from a WebApplicationContext
using the syntax without prefix:
<context:property-placeholder location="idm.properties" />
Reference:
ResourceLoader
ApplicationContext
types handle resources without prefix)PropertyPlaceholderConfigurer
mechanism<context:property-placeholder>
mechanism)use this css for height
height: calc(100vh) !important;
This will make the video to have 100% vertical height available.
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow()
,doAnswer()
,doNothing()
,doReturn()
family of methods from Mockito framework to mock void methods.
For example,
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
Presuming that you are looking at mocking the setter setState(String s)
in the class World below is the code uses doAnswer
method to mock the setState
.
World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
}
}).when(mockWorld).setState(anyString());
I was facing the same issue but was unable to solve, until I try this:
-vm
Enter
C:\Program Files\Java\jdk1.6.0_07\bin\javaw.exe
You should move your switch into the template by using the 'ng-switch' directive:
module.directive('testForm', function() {
return {
restrict: 'E',
controllerAs: 'form',
controller: function ($scope) {
console.log("Form controller initialization");
var self = this;
this.fields = {};
this.addField = function(field) {
console.log("New field: ", field);
self.fields[field.name] = field;
};
}
}
});
module.directive('formField', function () {
return {
require: "^testForm",
template:
'<div ng-switch="field.fieldType">' +
' <span>{{title}}:</span>' +
' <input' +
' ng-switch-when="text"' +
' name="{{field.name}}"' +
' type="text"' +
' ng-model="field.value"' +
' />' +
' <select' +
' ng-switch-when="select"' +
' name="{{field.name}}"' +
' ng-model="field.value"' +
' ng-options="option for option in options">' +
' <option value=""></option>' +
' </select>' +
'</div>',
restrict: 'E',
replace: true,
scope: {
fieldType: "@",
title: "@",
name: "@",
value: "@",
options: "=",
},
link: function($scope, $element, $attrs, form) {
$scope.field = $scope;
form.addField($scope);
}
};
});
It can be use like this:
<test-form>
<div>
User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
</div>
<form-field title="Email" name="email" field-type="text" value="[email protected]"></form-field>
<form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
<form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>
Even if you want to accept numbers for the input, I would recommend using the text
type.
<input type="text" name"some-number" />
Client-side run some jQuery validations to verify it's a number.
Then in your server side code, run some validation to verify it is in fact a numerical value.
The accepted answer was not working for me, I followed this tutorial instead with success.
Basically:
<div id="muteYouTubeVideoPlayer"></div>
<script async src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('muteYouTubeVideoPlayer', {
videoId: 'YOUR_VIDEO_ID', // YouTube Video ID
width: 560, // Player width (in px)
height: 316, // Player height (in px)
playerVars: {
autoplay: 1, // Auto-play the video on load
controls: 1, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 1, // Hide the Youtube Logo
loop: 1, // Run the video in a loop
fs: 0, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
autohide: 0 // Hide video controls when playing
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
// Written by @labnol
</script>
If you've just inserted a record into the Customers table and you need the value of the recently populated ID field, you can use the SCOPE_IDENTITY
function. This is only useful when the INSERT
has occurred within the same scope as the call to SCOPE_IDENTITY
.
INSERT INTO Customers(ID, FirstName, LastName)
Values
(23, 'Bob', 'Smith')
SET @mostRecentId = SCOPE_IDENTITY()
This may or may not be useful for you, but it's a good technique to be aware of. It will also work with auto-generated columns.
You can get a few way ip address utilizing Request ip, Request getClientIp and solicitation partner work. In this model, I will tell you the best way to get current client ip address in laravel 5.8.
$clientIP = request()->ip();
dd($clientIP);
You can follow this from here
If you're creating 2 executable JAR files, each will have it's own manifest file, and each manifest file will specify the class that contains the main()
method you want to use to start execution.
In each JAR file, the manifest will be a file with the following path / name inside the JAR - META-INF/MANIFEST.MF
There are ways to specify alternatively named files as a JAR's manifest using the JAR command-line parameters.
The specific class you want to use is specified using Main-Class: package.classname inside the META-INF/MANIFEST.MF file.
As for how to do this in Netbeans - not sure off the top of my head - I usually use IntelliJ and / or Eclipse and usually build the JAR through ANT or Maven anyway.