Simply add a -h
after adding your credentials using a -u -p
, and it will run with elevated privileges.
Although most of the points are already discussed. But I would like to highlight again one more reason for NaN which is missing.
tf.estimator.DNNClassifier(
hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None,
label_vocabulary=None, optimizer='Adagrad', activation_fn=tf.nn.relu,
dropout=None, config=None, warm_start_from=None,
loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE, batch_norm=False
)
By default activation function is "Relu". It could be possible that intermediate layer's generating a negative value and "Relu" convert it into the 0. Which gradually stops training.
I observed the "LeakyRelu" able to solve such problems.
you can use regex in order to catch any length of white space, and this would be like:
var text = "hoi how are you";
var arr = text.split(/\s+/);
console.log(arr) // will result : ["hoi", "how", "are", "you"]
console.log(arr[2]) // will result : "are"
event.target
returns the node that was targeted by the function. This means you can do anything you would do with any other node like one you'd get from document.getElementById
That’s a media query. It prevents the CSS inside it from being run unless the browser passes the tests it contains.
The tests in this media query are:
@media screen
— The browser identifies itself as being in the “screen” category. This roughly means the browser considers itself desktop-class — as opposed to e.g. an older mobile phone browser (note that the iPhone, and other smartphone browsers, do identify themselves as being in the screen category), or a screenreader — and that it’s displaying the page on-screen, rather than printing it.
max-width: 1024px
— the width of the browser window (including the scroll bar) is 1024 pixels or less. (CSS pixels, not device pixels.)
That second test suggests this is intended to limit the CSS to the iPad, iPhone, and similar devices (because some older browsers don’t support max-width
in media queries, and a lot of desktop browsers are run wider than 1024 pixels).
However, it will also apply to desktop browser windows less than 1024 pixels wide, in browsers that support the max-width
media query.
Here’s the Media Queries spec, it’s pretty readable:
It took me a while to figure this out too. url_for
in Flask looks for endpoints that you specified in the routes.py
script.
So if you have a decorator in your routes.py
file like @blah.route('/folder.subfolder')
then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }}
. The 'folder.subfolder'
argument sends it to a Flask endpoint it recognizes.
However let us say that you stored your image file, some_image.jpg
, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py
, your route decorator looks like @blah.routes('/folder')
. You then have to ask for your image file this way:
{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.
As explained in the documentation, by using an @RequestParam
annotation:
public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
+ foo;
}
Having tackled this same problem myself today, I'd like to present a solution that (currently) works on the major browsers. Some of the other answers on this page did work once, but recent updates, whether it be browser or OS, have voided most/all of these answers.
The key is to place the image in a container, and to transform:scale that container out of it's overflow:hidden parent. Then, the blur gets applied to the img inside the container, instead of on the container itself.
Working Fiddle: https://jsfiddle.net/x2c6txk2/
HTML
<div class="container">
<div class="img-holder">
<img src="https://unsplash.it/500/300/?random">
</div>
</div>
CSS
.container {
width : 90%;
height : 400px;
margin : 50px 5%;
overflow : hidden;
position : relative;
}
.img-holder {
position : absolute;
left : 0;
top : 0;
bottom : 0;
right : 0;
transform : scale(1.2, 1.2);
}
.img-holder img {
width : 100%;
height : 100%;
-webkit-filter : blur(15px);
-moz-filter : blur(15px);
filter : blur(15px);
}
NOTE: This answer is applicable to legacy browsers without support for the Flexbox standard. For a modern approach, see: https://stackoverflow.com/a/23300532/1155721
I suggest you take a look at Equal Height Columns with Cross-Browser CSS and No Hacks.
Basically, doing this with CSS in a browser compatible way is not trivial (but trivial with tables) so find yourself an appropriate pre-packaged solution.
Also, the answer varies on whether you want 100% height or equal height. Usually it's equal height. If it's 100% height the answer is slightly different.
When rebase or push to head/master this error may occurred
remote: GitLab: You are not allowed to access some of the refs!
To git@giturl:main/xyz.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@giturl:main/xyz.git'
To resolve this issue in git dashboard should remove master branch from "Protected branches"
then you can run this command
git push -f origin master
or
git rebase --onto temp $1 master
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
First access the children with: this.props.children
, each child will then have its ref
as a property on it.
Here is a simple way to filter any request/response params from the logs using HttpLoggingInterceptor
:
// Request patterns to filter
private static final String[] REQUEST_PATTERNS = {
"Content-Type",
};
// Response patterns to filter
private static final String[] RESPONSE_PATTERNS = {"Server", "server", "X-Powered-By", "Set-Cookie", "Expires", "Cache-Control", "Pragma", "Content-Length", "access-control-allow-origin"};
// Log requests and response
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
// Blacklist the elements not required
for (String pattern: REQUEST_PATTERNS) {
if (message.startsWith(pattern)) {
return;
}
}
// Any response patterns as well...
for (String pattern: RESPONSE_PATTERNS) {
if (message.startsWith(pattern)) {
return;
}
}
Log.d("RETROFIT", message);
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Here is the full gist:
https://gist.github.com/mankum93/179c2d5378f27e95742c3f2434de7168
You can even use this one. worked well for me
$("#registerform").attr("action", "register.php?btnsubmit=Save")
$('#registerform').submit();
this will submit btnsubmit =Save as GET value to register.php form.
For completeness, scaling text by 150% with cex = 1.5
, here is a full solution:
cex <- 1.5
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(...)
par(cex.lab=1, cex.axis=1, cex.main=1)
I recommend wrapping things like this to reduce boilerplate, e.g.:
plot_cex <- function(x, y, cex=1.5, ...) {
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(x, y, ...)
par(cex.lab=1, cex.axis=1, cex.main=1)
invisible(0)
}
which you can then use like this:
plot_cex(x=1:5, y=rnorm(5), cex=1.3)
The ...
are known as ellipses in R and are used to pass additional parameters on to functions. Hence, they are commonly used for plotting. So, the following works as expected:
plot_cex(x=1:5, y=rnorm(5), cex=1.5, ylim=c(-0.5,0.5))
Ok, I've found a better way. I'm now able to only change the color of the title. You can also tweak the subtitle.
Here is my styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">@style/MyTheme.ActionBarStyle</item>
</style>
<style name="MyTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
</style>
<style name="MyTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
<item name="android:textColor">@color/red</item>
</style>
</resources>
I ran into a same problem. I was running portable version of android studio so downloaded a package from https://developer.android.com/studio/#downloads and installed it, and like that, done!
In modern browsers you can use the ::marker CSS pseudo-element like this:
.farParentDiv ul li::marker {
font-size: 0.8em;
}
For browser support, please refer to: Can I Use ::marker pseudo-element
For react-native-firebase, adding this to app/build.gradle
dependencies section made it work for me:
implementation('com.squareup.okhttp3:okhttp:3.12.1') { force = true }
implementation('com.squareup.okio:okio:1.15.0') { force = true }
implementation('com.google.code.findbugs:jsr305:3.0.2') { force = true}
I made a small modification on @jonathan.cone's one liner ( by adding .getFile()
) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();
You can also just "not" add a url inside the <a>
tag, i do this for menus that are <a>
tag driven with drop downs as well. If there is not drop down then i add the url but if there are drop downs with a <ul> <li>
list i just remove it.
I know that is old, but that is the better solution that i found:
killtree() {
for p in $(pstree -p $1 | grep -o "([[:digit:]]*)" |grep -o "[[:digit:]]*" | tac);do
echo Terminating: $p
kill $p
done
}
You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));
Element root = document.getDocumentElement();
for (Server newServer : Collection<Server> bunchOfNewServers){
Element server = Document.createElement("server");
/* create and setup the server node...*/
root.appendChild(server);
}
/* use whatever method to output DOM to XML (for example, using transformer like you did).*/
Use a benchmark library, like this recent foray from Jon Skeet to measure it.
As all (micro-)performance questions, this depends on the versions of software you are using, the details of the data inspected and the code surrounding the call.
As all (micro-)performance questions, the first step has to be to get a running version which is easily maintainable. Then benchmarking, profiling and tuning can be applied to the measured bottlenecks instead of guessing.
The find
method returns a Cursor
instance, which allows you to iterate over all matching documents.
To get the first document that matches the given criteria you need to use find_one
. The result of find_one
is a dictionary.
You can always use the list
constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.
You should do that if you need to reuse the cursor and have a good reason not to use rewind()
Demo using find
:
>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
... print(doc) # or do something with the document
...
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}
Demo using find_one
:
>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
The main reason for this kind of error is you might have uninstalled Mysql server application. Install it and then give it a go.
Leaving this here for myself,
If I get this error, I probably used const char*
when I should be using char* const
.
This makes the pointer constant, and not the contents of the string.
const char* const
makes it so the value and the pointer is constant also.
Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!
In the child pom, use something like this:
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.felipe</groupId>
<artifactId>tutorial_maven</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>tutorial_maven_jar</artifactId>
Using properties like ${project.groupId}
won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
The Best is use use closedxml.codeplex.com Library.Refer it @https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation
var wb = new ClosedXML.Excel.XLWorkbook();
DataTable dt = GetTheDataTable();//Refer documentation
wb.Worksheets.Add(dt);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=\"FileName.xlsx\"");
using (var ms = new System.IO.MemoryStream()) {
wb.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
ms.Close();
}
Response.End();
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
Indexing in python starting from 0. You wrote [1:] this would not return you a first char in any case - this will return you a rest(except first char) of string.
If you have the following structure:
mylist = ['base', 'sample', 'test']
And want to get fist char for the first one string(item):
myList[0][0]
>>> b
If all first chars:
[x[0] for x in myList]
>>> ['b', 's', 't']
If you have a text:
text = 'base sample test'
text.split()[0][0]
>>> b
infile = open('filename.txt', 'r')
firstLine = infile.readline()
Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the compression middleware for gzip compression in your Express app. For example:
var compression = require('compression');
var express = require('express')
var app = express()
app.use(compression())
The disapproval of tail
here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n
, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1] 1 2 3 4 5 6 7 8 9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
# only 0's may be mixed with negative subscripts
Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.
This worked for me under 10.7.5 with EPD_free-7.3-2 from Enthought:
Install EPD free, then follow the step in the following link to create .bash_profile file.
http://redfinsolutions.com/blog/creating-bashprofile-your-mac
And add the following to the file.
PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:$(PATH)}"
export PATH
Execute the following command in Terminal
$ sudo easy_install pandas
When finished, launch PyLab and type:
In [1]: import pandas
In [2]: plot(arange(10))
This should open a plot with a diagonal straight line.
> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
a b
"numeric" "numeric"
Use outline:none
to anchor tag class
You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.
Some type of input hasn't got the :after or :before pseudo-element, so you can use a background-image with an SVG text element:
input {
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='gray' font-size='15'>Type Something...</text></svg>");
background-repeat: no-repeat;
}
input:focus {
background-image: none;
}
My codepen: https://codepen.io/Scario/pen/BaagbeZ
It's actually quite easy, assuming you have an openssl installation handy. (What platform are you on?)
Assuming you're on linux/solaris/mac os/x, Van's Apache SSL/TLS mini-HOWTO has an excellent walkthrough that I won't reproduce here.
However, the executive summary is that you have to create a self-signed certificate. Since you're running apache for localhost presumably for development (i.e. not a public web server), you'll know that you can trust the self-signed certificate and can ignore the warnings that your browser will throw at you.
since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:
npx mocha <args>
Note: the optional args are forwarded to the command being executed (mocha in this case)
this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).
Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.
You can read more on npx here
Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...
you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:
node node_modules/.bin/mocha
npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:
"scripts": {
"test": "mocha"
}
and invoke it with
npm test
Add org.hibernate.dialect.OracleDialect for Oracle11g database. It will resolve this error.
I'd prefer this way to redirect standard output (native PowerShell)...
($foo = someFunction) | out-null
But this works too:
($foo = someFunction) > $null
To redirect just standard error after defining $foo with result of "someFunction", do
($foo = someFunction) 2> $null
This is effectively the same as mentioned above.
Or to redirect any standard error messages from "someFunction" and then defining $foo with the result:
$foo = (someFunction 2> $null)
To redirect both you have a few options:
2>&1>$null
2>&1 | out-null
In C++11 you can use std::to_string:
std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);
After hours of searching I think my problem was that command yum install php-soap
installs the latest version of soap for the latest php version.
My php version was 7.027
, but latest php version is 7.2
so I had to search for the right soap version and finaly found it HERE!
yum install rh-php70-php-soap
Now php -m | grep -i soap
works, Output: soap
Do not forget to restart httpd
service.
Having seen simply too many edge cases, I went for a simpler check:
^(([0-9\ \+\_\-\,\.\^\*\?\$\^\#\(\)])|(ext|x)){1,20}$
The first thing one may point out is allowing repetition of "ext", but the purpose of this regex is to prevent users from accidentally entering email ids etc. instead of phone numbers, which it does.
qsort()
is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.
It does its magic and your array is sorted in-place. An example follows:
#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2)
{
int f = *((int*)elem1);
int s = *((int*)elem2);
if (f > s) return 1;
if (f < s) return -1;
return 0;
}
int main(int argc, char* argv[])
{
int x[] = {4,5,2,3,1,0,9,8,6,7};
qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);
for (int i = 0 ; i < 10 ; i++)
printf ("%d ", x[i]);
return 0;
}
Try this in your css:
.card-img-top {
width: 100%;
height: 15vw;
object-fit: cover;
}
Adjust the height vw as you see fit. The object-fit: cover enables zoom instead of image stretching.
VS2015: Updated the NuGet and worked.
Use a regular expression to catch the id number and replace the whole line with the number. Something like this should do it (match everything up to "id=", then match any number of digits, then match the rest of the line):
sed -e 's/.*id=\([0-9]\+\).*/\1/g'
Do this for every line and you get the list of ids.
DELETE T2
FROM table_name T1
JOIN same_table_name T2 ON (T1.title = T2.title AND T1.ID <> T2.ID)
Just because you have a project inside the workspace directory doesn't mean Eclipse opens it or even sees it automatically. You must use File - Import - General - Import existing project into workspace to have your project in Eclipse.
In our case we had a query which loads multiple items with select * from x where something in (...) The in part was so long for benchmark test.(17mb as text query). Query is valid but text so long. Shortening the query solved the problem.
Try using the following:
Window parentWindow = Window.GetWindow(userControlReference);
The GetWindow
method will walk the VisualTree for you and locate the window that is hosting your control.
You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow
method from returning null
. E.g. wire up an event:
this.Loaded += new RoutedEventHandler(UserControl_Loaded);
By Running this command you'll get the most recent tag that usually is the version of your project:
git describe --abbrev=0 --tags
This worked for me:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
function show(str){
document.getElementById('sh2').style.display = 'none';
document.getElementById('sh1').style.display = 'block';
}
function show2(sign){
document.getElementById('sh2').style.display = 'block';
document.getElementById('sh1').style.display = 'none';
}
</script>
</head>
<body>
<p>
<input type="radio" name="r1" id="e1" onchange="show2()"/> I Am New User
<input type="radio" checked="checked" name="r1" onchange="show(this.value)"/> Existing Member
</p>
<div id="sh1">Hello There !!</div>
<p> </p>
<div id="sh2" style="display:none;">Hey Watz up !!</div>
</body>
</html>
If I understand your requirement correctly, the simple answer is: you can't.
That's because the client of the WCF service may be generated by any third party that uses your service.
IF you have control of the clients of your service, you can create a base client class that add the desired header and inherit the behavior on the worker classes.
I dump all collection on robo3t. I run the command below on vagrant/homestead. It's work for me
mongodump --host localhost --port 27017 --db db_name --out db_path
Ref this
SELECT * FROM product WHERE name REGEXP '[0-9]'
I had the same issue as you, what I did is change to
<script type="application/javascript" src="bootstrap-wysiwyg.js"></script>
It works for me.
Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.
Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal
' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
If Input < 0 Then Input = 0
if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.
End Function
Consider thttpd. It can run under windows.
Quoting wikipedia:
"it is uniquely suited to service high volume requests for static data"
A version of thttpd-2.25b compiled under cygwin with cygwin dll's is available. It is single threaded and particularly good for servicing images.
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
I just run into this problem too, with all the MySQL re-config mentioned above the error still appears. It turns out that I misspelled the database name.
So be sure you're connecting with the right database name especially the case.
Try this:
Dim dataView As New DataView(table)
dataView.Sort = " AutoID DESC, Name DESC"
Dim dataTable AS DataTable = dataView.ToTable()
One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.
Type python in the prompt, and press the tab key to see what versions of Python in your environment.
Did not like the event-bus approach using $on
bindings in the child during create
. Why? Subsequent create
calls (I'm using vue-router
) bind the message handler more than once--leading to multiple responses per message.
The orthodox solution of passing props down from parent to child and putting a property watcher in the child worked a little better. Only problem being that the child can only act on a value transition. Passing the same message multiple times needs some kind of bookkeeping to force a transition so the child can pick up the change.
I've found that if I wrap the message in an array, it will always trigger the child watcher--even if the value remains the same.
Parent:
{
data: function() {
msgChild: null,
},
methods: {
mMessageDoIt: function() {
this.msgChild = ['doIt'];
}
}
...
}
Child:
{
props: ['msgChild'],
watch: {
'msgChild': function(arMsg) {
console.log(arMsg[0]);
}
}
}
HTML:
<parent>
<child v-bind="{ 'msgChild': msgChild }"></child>
</parent>
In simple words Autowiring, wiring links automatically, now comes the question who does this and which kind of wiring. Answer is: Container does this and Secondary type of wiring is supported, primitives need to be done manually.
Question: How container know what type of wiring ?
Answer: We define it as byType,byName,constructor.
Question: Is there are way we do not define type of autowiring ?
Answer: Yes, it's there by doing one annotation, @Autowired.
Question: But how system know, I need to pick this type of secondary data ?
Answer: You will provide that data in you spring.xml file or by using sterotype annotations to your class so that container can themselves create the objects for you.
'<>'
is from the SQL-92 standard and '!='
is a proprietary T-SQL operator. It's available in other databases as well, but since it isn't standard you have to take it on a case-by-case basis.
In most cases, you'll know what database you're connecting to so this isn't really an issue. At worst you might have to do a search and replace in your SQL.
I managed to reproduce this error by doing the following.
CREATE DATABASE TESTING123
GO
USE TESTING123;
SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6
set lock_timeout 5;
ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
If you don't want to touch your current table too much you can make a fake pinned column in front of the table.
The example shows one way of doing it without JS
table {_x000D_
border-collapse: collapse;_x000D_
border-spacing: 0;_x000D_
border: 1px solid #ddd;_x000D_
min-width: 600px;_x000D_
}_x000D_
_x000D_
.labels {_x000D_
display:flex;_x000D_
flex-direction: column_x000D_
}_x000D_
_x000D_
.overflow {_x000D_
overflow-x: scroll;_x000D_
min width: 400px;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.label {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
white-space:nowrap;_x000D_
padding: 10px;_x000D_
flex: 1;_x000D_
border-bottom: 1px solid #ddd;_x000D_
border-right: 2px solid #ddd;_x000D_
}_x000D_
_x000D_
.label:last-of-type {_x000D_
overflow-x: scroll;_x000D_
border-bottom: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid #ddd;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display:flex;_x000D_
max-width: 600px;_x000D_
padding: 0;_x000D_
border: 5px solid #ddd;_x000D_
}
_x000D_
<div class="flex">_x000D_
<div class="labels">_x000D_
<span class="label">Label 1</span>_x000D_
<span class="label">Lorem ipsum dolor sit amet.</span>_x000D_
<span class="label">Lorem ipsum dolor.</span>_x000D_
</div>_x000D_
<div class="overflow">_x000D_
<table>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
<td class="long">Lorem ipsum dolor sit amet consectetur adipisicing</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
its possible if you already have a python installed (pip) you could do a upgrade on mac by
brew upgrade python
Using "Store as a Global Variable" works, but it only gets the final instance of the object, and not the moment the object is being logged (since you're likely wanting to compare changes to the object as they happen). To get the object at its exact point in time of being modified, I use this...
function logObject(object) {
console.info(JSON.stringify(object).replace(/,/g, ",\n"));
}
Call it like so...
logObject(puzzle);
You may want to remove the .replace(/./g, ",\n") regex if your data happens to have comma's in it.
How about typing document.cookie into the console? It just shows the values, but it's something.
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input
does not do any type checking, so you need to be careful...
You probably want SETLOCAL ENABLEDELAYEDEXPANSION
. See https://devblogs.microsoft.com/oldnewthing/20060823-00/?p=29993 for details.
Basically: Normal %variables%
are expanded right aftercmd.exe
reads the command. In your case the "command" is the whole
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo %z%
echo %%a
)
loop. At that point z
has no value yet, so echo %z%
turns into echo
. Then the loop is executed and z
is set, but its value isn't used anymore.
SETLOCAL ENABLEDELAYEDEXPANSION
enables an additional syntax, !variable!
. This also expands variables but it only does so right before each (sub-)command is executed.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
This gives you the current value of z
each time the echo
runs.
JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
var floatValue = 10.23
var intValue = Int(floatValue)
This is enough to convert from float
to Int
As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING)
to get the string value of a numeric cell, as you'll loose all the formatting
Instead, as the javadocs explain, you should use DataFormatter
What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.
So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:
// Create a formatter, do this once
DataFormatter formatter = new DataFormatter(Locale.US);
.....
for (int i=1; i <= sheet.getLastRowNum(); i++) {
Row r = sheet.getRow(i);
if (r == null) {
// empty row, skip
} else {
String j_username = formatter.formatCellValue(row.getCell(0));
String j_password = formatter.formatCellValue(row.getCell(1));
// Use these
}
}
The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell
From the mysql documentation version: 8.0.18:
A superuser account 'root'@'localhost'
is created. A password for the superuser is set and stored
in the error log file. To reveal it, use the following command:
shell> sudo grep 'temporary password' /var/log/mysqld.log
Change the root password as soon as possible by logging in with the generated, temporary password
and set a custom password for the superuser account:
shell> mysql -uroot -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass4!';
In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :
Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0
. It makes more sense to say Version.1_0
since there is only one 1_0 Version.
I remember someday that I spent a lot of time trying to center a div, using margin: 0 auto
.
I had display: inline-block
on it, when I removed it, the div centered correctly.
As Ross pointed out, it doesn't work on inline elements.
You can use routerLink in the following manner,
<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">
or use <button [routerLink]="['./url']">
in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471
the other methods are also correct but they create a dependency on the component file.
Hope your concern is resolved.
Here is way to avoid absolute divs and tables if you know parent's height:
<div class="parent">
<div class="child"> <a href="#">Home</a>
</div>
</div>
CSS:
.parent {
line-height:80px;
border: 1px solid black;
}
.child {
line-height:normal;
display: inline-block;
vertical-align:bottom;
border: 1px solid red;
}
JsFiddle:
Or use awk
instead:
awk '/null/ { counter++; printf("%s%s%i\n",$0, " - Line number: ", NR)} END {print "Total null count: " counter}' file
In my case, Filezilla sends the AWS ppk file to every other FTP server I try to securely connect to.
That's crazy. There's a workaround as written below but it's ugly.
It does not behave well as @Lucio M pointed out.
From this discussion: https://forum.filezilla-project.org/viewtopic.php?t=30605
n0lqu:
Agreed. However, given I can't control the operation of the server, is there any way to specify within FileZilla that a site should authenticate with a password rather than key, or vice-versa? Or tell it to try password first, then key only if password fails? It appears to me it's trying key first, and then not getting a chance to try password.
botg(Filezilla admin) replied:
There's no such option.
n0lqu:
Could such an option be added, or are there any good workarounds anyone can recommend? Right now, the only workaround I know is to delete the key from general preferences, add it back only when connecting to the specific site that requires it, then deleting it again when done so it doesn't mess up other sites.
botg:
Right now you could have two FileZilla instances with separate config dirs (e. g. one installed and one portable).
timboskratch:
I just had this same issue today and managed to resolve it by changing the "logon type" of the connection using a password in the site manager. Instead of "Normal" I could select either "Interactive" or "Ask for Password" (not really sure what the difference is) and then when I tried to connect to the site again it gave me a prompt to enter my password and then connected successfully. It's not ideal as it means you have to remember and re-type you password every time you connect, but better than having to install 2 instances of FileZilla. I totally agree that it would be very useful in the Site Manager to have full options of how you would like FileZilla to connect to each site which is set up (whether to use a password, key, etc.) Hope this is helpful! Tim
Also see: https://forum.filezilla-project.org/viewtopic.php?t=34676
So, it seems:
For multiple FTP sites with keys / passwords, use multiple Filezilla installs, OR, use the same ppk key for all servers.
I wish there was a way to tell FileZilla which ppk is for which site in Site Manger
You can change this in global User
level or Workspace
level.
Open the settings: Using the shortcut Ctrl , or clicking File
> Preferences
> Settings
as shown below.
Then, do the following 2 changes: (type tabSize
in the search bar)
Detect Indentation
you need os.path.realpath
(sample below adds the parent directory to your path)
import sys,os
sys.path.append(os.path.realpath('..'))
No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work. For example if you are creating connection:
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1/"+dbname,user,pass);
} catch (SQLException e) {
e.printStackTrace();
return;
}
After doing your work close connection:
try {
connection.commit();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
Eclipse is looking for eclipse projects, meaning its is searching for eclipse-specific files in the root directory, namely .project
and .classpath
. You either gave Eclipse the wrong directory (if you are importing a eclipse project) or you actually want to create a new project from existing source(new
->java project
->create project from existing source
).
I think you probably want the second one, because Eclipse projects usually have separate source & build directories. If your sources and .class files are in the same directory, you probably didn't have a eclipse project.
nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))
[1] 2 1 0
Notice that I coerce the factor variable to character, before passing to nchar. The regex functions appear to do that internally.
Here's benchmark results (with a scaled up size of the test to 3000 rows)
q.data<-q.data[rep(1:NROW(q.data), 1000),]
str(q.data)
'data.frame': 3000 obs. of 3 variables:
$ number : int 1 2 3 1 2 3 1 2 3 1 ...
$ string : Factor w/ 3 levels "greatgreat","magic",..: 1 2 3 1 2 3 1 2 3 1 ...
$ number.of.a: int 2 1 0 2 1 0 2 1 0 2 ...
benchmark( Dason = { q.data$number.of.a <- str_count(as.character(q.data$string), "a") },
Tim = {resT <- sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter) }) },
DWin = {resW <- nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))},
Josh = {x <- sapply(regmatches(q.data$string, gregexpr("g",q.data$string )), length)}, replications=100)
#-----------------------
test replications elapsed relative user.self sys.self user.child sys.child
1 Dason 100 4.173 9.959427 2.985 1.204 0 0
3 DWin 100 0.419 1.000000 0.417 0.003 0 0
4 Josh 100 18.635 44.474940 17.883 0.827 0 0
2 Tim 100 3.705 8.842482 3.646 0.072 0 0
Rob R.'s answer was definitely the way to go. I tried copying the ic_launcher.png files from another project and Eclipse still wouldn't read them. Going through the manifest is much quicker and easier.
This is not optimal performance-wise, but a pretty straight-forward Linq approach:
string strippedString = new string(
yourString.Where(c => c <= sbyte.MaxValue).ToArray()
);
The downside is that all the "surviving" characters are first put into an array of type char[]
which is then thrown away after the string
constructor no longer uses it.
Here is a link for JDK 5 zip file. sun-jdk-5-win32-x86-1.5.0.12.zip
Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)
edit: relevant paragraph follows:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:
'-' + vendor identifier + '-' + meaningful name '_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.
Other known examples:
-moz-box-sizing -moz-border-radius -wap-accesskey
An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.
Authors should avoid vendor-specific extensions
Many answers for this questions are great and some have even looked into the corner cases. I would like to add a simple answer that can be of daily use... where you mostly get into those corner cases (like having escaped commas or commas in quotes etc.,).
FS (Field Separator) is the variable whose value is dafaulted to space. So awk by default splits at space for any line.
So using BEGIN (Execute before taking input) we can set this field to anything we want...
awk 'BEGIN {FS = ","}; {print $3}'
The above code will print the 3rd column in a csv file.
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
Here's my solution if you know the aspect ratio, which you can either get from the image metadata or prior knowledge. This fills the whole width of the screen, but that, of course, can be adjusted.
function imageStyle(aspect)
{
//Include any other style requirements in your returned object.
return {alignSelf: "stretch", aspectRatio: aspect, resizeMode: 'stretch'}
}
This looks a bit nicer than contain
, and takes less finessing with sizes, and it will adjust the height to maintain the proper aspect ratio so your images don't look skewed. Using contain will preserve the aspect ratio but will scale it to fit your other style requirements, which may drastically shrink the image.
I worked quite a long time with Flux and now quite a long time using Redux. As Dan pointed out both architectures are not so different. The thing is that Redux makes the things simpler and cleaner. It teaches you a couple of things on top of Flux. Like for example Flux is a perfect example of one-direction data flow. Separation of concerns where we have data, its manipulations and view layer separated. In Redux we have the same things but we also learn about immutability and pure functions.
Believe this occurs because you have a child repository "submodule" that has changes which have not been staged and committed.
Had a similar problem, where my IDE kept reporting uncommitted changes, and running the stage (git add .
) and commit (git commit -m "message"
) commands had no effect. Thinking about this in hindsight, it's probably because the child repository had the changes that needed to be staged and committed, not the parent repository.
cd
into the submodule (has a hidden folder named .git
) and execute the commands to stage (git add .
) and commit (git commit -m "Update child repo"
)cd ..
back to the parent repo, and execute the commands to stage (git add .
) and commit (git commit -m "Update parent repo"
)sudo rm -Rf .git
== DO NOT USE THIS COMMAND == it permanently deletes submodule repository history (the purpose of GIT)git add -A
=== Added untracked files, but didn't fix issueKnockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an on-click
binding using function.bind like this:
<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
Click me
</button>
To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):
/path/to/virtualenv/bin/python
The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:
me$ /path/to/virtualenv/bin/python myscript.py
The same for a Windows environment (whether it is from the command line or from a script):
> \path\to\env\Scripts\python.exe myscript.py
In case of temporary tables, you might want to try
SELECT 'DROP TABLE "' + t.name + '"'
FROM tempdb.sys.tables t
WHERE t.name LIKE '[prefix]%'
The TextFinder is good only if the job status hasn't been changed from SUCCESS to FAILED or ABORTED. For such cases, use a groovy script in the PostBuild step:
errpattern = ~/TEXT-TO-LOOK-FOR-IN-JENKINS-BUILD-OUTPUT.*/;
manager.build.logFile.eachLine{ line ->
errmatcher=errpattern.matcher(line)
if (errmatcher.find()) {
manager.build.@result = hudson.model.Result.NEW-STATUS-TO-SET
}
}
See more details in a post I've wrote about it: http://www.tikalk.com/devops/JenkinsJobStatusChange/
Are you trying to mimic a click on a button when the enter key is pressed? If so you may need to use the trigger
syntax.
Try changing
$('input[name = butAssignProd]').click();
to
$('input[name = butAssignProd]').trigger("click");
If this isn't the problem then try taking a second look at your key capture syntax by looking at the solutions in this post: jQuery Event Keypress: Which key was pressed?
After a rigorous code-hunting session over the internet, I finally came up with a solution which lets you compile + run your C code "together at once", in C99, in a dedicated terminal window. I know, a few people dont like C99. I dont like a few people either.
In most of the cases Sublime compiles and runs the code, but in C90 or a lesser version. So if you specifically want it to be C99, this is the way to go.
NOTE: Btw, I did this on a Windows machine, cannot guarantee for others! It probably won't work there.
1. Create a new build system in Sublime: Tools > Build System > New Build System...
2. A new file called untitled.sublime-build
would be created.
Most probably, Sublime will open it for you.
If not, go to Preferences > Browse Packages > User
If the file untitled.sublime-build
is there, then open it,
if it isn't there, then create it manually and open it.
3. Copy and paste the given below code in the above mentioned untitled.sublime-build
file and save it.
{
"windows":
{
"cmd": ["gcc","-std=c99" ,"$file_name","-o", "${file_base_name}.exe", "-lm", "-Wall", "&","start", "${file_base_name}.exe"]
},
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path",
}
Close the file. You are almost done!
4. Finally rename your file from untitled.sublime-build
to myC.sublime-build
, or you might as well show your creativity here. Just keep the file extension same.
5. Finally set the current Build System to the filename which you wrote in the previous step. In this case, it is myC
Voila !
Compile + Run your C code using C99 by Tools > Build , or by simply pressing Ctrl + B
Quick and dirty way:
<View
android:id="@+id/colored_bar"
android:layout_width="48dp"
android:layout_height="3dp"
android:background="@color/bar_red" />
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
Content-Length = "Content-Length" ":" 1*DIGIT
An example is
Content-Length: 3495
Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.
Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.
Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.
My interpretation is that this means the length "on the wire", i.e. the length of the *encoded" content
I recommend TCPDF or DOMPDF, in that order.
When calling rsync within java (and perhaps other languages), I found that setting
-e ssh -p 22
resulting in rsync complaining it could not execute the binary:
ssh -p 22
because that path ssh -p 22
did not exist (the -p and 22 are no longer arguments for some reason and now make up part of the path to the binary rsync should call).
To workaround this problem I was able to use this environment variable:
export "RSYNC_RSH=ssh -p 2222"
(Programmatically set within java using env.put("RSYNC_RSH", "ssh -p " + port);
)
Start with
svn log -q file | grep '^r' | cut -f1 -d' '
That will get you a list of revisions where the file changed, which you can then use to script repeated calls to svn diff
.
The standard definiton allows only for adding or deleting a single class. A couple of small wrapper functions can do what you ask :
function addClasses (el, classes) {
classes = Array.prototype.slice.call (arguments, 1);
console.log (classes);
for (var i = classes.length; i--;) {
classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/);
for (var j = classes[i].length; j--;)
el.classList.add (classes[i][j]);
}
}
function removeClasses (el, classes) {
classes = Array.prototype.slice.call (arguments, 1);
for (var i = classes.length; i--;) {
classes[i] = classes[i].trim ().split (/\s*,\s*|\s+/);
for (var j = classes[i].length; j--;)
el.classList.remove (classes[i][j]);
}
}
These wrappers allow you to specify the list of classes as separate arguments, as strings with space or comma separated items, or a combination. For an example see http://jsfiddle.net/jstoolsmith/eCqy7
Late at party, but a very simple solution is to use the jpsstat.sh script. It provides a simple live current memory, max memory and cpu use details.
Here is the sample output of script -
===== ====== ======= ======= =====
PID Name CurHeap MaxHeap %_CPU
===== ====== ======= ======= =====
2777 Test3 1.26 1.26 5.8
2582 Test1 2.52 2.52 8.3
2562 Test2 2.52 2.52 6.4
MRalwasser, I'd give you a hint, cast the URL.getConnection()
to JarURLConnection
.
Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.
The rest I leave to you.
Hope this helps!
There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.
It is possible to go directly to a datatable, with JSON.NET and code like this:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
Here's an example
// in the service
getVehicles(){
return Observable.interval(2200).map(i=> [{name: 'car 1'},{name: 'car 2'}])
}
// in the controller
vehicles: Observable<Array<any>>
ngOnInit() {
this.vehicles = this._vehicleService.getVehicles();
}
// in template
<div *ngFor='let vehicle of vehicles | async'>
{{vehicle.name}}
</div>
Use getch()
:
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
Windows alternative should be _getch().
If you're using Windows, this should be the full example:
#include <conio.h>
#include <ctype.h>
int main( void )
{
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
_getch();
}
P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.
Taking it further you could even parse on the fly
e.g.
& "my.exe" | %{
if ($_ -match 'OK')
{ Write-Host $_ -f Green }
else if ($_ -match 'FAIL|ERROR')
{ Write-Host $_ -f Red }
else
{ Write-Host $_ }
}
OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.
<script>
function dostuff() {
if (document.getElementById('MyBox').style.height == "0px") {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;");
}
else {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;");
}
}
</script>
<div id="MyBox" style="height: 0px; width: 0px;">
</div>
<input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
I used Keystore Explorer
As of Python 3.2+, you can also accomplish this using the to_bytes
native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
newFile.write(byte.to_bytes(1, byteorder='big'))
I.e., each single call to to_bytes
in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte
. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))
The only problem you would run into is if the norm of V is zero (or very close to it). This could give you Inf or NaN when you divide, along with a divide-by-zero warning. If you don't care about getting an Inf or NaN, you can just turn the warning on and off using WARNING:
oldState = warning('off','MATLAB:divideByZero'); % Return previous state then
% turn off DBZ warning
uV = V/norm(V);
warning(oldState); % Restore previous state
If you don't want any Inf or NaN values, you have to check the size of the norm first:
normV = norm(V);
if normV > 0, % Or some other threshold, like EPS
uV = V/normV;
else,
uV = V; % Do nothing since it's basically 0
end
If I need it in a program, I usually put the above code in my own function, usually called unit (since it basically turns a vector into a unit vector pointing in the same direction).
Use sqlite3 database.sqlite3 < db.sql
. You'll need to make sure that your files contain valid SQL for SQLite.
If you cannot put them into one container, then you have to write code to change checked state of each RadioButton:
private void rbDataSourceFile_CheckedChanged(object sender, EventArgs e)
{
rbDataSourceNet.Checked = !rbDataSourceFile.Checked;
}
private void rbDataSourceNet_CheckedChanged(object sender, EventArgs e)
{
rbDataSourceFile.Checked = !rbDataSourceNet.Checked;
}
For Firefox:
Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.
select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');'' FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT ' ' +column_name + ', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
+ '+'', '
from information_schema.columns c
join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
where table_name = so.name
order by ordinal_position
FOR XML PATH('')) val (list)
where so.type = 'U'
I strongly favour minimal file headers, by which I mean just:
#!
line) if this is an executable script import os # standard library
import sys
import requests # 3rd party packages
from mypackage import ( # local source
mymodule,
myothermodule,
)
ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.
Everything else is a waste of time, visual space, and is actively misleading.
If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE
file, not random source code.
Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.
I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.
$( "button" ).on( "click", function(event) {_x000D_
_x000D_
alert( $( this ).html() );_x000D_
console.log( event.target );_x000D_
_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<button>test 1</button>_x000D_
<button>test 2</button>
_x000D_
Perhaps this could be another possible replace :
@Data
public class MyMap {
@Delegate //lombok
private HashMap<String, String> value;
}
you could just use replace function before you return the string in the method
return df.format(bd).replace(",", ".")
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
Try this:
Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
I prefer this one as it is easier to remember:
git config -l
It will list all useful information such as:
user.name=Your Name
[email protected]
core.autocrlf=input
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
remote.origin.url=https://github.com/mapstruct/mapstruct-examples
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
You can use query-objects from npm. You can search an array of objects using filters.
const queryable = require('query-objects');
const users = [
{
firstName: 'George',
lastName: 'Eracleous',
age: 28
},
{
firstName: 'Erica',
lastName: 'Archer',
age: 50
},
{
firstName: 'Leo',
lastName: 'Andrews',
age: 20
}
];
const filters = [
{
field: 'age',
value: 30,
operator: 'lt'
},
{
field: 'firstName',
value: 'Erica',
operator: 'equals'
}
];
// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);
// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);
How long is the list you're going to normalize?
def psum(it):
"This function makes explicit how many calls to sum() are done."
print "Another call!"
return sum(it)
raw = [0.07,0.14,0.07]
print "How many calls to sum()?"
print [ r/psum(raw) for r in raw]
print "\nAnd now?"
s = psum(raw)
print [ r/s for r in raw]
# if one doesn't want auxiliary variables, it can be done inside
# a list comprehension, but in my opinion it's quite Baroque
print "\nAnd now?"
print [ r/s for s in [psum(raw)] for r in raw]
Output
# How many calls to sum()?
# Another call!
# Another call!
# Another call!
# [0.25, 0.5, 0.25]
#
# And now?
# Another call!
# [0.25, 0.5, 0.25]
#
# And now?
# Another call!
# [0.25, 0.5, 0.25]
I found best example on Dzone.com which is really helpfull to understand the real different between IOC and DI
“IoC is when you have someone else create objects for you.” So instead of writing "new " keyword (For example, MyCode c=new MyCode())in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container. It means we handover the rrsponsibility (control )to the container to get instance of object is called Inversion of Control., means instead of you are creating object using new operator, let the container do that for you.
DI(Dependency Injection): Way of injecting properties to an object is
called
Dependency injection.
We have three types of Dependency injection
1) Constructor Injection
2) Setter/Getter Injection
3) Interface Injection
Spring will support only Constructor Injection and Setter/Getter Injection.
For me, the below helped
Find org.apache.http.legacy.jar
which is in Android/Sdk/platforms/android-23/optional,
add it to your dependency.
Table names cannot be supplied as parameters, so you'll have to construct the SQL string manually like this:
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
However, make sure that your application does not allow a user to directly enter the value of @TableName
, as this would make your query susceptible to SQL injection. For one possible solution to this, see this answer.
wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz
cd Python-2.7.11
Now read the README
file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.
./configure
make
sudo make install
For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
For other versions and the most up to date download links:
http://www.python.org/getit/
Although other answers prove the requirement, they don't explain why the requirement exists.
The JLS mentions why in §15.27.2:
The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.
To lower risk of bugs, they decided to ensure captured variables are never mutated.
This is not an example use or an explanation of how to use FLAG_ACTIVITY_NO_ANIMATION
, however it does answer how to disable the Activity
switching animation, as asked in the question title:
Android, how to disable the 'wipe' effect when starting a new activity?
Much of the reason that it took > 48 hours to do your inserts is because of your indexes. It is incredibly faster to:
1 - Drop all indexes 2 - Do all inserts 3 - Create indexes again
In my case the select2 would open correctly if there was zero or more pills.
But if there was one or more pills, and I deleted them all, it would shrink to the smallest width. My solution was simply:
$("#myselect").select2({ width: '100%' });
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
use dynamic sql
BEGIN
DECLARE
maxId NUMBER;
BEGIN
SELECT MAX(id)+1
INTO maxId
FROM table_name;
execute immediate('CREATE SEQUENCE sequane_name MINVALUE '||maxId||' START WITH '||maxId||' INCREMENT BY 1 NOCACHE NOCYCLE');
END;
END;
Make a connection to your DB using a procedural programming language (here Python), and do the loop there. This way you can do complicated loops as well.
# make a connection to your db
import pyodbc
conn = pyodbc.connect('''
Driver={ODBC Driver 13 for SQL Server};
Server=serverName;
Database=DBname;
UID=userName;
PWD=password;
''')
cursor = conn.cursor()
# run sql code
for id in [4, 7, 12, 22, 19]:
cursor.execute('''
exec p_MyInnerProcedure {}
'''.format(id))
You should use the ClearContents method if you want to clear the content but preserve the formatting.
Worksheets("Sheet1").Range("A1:G37").ClearContents
I spend a hour finding out what was wrong.. But Clean Project did the trick.
Build -> Clean All
The accepted solution is probably also working.. but this was enough for me.
// to string
String text = textField.getText();
// to JTextField
textField.setText(text);
You can also create a new text field: new JTextField(text)
Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.
Reference: javadocs of JTextField
Just be careful. You will get this message if you try to enter a command that doesn't exist like this
/usr/bin/java -v
All file modes in Python
r
for readingr+
opens for reading and writing (cannot truncate a file)w
for writing w+
for writing and reading (can truncate a file) rb
for reading a binary file. The file pointer is placed at the beginning of the file.rb+
reading or writing a binary filewb+
writing a binary filea+
opens for appendingab+
Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.x
open for exclusive creation, failing if the file already exists (Python 3)Also, you can do it with css selectors:
form#myform input[type='submit']
space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element
The only way I could get it to work in ALL scenarios (except Protected sheets) (based on Farham's Answer):
It supports:
Scanning Hidden Row / Columns
Ignores formatted cells with no data / formula
Code:
// Unhide All Cells and clear formats
sheet.Columns.ClearFormats();
sheet.Rows.ClearFormats();
// Detect Last used Row - Ignore cells that contains formulas that result in blank values
int lastRowIgnoreFormulas = sheet.Cells.Find(
"*",
System.Reflection.Missing.Value,
InteropExcel.XlFindLookIn.xlValues,
InteropExcel.XlLookAt.xlWhole,
InteropExcel.XlSearchOrder.xlByRows,
InteropExcel.XlSearchDirection.xlPrevious,
false,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value).Row;
// Detect Last Used Column - Ignore cells that contains formulas that result in blank values
int lastColIgnoreFormulas = sheet.Cells.Find(
"*",
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
InteropExcel.XlSearchOrder.xlByColumns,
InteropExcel.XlSearchDirection.xlPrevious,
false,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value).Column;
// Detect Last used Row / Column - Including cells that contains formulas that result in blank values
int lastColIncludeFormulas = sheet.UsedRange.Columns.Count;
int lastColIncludeFormulas = sheet.UsedRange.Rows.Count;
You can try this code .
private enum DownloadType {
AUDIO , VIDEO , AUDIO_AND_VIDEO ;
}
You can use this enumeration as like this : DownloadType.AUDIO.ordinal()
. Hope this code snippet will help you .
Update: See the top-voted answer please.
My own is currently obsolete. Only kept here for historical reasons.
Distinct in HQL is usually needed in Joins and not in simple examples like your own.
I see the many types of uses, but I find this layout more useful as a reference tool:
SELECT DATE_FORMAT('2004-01-20' ,'%Y-%m-01');
In class do like this
@RequestMapping(value = "/saveData", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(
HttpServletResponse response,
Bean beanName
) throws MyException {
return new ResponseEntity<Boolean>(uiRequestProcessor.saveData(a), HttpStatus.OK);
}
In page do like this:
<form enctype="multipart/form-data" action="<%=request.getContextPath()%>/saveData" method="post" name="saveForm" id="saveForm">
<input type="text" value="${beanName.userName }" id="username" name="userName" />
</from>
After commenting @Marcin answer, I have more carefully checked one of my students code where I found the same weird behavior, even after only 2 epochs ! (So @Marcin's explanation was not very likely in my case).
And I found that the answer is actually very simple: the accuracy computed with the Keras method evaluate
is just plain wrong when using binary_crossentropy with more than 2 labels. You can check that by recomputing the accuracy yourself (first call the Keras method "predict" and then compute the number of correct answers returned by predict): you get the true accuracy, which is much lower than the Keras "evaluate" one.
I felt a like I needed to share this manipulated code to the accepted answer - as I have no reputation, I'm unable to comment..
using System;
using System.Xml.Serialization;
using System.IO;
namespace ObjectSerialization
{
public static class ObjectSerialization
{
// THIS: (C): https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
/// <summary>
/// A helper to serialize an object to a string containing XML data of the object.
/// </summary>
/// <typeparam name="T">An object to serialize to a XML data string.</typeparam>
/// <param name="toSerialize">A helper method for any type of object to be serialized to a XML data string.</param>
/// <returns>A string containing XML data of the object.</returns>
public static string SerializeObject<T>(this T toSerialize)
{
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
// using is necessary with classes which implement the IDisposable interface..
using (StringWriter stringWriter = new StringWriter())
{
// serialize a class to a StringWriter class instance..
xmlSerializer.Serialize(stringWriter, toSerialize); // a base class of the StringWriter instance is TextWriter..
return stringWriter.ToString(); // return the value..
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string. If the object has no instance a new object will be constructed if possible.
/// <note type="note">An exception will occur if a null reference is called an no valid constructor of the class is available.</note>
/// </summary>
/// <typeparam name="T">An object to deserialize from a XML data string.</typeparam>
/// <param name="toDeserialize">An object of which XML data to deserialize. If the object is null a a default constructor is called.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static T DeserializeObject<T>(this T toDeserialize, string xmlData)
{
// if a null instance of an object called this try to create a "default" instance for it with typeof(T),
// this will throw an exception no useful constructor is found..
object voidInstance = toDeserialize == null ? Activator.CreateInstance(typeof(T)) : toDeserialize;
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(voidInstance.GetType());
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return (T)xmlSerializer.Deserialize(stringReader);
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string.
/// </summary>
/// <param name="toDeserialize">A type of an object of which XML data to deserialize.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static object DeserializeObject(Type toDeserialize, string xmlData)
{
// create an instance of a XmlSerializer class with the given type toDeserialize..
XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize);
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return xmlSerializer.Deserialize(stringReader);
}
}
}
}
Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:
import os, shutil, glob
src_fldr = r"Source Folder/Directory path"; ## Edit this
dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print "Folder already exist or some error";
below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr
for txt_file in glob.glob(src_fldr+"\\*.txt"):
shutil.copy2(txt_file, dst_fldr);
If anyone ever needs it - Here is a recursive average.
In the context of the original question, you may want to use the recursive average if you allowed the user to insert additional values and, without incurring the cost of visiting each element again, wanted to "update" the existing average.
/**
* Computes the recursive average of an indefinite set
* @param {Iterable<number>} set iterable sequence to average
* @param {number} initAvg initial average value
* @param {number} initCount initial average count
*/
function average(set, initAvg, initCount) {
if (!set || !set[Symbol.iterator])
throw Error("must pass an iterable sequence");
let avg = initAvg || 0;
let avgCnt = initCount || 0;
for (let x of set) {
avgCnt += 1;
avg = avg * ((avgCnt - 1) / avgCnt) + x / avgCnt;
}
return avg; // or {avg: avg, count: avgCnt};
}
average([2, 4, 6]); //returns 4
average([4, 6], 2, 1); //returns 4
average([6], 3, 2); //returns 4
average({
*[Symbol.iterator]() {
yield 2; yield 4; yield 6;
}
}); //returns 4
How:
this works by maintaining the current average and element count. When a new value is to be included you increment count by 1, scale the existing average by (count-1) / count
, and add newValue / count
to the average.
Benefits:
Downsides:
BigNumber
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//..do something
//event.stopPropagation(); //if you don't want event to bubble up
});
To reload the same page you don't need the 2nd argument. You can just use:
<meta http-equiv="refresh" content="30" />
This triggers a reload every 30 seconds.
I had the same problem and I chosed to create my own encoder, which will cope by themself with recursion.
I created classes which implements Symfony\Component\Serializer\Normalizer\NormalizerInterface
, and a service which holds every NormalizerInterface
.
#This is the NormalizerService
class NormalizerService
{
//normalizer are stored in private properties
private $entityOneNormalizer;
private $entityTwoNormalizer;
public function getEntityOneNormalizer()
{
//Normalizer are created only if needed
if ($this->entityOneNormalizer == null)
$this->entityOneNormalizer = new EntityOneNormalizer($this); //every normalizer keep a reference to this service
return $this->entityOneNormalizer;
}
//create a function for each normalizer
//the serializer service will also serialize the entities
//(i found it easier, but you don't really need it)
public function serialize($objects, $format)
{
$serializer = new Serializer(
array(
$this->getEntityOneNormalizer(),
$this->getEntityTwoNormalizer()
),
array($format => $encoder) );
return $serializer->serialize($response, $format);
}
An example of a Normalizer :
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class PlaceNormalizer implements NormalizerInterface {
private $normalizerService;
public function __construct($normalizerService)
{
$this->service = normalizerService;
}
public function normalize($object, $format = null) {
$entityTwo = $object->getEntityTwo();
$entityTwoNormalizer = $this->service->getEntityTwoNormalizer();
return array(
'param' => object->getParam(),
//repeat for every parameter
//!!!! this is where the entityOneNormalizer dealt with recursivity
'entityTwo' => $entityTwoNormalizer->normalize($entityTwo, $format.'_without_any_entity_one') //the 'format' parameter is adapted for ignoring entity one - this may be done with different ways (a specific method, etc.)
);
}
}
In a controller :
$normalizerService = $this->get('normalizer.service'); //you will have to configure services.yml
$json = $normalizerService->serialize($myobject, 'json');
return new Response($json);
The complete code is here : https://github.com/progracqteur/WikiPedale/tree/master/src/Progracqteur/WikipedaleBundle/Resources/Normalizer
Let's enjoy some hacky things:
Here is a Style
of Slider
as a NumericUpDown
, simple and easy to use, without any hidden code or third party library.
<Style TargetType="{x:Type Slider}">
<Style.Resources>
<Style x:Key="RepeatButtonStyle" TargetType="{x:Type RepeatButton}">
<Setter Property="Focusable" Value="false" />
<Setter Property="IsTabStop" Value="false" />
<Setter Property="Padding" Value="0" />
<Setter Property="Width" Value="20" />
</Style>
</Style.Resources>
<Setter Property="Stylus.IsPressAndHoldEnabled" Value="false" />
<Setter Property="SmallChange" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Slider}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.RowSpan="2"
Height="Auto"
Margin="0" Padding="0" VerticalAlignment="Stretch" VerticalContentAlignment="Center"
Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Value}" />
<RepeatButton Grid.Row="0" Grid.Column="1" Command="{x:Static Slider.IncreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
<Path Data="M4,0 L0,4 8,4 Z" Fill="Black" />
</RepeatButton>
<RepeatButton Grid.Row="1" Grid.Column="1" Command="{x:Static Slider.DecreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
<Path Data="M0,0 L4,4 8,0 Z" Fill="Black" />
</RepeatButton>
<Border x:Name="TrackBackground" Visibility="Collapsed">
<Rectangle x:Name="PART_SelectionRange" Visibility="Collapsed" />
</Border>
<Thumb x:Name="Thumb" Visibility="Collapsed" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
With bootstrap3-typeahead, I made it to work with the following code:
<input id="typeahead-input" type="text" data-provide="typeahead" />
<script type="text/javascript">
jQuery(document).ready(function() {
$('#typeahead-input').typeahead({
source: function (query, process) {
return $.get('search?q=' + query, function (data) {
return process(data.search_results);
});
}
});
})
</script>
The backend provides search service under the search
GET endpoint, receiving the query in the q
parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }
. The elements of the search_results
array are displayed in the typeahead input.
Throwable
is super class of Exception
as well as Error
. In normal cases we should always catch sub-classes of Exception
, so that the root cause doesn't get lost.
Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error
or Throwable
.
I remember catching Throwable to flag that a native library is not loaded.
Try this :
$('body, html').css('overflow', 'hidden');
var screenWidth1 = $(window).width();
$('body, html').css('overflow', 'visible');
var screenWidth2 = $(window).width();
alert(screenWidth1); // Gives the screenwith without scrollbar
alert(screenWidth2); // Gives the screenwith including scrollbar
You can get the screen width by with and without scroll bar by using this code.
Here, I have changed the overflow value of body
and get the width with and without scrollbar.
I think a Do Until
-loop is cleaner, shorter and more appropriate here:
Public Sub SelectFirstBlankCell(col As String)
Dim Column_Index as Integer
Dim Row_Counter as
Column_Index = Range(col & 1).Column
Row_Counter = 1
Do Until IsEmpty(Cells(Row_Counter, 1))
Row_Counter = Row_Counter + 1
Loop
Cells(Row_Counter, Column_Index).Select
You can get one of following ways
$("#list").find('option').filter('[value=2]').text()
$("#list").find('option[value=2]').text()
$("#list").children('option[value=2]').text()
$("#list option[value='2']").text()
$(function(){ _x000D_
_x000D_
console.log($("#list").find('option').filter('[value=2]').text());_x000D_
console.log($("#list").find('option[value=2]').text());_x000D_
console.log($("#list").children('option[value=2]').text());_x000D_
console.log($("#list option[value='2']").text());_x000D_
_x000D_
});
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<select id='list'>_x000D_
<option value='1'>Option A</option>_x000D_
<option value='2'>Option B</option>_x000D_
<option value='3'>Option C</option>_x000D_
</select>
_x000D_
On my pc I need to do the following:
@echo off
start C:\"Program Files (x86)\VirtualDJ\virtualdj_pro.exe"
start C:\toolbetech\TBETECH\"Your Toolbar.exe"
exit
If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:
sys.path.insert(1, path_to_dev_pyworkbooks)
This could be important since 3rd party code may rely on sys.path documentation conformance:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.
As other have alluded, 7-zip is great.
Note: I am going to zip and then unzip a file. Unzip is at the bottom.
My contribution:
Get the
7-Zip Command Line Version
Current URL
http://www.7-zip.org/download.html
The syntax?
You can put the following into a .bat file
"C:\Program Files\7-Zip\7z.exe" a MySuperCoolZipFile.zip "C:\MyFiles\*.jpg" -pmypassword -r -w"C:\MyFiles\" -mem=AES256
I've shown a few options.
-r is recursive. Usually what you want with zip functionality.
a is for "archive". That's the name of the output zip file.
-p is for a password (optional)
-w is a the source directory. This will nest your files correctly in the zip file, without extra folder information.
-mem is the encryption strength.
There are others. But the above will get you running.
NOTE: Adding a password will make the zip file unfriendly when it comes to viewing the file through Windows Explorer. The client may need their own copy of 7-zip (or winzip or other) to view the contents of the file.
EDIT::::::::::::(just extra stuff).
There is a "command line" version which is probably better suited for this: http://www.7-zip.org/download.html
(current (at time of writing) direct link) http://sourceforge.net/projects/sevenzip/files/7-Zip/9.20/7za920.zip/download
So the zip command would be (with the command line version of the 7 zip tool).
"C:\WhereIUnzippedCommandLineStuff\7za.exe" a MySuperCoolZipFile.zip "C:\MyFiles\*.jpg" -pmypassword -r -w"C:\MyFiles\" -mem=AES256
Now the unzip portion: (to unzip the file you just created)
"C:\WhereIUnzippedCommandLineStuff\7zipCommandLine\7za.exe" e MySuperCoolZipFile.zip "*.*" -oC:\SomeOtherFolder\MyUnzippedFolder -pmypassword -y -r
As an alternative to the "e" argument, there is a x argument.
e: Extract files from archive (without using directory names)
x: eXtract files with full paths
Documentation here:
http://sevenzip.sourceforge.jp/chm/cmdline/commands/extract.htm
The new way to do this is a lot more simple and will save you some time! Just pass the event into the original click handler and call preventDefault();
.
clickHandler(e){
e.preventDefault();
//Your functionality here
}
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
They don't exist in MySQL do they? Just use a temp table:
CREATE PROCEDURE my_proc () BEGIN
CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100));
INSERT INTO TempTable SELECT tblid, tblfield FROM Table1;
/* Do some more stuff .... */
From MySQL here
"You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)"
To elaborate more on some answers that have mentioned -webkit-text-stroke, here's is the code to make it work:
div {
-webkit-text-fill-color: black;
-webkit-text-stroke-color: red;
-webkit-text-stroke-width: 2.00px;
}
An in-depth article about using text stroke is here and a list of browsers that support text stroke is here.
To find how many records are duplicates in name column in Employee, the query below is helpful;
Select name from employee group by name having count(*)>1;
For an NTLM Authentication Proxy:
File -> Settings -> Project Settings -> Gradle -> Global Gradle Settings -> Gradle VM Options
-Dhttp.proxyHost=myProxyAddr -Dhttp.proxyPort=myProxyPort -Dhttp.proxyUser=myUsername -Dhttp.proxyPassword=myPasswd -Dhttp.auth.ntlm.domain=myDomainName
Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:
package test;
public class Demo {
public Demo() {
System.out.println("Hi!");
}
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("test.Demo");
Demo demo = (Demo) clazz.newInstance();
}
}
As explained in its javadoc, calling Class.forName(String)
returns the Class
object associated with the class or interface with the given string name i.e. it returns test.Demo.class
which is affected to the clazz
variable of type Class
.
Then, calling clazz.newInstance()
creates a new instance of the class represented by this Class
object. The class is instantiated as if by a new
expression with an empty argument list. In other words, this is here actually equivalent to a new Demo()
and returns a new instance of Demo
.
And running this Demo
class thus prints the following output:
Hi!
The big difference with the traditional new
is that newInstance
allows to instantiate a class that you don't know until runtime, making your code more dynamic.
A typical example is the JDBC API which loads, at runtime, the exact driver required to perform the work. EJBs containers, Servlet containers are other good examples: they use dynamic runtime loading to load and create components they don't know anything before the runtime.
Actually, if you want to go further, have a look at Ted Neward paper Understanding Class.forName() that I was paraphrasing in the paragraph just above.
EDIT (answering a question from the OP posted as comment): The case of JDBC drivers is a bit special. As explained in the DriverManager chapter of Getting Started with the JDBC API:
(...) A
Driver
class is loaded, and therefore automatically registered with theDriverManager
, in one of two ways:
by calling the method
Class.forName
. This explicitly loads the driver class. Since it does not depend on any external setup, this way of loading a driver is the recommended one for using theDriverManager
framework. The following code loads the classacme.db.Driver
:Class.forName("acme.db.Driver");
If
acme.db.Driver
has been written so that loading it causes an instance to be created and also callsDriverManager.registerDriver
with that instance as the parameter (as it should do), then it is in theDriverManager
's list of drivers and available for creating a connection.(...)
In both of these cases, it is the responsibility of the newly-loaded
Driver
class to register itself by callingDriverManager.registerDriver
. As mentioned, this should be done automatically when the class is loaded.
To register themselves during initialization, JDBC driver typically use a static initialization block like this:
package acme.db;
public class Driver {
static {
java.sql.DriverManager.registerDriver(new Driver());
}
...
}
Calling Class.forName("acme.db.Driver")
causes the initialization of the acme.db.Driver
class and thus the execution of the static initialization block. And Class.forName("acme.db.Driver")
will indeed "create" an instance but this is just a consequence of how (good) JDBC Driver are implemented.
As a side note, I'd mention that all this is not required anymore with JDBC 4.0(added as a default package since Java 7) and the new auto-loading feature of JDBC 4.0 drivers. See JDBC 4.0 enhancements in Java SE 6.
You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.
import locale
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
pd.set_option("float_format", locale.currency)
df = pd.DataFrame(
[123.4567, 234.5678, 345.6789, 456.7890],
index=["foo", "bar", "baz", "quux"],
columns=["cost"],
)
print(df)
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
If you are creating the SVG programmatically you can simplify it and do something like this:
<g>
<rect x={x} y={y} width={width} height={height} />
<text
x={x + width / 2}
y={y + height / 2}
dominant-baseline="middle"
text-anchor="middle"
>
{label}
</text>
</g>
All the answers given so far deal with commands that terminate and output a non-empty string.
Most are broken in the following senses:
yes
).So to fix all these issues, and to answer the following question efficiently,
How can I test if a command outputs an empty string?
you can use:
if read -n1 -d '' < <(command_here); then
echo "Command outputs something"
else
echo "Command doesn't output anything"
fi
You may also add some timeout so as to test whether a command outputs a non-empty string within a given time, using read
's -t
option. E.g., for a 2.5 seconds timeout:
if read -t2.5 -n1 -d '' < <(command_here); then
echo "Command outputs something"
else
echo "Command doesn't output anything"
fi
Remark. If you think you need to determine whether a command outputs a non-empty string, you very likely have an XY problem.
I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers
still had the old server name.
I had to drop the old server name and add the new server name to sys.servers
on the new server
sp_dropserver 'Server_A'
GO
sp_addserver 'Server',local
GO
You should take a look at Batarang for AngularJS debugging
As for your issue:
Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show
<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
</div>
</div>
</div>
</div>
<!-- End of Confirmation Dialog -->
Usually when I get these kinds of errors, opening the __init__.py
file and poking around helps. Go to the directory C:\Python27\lib\site-packages\sklearn
and ensure that there's a sub-directory called __check_build
as a first step. On my machine (with a working sklearn installation, Mac OSX, Python 2.7.3) I have __init__.py
, setup.py
, their associated .pyc
files, and a binary _check_build.so
.
Poking around the __init__.py
in that directory, the next step I'd take is to go to sklearn/__init__.py
and comment out the import statement---the check_build stuff just checks that things were compiled correctly, it doesn't appear to do anything but call a precompiled binary. This is, of course, at your own risk, and (to be sure) a work around. If your build failed you'll likely soon run into other, bigger problems.
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});
Using writing-mode
and transform
.
.rotate {
writing-mode: vertical-lr;
-webkit-transform: rotate(-180deg);
-moz-transform: rotate(-180deg);
}
<span class="rotate">Hello</span>
For windows system
Open putty
then login in server
If you want to see screen in Console then you have to write command
Screen -ls
if you have to access the screen then you have to use below command
screen -x screen id
Write PWD
in command line to check at which folder you are currently
Here is an example of the practical significance of the difference and how it can bite you if you don't realize it (document.location being an object and document.location.href being a string):
We use MonoX Social CMS (http://mono-software.com) free version at http://social.ClipFlair.net and we wanted to add the language bar WebPart at some pages to localize them, but at some others (e.g. at discussions) we didn't want to use localization. So we made two master pages to use at all our .aspx (ASP.net) pages, in the first one we had the language bar WebPart and the other one had the following script to remove the /lng/el-GR etc. from the URLs and show the default (English in our case) language instead for those pages
<script>
var curAddr = document.location; //MISTAKE
var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
if (curAddr != newAddr)
document.location = newAddr;
</script>
But this code isn't working, replace function just returns Undefined (no exception thrown) so it tries to navigate to say x/lng/el-GR/undefined instead of going to url x. Checking it out with Mozilla Firefox's debugger (F12 key) and moving the cursor over the curAddr variable it was showing lots of info instead of some simple string value for the URL. Selecting Watch from that popup you could see in the watch pane it was writing "Location -> ..." instead of "..." for the url. That made me realize it was an object
One would have expected replace to throw an exception or something, but now that I think of it the problem was that it was trying to call some non-existent "replace" method on the URL object which seems to just give back "undefined" in Javascript.
The correct code in that case is:
<script>
var curAddr = document.location.href; //CORRECT
var newAddr = curAddr.replace(new RegExp("/lng/[a-z]{2}-[A-Z]{2}", "gi"), "");
if (curAddr != newAddr)
document.location = newAddr;
</script>
I solved the problem.
In my apache, I have to specify:
PHPIniDir "C://php" AddType application/x-httpd-php .php
and for php.ini, instead of using the php.ini_recommend, use php.ini_dist to configure my php.ini.
then make sure the php engine has turned on. then it works now. Thanks all.
note you can use several else...if statements in your lambda definition:
f = lambda x: 1 if x>0 else 0 if x ==0 else -1
You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.
The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:
The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)
Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.
If you're asking when you should use what, I generally use print_r()
for displaying values and var_dump()
for when having issues with variable types.