The LSP is a rule about the contract of the clases: if a base class satisfies a contract, then by the LSP derived classes must also satisfy that contract.
In Pseudo-python
class Base:
def Foo(self, arg):
# *... do stuff*
class Derived(Base):
def Foo(self, arg):
# *... do stuff*
satisfies LSP if every time you call Foo on a Derived object, it gives exactly the same results as calling Foo on a Base object, as long as arg is the same.
If all you want is calling ravel
on your (nested, I s'pose?) list, you can do that directly, numpy
will do the casting for you:
L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)
Also worth mentioning that you needn't go through numpy
at all.
What system are you using? Webpack? Vue-loader?
I'll only brainstorming here...
Because .png is not a JavaScript file, you will need to configure Webpack to use file-loader or url-loader to handle them. The project scaffolded with vue-cli has also configured this for you.
You can take a look at webpack.conf.js
in order to see if it's well configured like
...
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
...
/assets
is for files that are handles by webpack during bundling - for that, they have to be referenced somewhere in your javascript code.
Other assets can be put in /static
, the content of this folder will be copied to /dist
later as-is.
I recommend you to try to change:
iconUrl: './assets/img.png'
to
iconUrl: './dist/img.png'
You can read the official documentation here: https://vue-loader.vuejs.org/en/configurations/asset-url.html
Hope it helps to you!
In webforms you could also render almost whole html by hand, except few tags like viewstate, eventvalidation and similar, which can be removed with PageAdapters. Nobody force you to use GridView or some other server side control that has bad html rendering output.
I would say that biggest advantage of MVC is SPEED!
Next is forced separation of concern. But it doesn't forbid you to put whole BL and DAL logic inside Controller/Action! It's just separation of view, which can be done also in webforms (MVP pattern for example). A lot of things that people mentions for mvc can be done in webforms, but with some additional effort.
Main difference is that request comes to controller, not view, and those two layers are separated, not connected via partial class like in webforms (aspx + code behind)
When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl
annotation on a create method in the ObjectFactory
class. Since you are creating the JAXBContext
on just the DocumentType
class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext
on the generated package name or ObjectFactory
class to ensure all the necessary metadata is processed.
Example solution:
JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();
There is no if-else, just if.
<c:if test="${user.age ge 40}">
You are over the hill.
</c:if>
Optionally you can use choose-when:
<c:choose>
<c:when test="${a boolean expr}">
do something
</c:when>
<c:when test="${another boolean expr}">
do something else
</c:when>
<c:otherwise>
do this when nothing else is true
</c:otherwise>
</c:choose>
The outcome sql will be different but the result should be the same:
var shifts = Shifts.Where(s => !EmployeeShifts.Where(es => es.ShiftID == s.ShiftID).Any());
I found out that composer runs with the php-version /usr/bin/env finds first in $PATH, which is 7.1.33 in my case on MacOs. So shifting mamp's php to the beginning helped me here.
PHPVER=$(/usr/libexec/PlistBuddy -c "print phpVersion" ~/Library/Preferences/de.appsolute.mamppro.plist)
export PATH=/Applications/MAMP/bin/php/php${PHPVER}/bin:$PATH
1) in a query window in SQL Server Management Studio, run the command:
SET SHOWPLAN_ALL ON
2) run your slow query
3) your query will not run, but the execution plan will be returned. store this output
4) run your fast version of the query
5) your query will not run, but the execution plan will be returned. store this output
6) compare the slow query version output to the fast query version output.
7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.
This might work for you:
printf "{new\nto\nlinux}" | paste -sd' '
{new to linux}
or:
printf "{new\nto\nlinux}" | tr '\n' ' '
{new to linux}
or:
printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
RecyclerView
is, by default, unaware of your dataset changes.
This means that whenever you make a deletion/addition on your data list, those changes won't be reflected to your RecyclerView directly. (i.e. you remove the item at index 5, but the 6th element remains in your recycler view).
RecyclerView
exposes some methods for you to communicate your dataset changes, reflecting those changes directly on your list items.
The standard Android APIs allow you to bind the process of data removal (for the purpose of the question) with the process of View removal.
The methods we talked about are:
notifyItemChanged(index: Int)
notifyItemInserted(index: Int)
notifyItemRemoved(index: Int)
notifyItemRangeChanged(startPosition: Int, itemCount: Int)
notifyItemRangeInserted(startPosition: Int, itemCount: Int)
notifyItemRangeRemoved(startPosition: Int, itemCount: Int)
If you don't properly specify what happens on each addition, change or removal of items, RecyclerView
children are animated unresponsively because of a lack of information about how to move the different views around the list.
Instead, the following code will precisely play the animation, just on the child that is being removed (And as a side note, it fixed any IndexOutOfBoundException
s, marked by the stacktrace as "data inconsistency").
void remove(position: Int) {
dataset.removeAt(position)
notifyItemChanged(position)
notifyItemRangeRemoved(position, 1)
}
Under the hood, if we look into RecyclerView
we can find documentation explaining that the second parameter we pass to notifyItemRangeRemoved
is the number of items that are removed from the dataset, not the total number of items (As wrongly reported in some others information sources).
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Previous position of the first item that was removed
* @param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
Do not use any of those functions. That's my personal view. They are counterintuitive, error-prone and they feel really verbose and unnecessary. Let a library like FastAdapter, Epoxy or Groupie take care of this business, or use an observable recycler view with data binding.
If you are working with Spyder, use CTRL + . (DOT) and you will restart the kernel, also you will stop the program.
You are trying to min-max scale the values of audio
between -1 and +1 and image
between 0 and 255.
Using sklearn.preprocessing.minmax_scale
, should easily solve your problem.
e.g.:
audio_scaled = minmax_scale(audio, feature_range=(-1,1))
and
shape = image.shape
image_scaled = minmax_scale(image.ravel(), feature_range=(0,255)).reshape(shape)
note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.
I came across this issue recently. I used PuPHPet to generate a config.
To connect to MySQL through SSH, the "vagrant" password was not working for me, instead I had to authenticate through the SSH key file.
To connect with MySQL Workbench
Connection method
Standard TCP/IP over SSH
SSH
Hostname: 127.0.0.1:2222 (forwarded SSH port)
Username: vagrant
Password: (do not use)
SSH Key File: C:\vagrantpath\puphpet\files\dot\ssh\insecure_private_key
(Locate your insercure_private_key)
MySQL
Server Port: 3306
username: (root, or username)
password: (password)
Test the connection.
Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.
import matplotlib.pyplot as plt
from matplotlib import interactive
plt.figure(1)
... code to make figure (1)
interactive(True)
plt.show()
plt.figure(2)
... code to make figure (2)
plt.show()
plt.figure(3)
... code to make figure (3)
interactive(False)
plt.show()
Well, a jar-file is just a zip-file, so if you unzip it (with your favorite unzipping utility), you get all the files inside.
If you want to look inside the class files to see the methods, you'll need a tool for that. As PhiLho mentions, Eclipse is able to do that (by default), and I would think most Java IDEs are capable of that.
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
The advantages of EditorFor
is that your code is not tied to an <input type="text"
. So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div
you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml
) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor
you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
I use <span style="display: inline-block; width: 2ch;">	</span>
for a two characters wide tab.
select columns
from table
where (
column like 'a%'
or column like 'b%' )
order by column asc
Use for a date three days ago:
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);
Check the DATE_ADD documentation.
Or you can use:
WHERE t.date >= ( CURDATE() - INTERVAL 3 DAY )
This will surely help you.
int n[] = {4,6,9,1,7};
for(int i=n.length;i>=0;i--){
for(int j=0;j<n.length-1;j++){
if(n[j] > n[j+1]){
swapNumbers(j,j+1,n);
}
}
}
printNumbers(n);
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
This error is shown when your XCode is old and the related device you are using is updated to latest version. First of all, install the latest Xcode version.
We can solve this issue by following the below steps:-
If everything worked properly, your XCode has a new developer disk image. Close the finder now, and quit your XCode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.
Thanks
If you are using Rails 5 and above, the following solution will work.
#delete based on id
user_id = 50
User.find(id: user_id).delete_all
#delete based on condition
threshold_age = 20
User.where(age: threshold_age).delete_all
https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all
None of the response works for me targeting a phonegapp App.
As the following link points, the solution below works.
@media screen and (device-height: 568px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
// css here
}
Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.
You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.
You could do an outer loop over the array
$.each(data.programs, function(index) {
// then loop over the object elements
$.each(data.programs[index], function(key, value) {
console.log(key + ": " + value);
}
}
Yes you can do that.
Here I am renaming a .exe file to .txt file
rename a file
Dim objFso
Set objFso= CreateObject("Scripting.FileSystemObject")
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"
For pyautogui users:
import pyautogui
screenshot = pyautogui.screenshot()
select 'DROP TABLE ' + name from sysobjects
where type = 'U' and sysobjects.name like '%test%'
-- Test is the table name
file = open('parsed_data.txt', 'w')
for link in soup.findAll('a', attrs={'href': re.compile("^http")}): print (link)
soup_link = str(link)
print (soup_link)
file.write(soup_link)
file.flush()
file.close()
In my case, I used BeautifulSoup to write a .txt with Python 3.x. It had the same issue. Just as @tsduteba said, change the 'wb' in the first line to 'w'.
If it's simply about inserting and resizing a picture, try the code below.
For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.
Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.
Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
Dim Pic As Picture, Shp as Shape
Set Pic = wsDestination.Pictures.Insert(FilePath)
Pic.Name = "myPicture"
'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
Set Shp = wsDestination.Shapes("myPicture")
With Shp
.Height = 100
.Width = 75
.LockAspectRatio = msoTrue 'Put this later so that changing height doesn't change width and vice-versa)
.Placement = 1
.Top = 100
.Left = 100
End with
End Sub
Good luck!
When you are going for strict XHTML compliance, you need the CDATA so less than and ampersands are not flagged as invalid characters.
Here's some sample code for that.
<script>
var param1var = getQueryVariable("param1");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
private string GetExtension(string attachment_name)
{
var index_point = attachment_name.IndexOf(".") + 1;
return attachment_name.Substring(index_point);
}
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
The following should do the trick:
div[class^='myclass'], div[class*=' myclass']{
color: #F00;
}
Edit: Added wildcard (*
) as suggested by David
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("c"=>"red","d"=>"black","e"=>"green");
If you are able output your value to the keys of your arrays instead (e.g ->pluck('name', 'id')->toArray() in Eloquent), you can use the following merge method instead
array_keys(array_merge($a1, $a2))
Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps
SELECT p.Name, v.Name
FROM Production.Product p
JOIN Purchasing.ProductVendor pv
ON p.ProductID = pv.ProductID
JOIN Purchasing.Vendor v
ON pv.BusinessEntityID = v.BusinessEntityID
WHERE ProductSubcategoryID = 15
ORDER BY v.Name;
try this
In your model
If u want get all album data use
function get_all_album_data() {
$this->db->select ( '*' );
$this->db->from ( 'Album' );
$this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
$this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
$query = $this->db->get ();
return $query->result ();
}
if u want to get specific album data use
function get_album_data($album_id) {
$this->db->select ( '*' );
$this->db->from ( 'Album' );
$this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
$this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
$this->db->where ( 'Album.album_id', $album_id);
$query = $this->db->get ();
return $query->result ();
}
When the form is submitted, The action will be executed and target the specific iframe to reload.
<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if (isset($_POST['Submit'])){
$Name = $_POST['Name'];
echo $Name;
}
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js">
</script>
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
var descr=document.getElementById('descr').value;
$.ajax({
type:"post",
url:"server_action.php",
data:
{
'name' :name,
'descr' :descr
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
<form >
<input type="" name="name" id="name">
<input type="" name="descr" id="descr">
<input type="submit" name="" value="submit" onclick="return clickButton();">
</form>
<p id="msg"></p>
<?php
$name = $_POST['name'];
$descr = $_POST['descr'];
echo $name;
echo $descr;
?>
scrollViewObject.fullScroll(ScrollView.FOCUS_UP)
this works fine, but only the problem with this line is that, when data is populating in scrollViewObject, has been called immediately. You have to wait for some milliseconds until data is populated. Try this code:
scrollViewObject.postDelayed(new Runnable() {
@Override
public void run() {
scroll.fullScroll(ScrollView.FOCUS_UP);
}
}, 600);
OR
scrollViewObject.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollViewObject.getViewTreeObserver().removeOnGlobalLayoutListener(this);
scrollViewObject.fullScroll(View.FOCUS_UP);
}
});
Can be done in major new broswers using the code below
.img {
-webkit-filter:invert(100%);
filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}
However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.
I've been using GUIDs as PKs since 2005. In this distributed database world, it is absolutely the best way to merge distributed data. You can fire and forget merge tables without all the worry of ints matching across joined tables. GUIDs joins can be copied without any worry.
This is my setup for using GUIDs:
PK = GUID. GUIDs are indexed similar to strings, so high row tables (over 50 million records) may need table partitioning or other performance techniques. SQL Server is getting extremely efficient, so performance concerns are less and less applicable.
PK Guid is NON-Clustered index. Never cluster index a GUID unless it is NewSequentialID. But even then, a server reboot will cause major breaks in ordering.
Add ClusterID Int to every table. This is your CLUSTERED Index... that orders your table.
Joining on ClusterIDs (int) is more efficient, but I work with 20-30 million record tables, so joining on GUIDs doesn't visibly affect performance. If you want max performance, use the ClusterID concept as your primary key & join on ClusterID.
Here is my Email table...
CREATE TABLE [Core].[Email] (
[EmailID] UNIQUEIDENTIFIER CONSTRAINT [DF_Email_EmailID] DEFAULT (newsequentialid()) NOT NULL,
[EmailAddress] NVARCHAR (50) CONSTRAINT [DF_Email_EmailAddress] DEFAULT ('') NOT NULL,
[CreatedDate] DATETIME CONSTRAINT [DF_Email_CreatedDate] DEFAULT (getutcdate()) NOT NULL,
[ClusterID] INT NOT NULL IDENTITY,
CONSTRAINT [PK_Email] PRIMARY KEY NonCLUSTERED ([EmailID] ASC)
);
GO
CREATE UNIQUE CLUSTERED INDEX [IX_Email_ClusterID] ON [Core].[Email] ([ClusterID])
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_Email_EmailAddress] ON [Core].[Email] ([EmailAddress] Asc)
You should wrap your Container
in a Flexible
to let your Row
know that it's ok for the Container
to be narrower than its intrinsic width. Expanded
will also work.
Flexible(
child: new Container(
padding: new EdgeInsets.only(right: 13.0),
child: new Text(
'Text largeeeeeeeeeeeeeeeeeeeeeee',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 13.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
),
),
I don't know why anyone told you that catching runtime exceptions was bad.
Use valueOf
and catching IllegalArgumentException
is fine for converting/checking a string to an enum.
Besides its use as a placeholder for unimplemented functions, pass
can be useful in filling out an if-else statement ("Explicit is better than implicit.")
def some_silly_transform(n):
# Even numbers should be divided by 2
if n % 2 == 0:
n /= 2
flag = True
# Negative odd numbers should return their absolute value
elif n < 0:
n = -n
flag = True
# Otherwise, number should remain unchanged
else:
pass
Of course, in this case, one would probably use return
instead of assignment, but in cases where mutation is desired, this works best.
The use of pass
here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag
is set in the two specifically mentioned cases, but not in the else
-case. Without using pass
, a future programmer might move flag = True
to outside the condition—thus setting flag
in all cases.
Another case is with the boilerplate function often seen at the bottom of a file:
if __name__ == "__main__":
pass
In some files, it might be nice to leave that there with pass
to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.
Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:
try:
n[i] = 0
except IndexError:
pass
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
Double d = scan.nextDouble();
String newStr = "";
Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
while( charScanner.hasNext() ) {
String c = charScanner.next();
if (c.equalsIgnoreCase("\r")) {
break;
}
else {
newStr += c;
}
}
System.out.println("String: " + newStr);
System.out.println("Int: " + i);
System.out.println("Double: " + d);
This code works fine
You can limit the scope of a playbook by changing the hosts header in its plays without relying on your special host label ‘local’ in your inventory. Localhost does not need a special line in inventories.
- name: run on all except local
hosts: all:!local
The border is been set on the generated tr
and td
elements, not on the table
. So, this should do:
.companyHeaderGrid.ui-panelgrid>*>tr,
.companyHeaderGrid.ui-panelgrid .ui-panelgrid-cell {
border: none;
}
How I found it? Just check the generated HTML output and all CSS style rules in the webdeveloper toolset of Chrome (rightclick, Inspect Element or press F12). Firebug and IE9 have a similar toolset. As to the confusion, just keep in mind that JSF/Facelets ultimately generates HTML and that CSS only applies on the HTML markup, not on the JSF source code. So to apply/finetune CSS you need to look in the client (webbrowser) side instead.
If you're still on PrimeFaces 4 or older, use below instead:
.companyHeaderGrid.ui-panelgrid>*>tr,
.companyHeaderGrid.ui-panelgrid>*>tr>td {
border: none;
}
As suggested, I edited this message to place a proper answer.
The 'physical' location of the mysql databases are under /usr/local/mysql
the mysql is a symlink to the current active mysql installation, in my case the exact folder is mysql-5.6.10-osx10.7-x86_64.
Inside that folder you'll see another data folder, inside it are RESTRICTED folders with your databases.
You can't actually see the size of your databases (that was my issue) from the Finder because the folder are protected, you can though see from the terminal with sudo du -sh /usr/local/mysql/data/{your-database-name}
and like this you'll get a nice formatted output with the size.
In those folder you have different files with all the folders present in your database, so it's safer to check the db's folder to get a size.
That's it. Enjoy!
Sometimes it doesn't get login with username = root
and password
, then you can change the default settings or the reset settings.
Open config.inc.php
file in the phpmyadmin folder
Instead of
$cfg['Servers'][$i]['AllowNoPassword'] = false;
change it to:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Do not specify any password and put the user name as it was before, which means root
.
E.g.
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
This worked for me after i had edited my config.inc.php
file.
You should checkout gitignore.io for Objective-C and Swift.
Here is the .gitignore
file I'm using:
# Xcode
.DS_Store
*/build/*
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
profile
*.moved-aside
DerivedData
.idea/
*.hmap
*.xccheckout
*.xcworkspace
!default.xcworkspace
#CocoaPods
Pods
In new APIs don't forget about TAG:
notify(String tag, int id, Notification notification)
and correspondingly
cancel(String tag, int id)
instead of:
cancel(int id)
https://developer.android.com/reference/android/app/NotificationManager
Unfortunately triggering the onsubmit or submit events wont work in all browsers.
Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.
What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.
<script type="text/javascript">
$(function() {
$('form#ajaxForm').submit(function(event) {
eval($(this).attr('onsubmit')); return false;
});
$('form#ajaxForm').find('a.submit-link').click( function() {
$'form#ajaxForm').submit();
});
}
</script>
<% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
new AjaxOptions
{
UpdateTargetId = "DescriptionDiv",
HttpMethod = "post"
}, new { id = "ajaxForm" } )) {%>
Description:
<%= Html.TextBox("Description", Model.Description) %><br />
<a href="#" class="submit-link">Save</a>
<% } %>
Also, the link doesn't have to be contained within the form in order for this to work.
you can use this site to generate a proxy for you. it generates a class and can parse and validate your input JSON object.
Set-ADUser -Identity anyUser -Replace @{extensionAttribute4="myString"}
This is also usefull
From your description I assume you are on windows machine and your home is abc
So Now : Cause
When you run this command
keytool -genkey -alias tomcat -keyalg RSA
because you are not specifying an explicit keystore it will try to generate (and in your case as you are getting exception so to update) keystore C:\users\abc>.keystore
and of course you need to provide old password for .keystore while I believe you are providing your version (a new one).
Solution
Either delete .keystore
from C:\users\abc>
location and try the command
or try following command which will create a new xyzkeystore:
keytool -genkey -keystore xyzkeystore -alias tomcat -keyalg RSA
Note: -genkey
is old now rather use -genkeypair
althought both work equally.
As he didn't specify which version of SQL server he uses (date
type isn't available in 2005), one could also use
SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed
FROM table_name
GROUP BY CONVERT(VARCHAR(10),date_column,112)
I have try this code
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss Z");
Date datetime = new Date();
System.out.println("date "+sdf.format(datetime));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT "+ sdf.format(datetime));
sdf.setTimeZone(TimeZone.getTimeZone("GMT+13"));
System.out.println("GMT+13 "+ sdf.format(datetime));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("utc "+sdf.format(datetime));
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));
String newZealandTime = formatter.format(calendar.getTime());
System.out.println("using calendar "+newZealandTime);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and getting this result
date 06-10-2011 10:40:05 +0530
GMT 06-10-2011 05:10:05 +0000 // here getting 5:10:05
GMT+13 06-10-2011 06:10:05 +1300 // here getting 6:10:05
utc 06-10-2011 05:10:05 +0000
using calendar 06 Oct 2011 18:10:05 GMT+13:00
It is not finding the controllers, this is basic issues. it can be due to following reasons.
A. inside WEB-INF folder you have file web.xml that refers to dispatcherServlet. Here it this case is mvc-config.xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
B. This mvc-config.xml file have namespaces and it has to scan the controllers.
<context:component-scan base-package="org.vimal.spring.controllers" />
<mvc:annotation-driven />
C. Check for the correctness of the package name where you have the controllers. It should work.
All Controllers must be Annotated with @Controller.
We are not getting the correct results because any javascript generated content needs to be rendered on the DOM. When we fetch an HTML page, we fetch the initial, unmodified by javascript, DOM.
Therefore we need to render the javascript content before we crawl the page.
As selenium is already mentioned many times in this thread (and how slow it gets sometimes was mentioned also), I will list two other possible solutions.
Solution 1: This is a very nice tutorial on how to use Scrapy to crawl javascript generated content and we are going to follow just that.
What we will need:
Docker installed in our machine. This is a plus over other solutions until this point, as it utilizes an OS-independent platform.
Install Splash following the instruction listed for our corresponding OS.
Quoting from splash documentation:
Splash is a javascript rendering service. It’s a lightweight web browser with an HTTP API, implemented in Python 3 using Twisted and QT5.
Essentially we are going to use Splash to render Javascript generated content.
Run the splash server: sudo docker run -p 8050:8050 scrapinghub/splash
.
Install the scrapy-splash plugin: pip install scrapy-splash
Assuming that we already have a Scrapy project created (if not, let's make one), we will follow the guide and update the settings.py
:
Then go to your scrapy project’s
settings.py
and set these middlewares:DOWNLOADER_MIDDLEWARES = { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, }
The URL of the Splash server(if you’re using Win or OSX this should be the URL of the docker machine: How to get a Docker container's IP address from the host?):
SPLASH_URL = 'http://localhost:8050'
And finally you need to set these values too:
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter' HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
Finally, we can use a SplashRequest
:
In a normal spider you have Request objects which you can use to open URLs. If the page you want to open contains JS generated data you have to use SplashRequest(or SplashFormRequest) to render the page. Here’s a simple example:
class MySpider(scrapy.Spider): name = "jsscraper" start_urls = ["http://quotes.toscrape.com/js/"] def start_requests(self): for url in self.start_urls: yield SplashRequest( url=url, callback=self.parse, endpoint='render.html' ) def parse(self, response): for q in response.css("div.quote"): quote = QuoteItem() quote["author"] = q.css(".author::text").extract_first() quote["quote"] = q.css(".text::text").extract_first() yield quote
SplashRequest renders the URL as html and returns the response which you can use in the callback(parse) method.
Solution 2: Let's call this experimental at the moment (May 2018)...
This solution is for Python's version 3.6 only (at the moment).
Do you know the requests module (well who doesn't)?
Now it has a web crawling little sibling: requests-HTML:
This library intends to make parsing HTML (e.g. scraping the web) as simple and intuitive as possible.
Install requests-html: pipenv install requests-html
Make a request to the page's url:
from requests_html import HTMLSession
session = HTMLSession()
r = session.get(a_page_url)
Render the response to get the Javascript generated bits:
r.html.render()
Finally, the module seems to offer scraping capabilities.
Alternatively, we can try the well-documented way of using BeautifulSoup with the r.html
object we just rendered.
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
With the above example, I get around 10fps.
Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.
However, there are a lot of things you can do to speed this example up.
There are two main reasons why this is as slow as it is.
1) Calling fig.canvas.draw()
redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.
2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.
Both these can be fixed by using blitting.
To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.
However, without knowing a bit more about what you're doing, I can't help you there.
Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
This gives me ~200fps.
To make this a bit more convenient, there's an animations
module in recent versions of matplotlib.
As an example:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()
If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.
app.run(debug=True)
Or, from the shell:
$ export FLASK_DEBUG=1
$ flask run
OAuth is a protocol with which a 3-party app can access your data stored in another website without your account and password. For a more official definition, refer to the Wiki or specification.
Here is a use case demo:
I login to LinkedIn and want to connect some friends who are in my Gmail contacts. LinkedIn supports this. It will request a secure resource (my gmail contact list) from gmail. So I click this button:
A web page pops up, and it shows the Gmail login page, when I enter my account and password:
Gmail then shows a consent page where I click "Accept":
Now LinkedIn can access my contacts in Gmail:
Below is a flowchart of the example above:
Step 1: LinkedIn requests a token from Gmail's Authorization Server.
Step 2: The Gmail authorization server authenticates the resource owner and shows the user the consent page. (the user needs to login to Gmail if they are not already logged-in)
Step 3: User grants the request for LinkedIn to access the Gmail data.
Step 4: the Gmail authorization server responds back with an access token.
Step 5: LinkedIn calls the Gmail API with this access token.
Step 6: The Gmail resource server returns your contacts if the access token is valid. (The token will be verified by the Gmail resource server)
You can get more from details about OAuth here.
Some more explanations to the solution Rachel already gave:
"WPF Apps With The Model-View-ViewModel Design Pattern"
by Josh Smith
proceed = "y", "Y"
if answer in proceed:
Also, you don't want
answer = str(input("Is the information correct? Enter Y for yes or N for no"))
You want
answer = raw_input("Is the information correct? Enter Y for yes or N for no")
input()
evaluates whatever is entered as a Python expression, raw_input()
returns a string.
Edit: That is only true on Python 2. On Python 3, input
is fine, although str()
wrapping is still redundant.
If you want filter for one field:
label>Any: <input ng-model="search.color"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">
If you want filter for all field:
label>Any: <input ng-model="search.$"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">
and https://docs.angularjs.org/api/ng/filter/filter good for you
Assuming you mean it's a string, how about strtol?
The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.
Look at this longer list comprehension from the tutorial (the if
part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)
):
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.
On to your questions:
What type must object be in order to use this for loop structure?
An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.
What is the order in which i and j are assigned to elements in object?
They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)
Can it be simulated by a different for loop structure?
Yes, already shown above.
Can this for loop be nested with a similar or different structure for loop? And how would it look?
Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:
[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]
Changing the index variable i
from within the loop is unlikely to do what you expect. You may need to use a while
loop instead, and control the incrementing of the loop variable yourself. Each time around the for
loop, i
is reassigned with the next value from range()
. So something like:
i = 2
while i < n:
if(something):
do something
else:
do something else
i = 2 # restart the loop
continue
i += 1
In my example, the continue
statement jumps back up to the top of the loop, skipping the i += 1
statement for that iteration. Otherwise, i
is incremented as you would expect (same as the for
loop).
The filename should go at the end of the path to the directory. That is, it should be the full path to the file. You are doing this from a command line, and you have a working directory for that command line (on your local machine), this is the directory that your file will be downloaded to. The final argument in your command is only what you want the name of the file to be. So, first, change directory to where you want the file to land. I'm doing this from git bash on a Windows machine, so it looks like this:
cd C:\Users\myUserName\Downloads
Now that I have my working directory where I want the file to go:
scp -i 'c:\Users\myUserName\.ssh\AWSkeyfile.pem' [email protected]:/home/ec2-user/IwantThisFile.tar IgotThisFile.tar
Or, in your case:
cd /local/path/where/you/want/the/file/to/land
scp [email protected]:/local/machine/path/to/directory/filename filename
I used the following trick for the same problem. The good thing is it doesn't require any javascript.
CSS:
.body {
margin: 0em;
}
.page {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: -100vw;
overflow-y: auto;
z-index: 0;
background-color: hsl(0,0%,100%);
}
.page:target {
left: 0vw;
z-index: 1;
}
HTML:
<ul>
<li>Click <a href="#one">here</a> for page 1</li>
<li>Click <a href="#two">here</a> for page 2</li>
</ul>
<div class="page" id="one">
Content of page 1 goes here.
<ul>
<li><a href="#">Back</a></li>
<li><a href="#two">Page 2</a></li>
</ul>
</div>
<div class="page" id="two">
Content of page 2 goes here.
<ul style="margin-bottom: 100vh;">
<li><a href="#">Back</a></li>
<li><a href="#one">Page 1</a></li>
</ul>
</div>
See a JSFiddle.
Added advantage: as your url changes along, you can use it to link to specific pages. This is something the method won't let you do.
Hope this helps!
Look at https://stackoverflow.com/a/4726838/2963099
Turn off pre compiled headers:
Project Properties -> C++ -> Precompiled Headers
set Precompiled Header
to "Not Using Precompiled Header"
.
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [@(result) stringValue];
Be careful, in some cases clicking on a Form Control or Active X Control will give two different results for the same macro - which should not be the case. I find Active X more reliable.
Most of the answers seem to assume that iterative
= for loop
. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for
loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.
All (computable) functions can be implemented both recursively and using while
loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops
, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.
What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).
I just encountered this on an MVC5 application and nothing was working for me. This happened right after I had tried to do an SVN revert to an older version of the project.
I had to delete global.asax.cs and then added a new one by right clicking Project -> Add New Item -> Global.asax and THAT finally fixed it.
Just thought it might help someone.
It is possible to use super to call the method from mother class, but this would mean you probably have a design problem.
Maybe B.alphaMethod1()
shouldn't override A's method and be called B.betaMethod1()
.
If it depends on the situation, you can put some code logic like :
public void alphaMethod1(){
if (something) {
super.alphaMethod1();
return;
}
// Rest of the code for other situations
}
Like this it will only call A's method when needed and will remain invisible for the class user.
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
I know its Too late But I hope it will work new comers Try This Its Working ... :D
select
case
when isnumeric(my_NvarcharColumn) = 1 then
cast(my_NvarcharColumn AS int)
else
NULL
end
AS 'my_NvarcharColumnmitter'
from A
You should write something like
*.class
into your .gitignore
file.
I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.
Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)
You can use __CLASS__
within a class to get the name.
The Google Testing Blog discussed this problem recently:
So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return.
(snip)
These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%. Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.
NOTE: nosid's answer shows how to add to an existing collection using forEachOrdered()
. This is a useful and effective technique for mutating existing collections. My answer addresses why you shouldn't use a Collector
to mutate an existing collection.
The short answer is no, at least, not in general, you shouldn't use a Collector
to modify an existing collection.
The reason is that collectors are designed to support parallelism, even over collections that aren't thread-safe. The way they do this is to have each thread operate independently on its own collection of intermediate results. The way each thread gets its own collection is to call the Collector.supplier()
which is required to return a new collection each time.
These collections of intermediate results are then merged, again in a thread-confined fashion, until there is a single result collection. This is the final result of the collect()
operation.
A couple answers from Balder and assylias have suggested using Collectors.toCollection()
and then passing a supplier that returns an existing list instead of a new list. This violates the requirement on the supplier, which is that it return a new, empty collection each time.
This will work for simple cases, as the examples in their answers demonstrate. However, it will fail, particularly if the stream is run in parallel. (A future version of the library might change in some unforeseen way that will cause it to fail, even in the sequential case.)
Let's take a simple example:
List<String> destList = new ArrayList<>(Arrays.asList("foo"));
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");
newList.parallelStream()
.collect(Collectors.toCollection(() -> destList));
System.out.println(destList);
When I run this program, I often get an ArrayIndexOutOfBoundsException
. This is because multiple threads are operating on ArrayList
, a thread-unsafe data structure. OK, let's make it synchronized:
List<String> destList =
Collections.synchronizedList(new ArrayList<>(Arrays.asList("foo")));
This will no longer fail with an exception. But instead of the expected result:
[foo, 0, 1, 2, 3]
it gives weird results like this:
[foo, 2, 3, foo, 2, 3, 1, 0, foo, 2, 3, foo, 2, 3, 1, 0, foo, 2, 3, foo, 2, 3, 1, 0, foo, 2, 3, foo, 2, 3, 1, 0]
This is the result of the thread-confined accumulation/merging operations I described above. With a parallel stream, each thread calls the supplier to get its own collection for intermediate accumulation. If you pass a supplier that returns the same collection, each thread appends its results to that collection. Since there is no ordering among the threads, results will be appended in some arbitrary order.
Then, when these intermediate collections are merged, this basically merges the list with itself. Lists are merged using List.addAll()
, which says that the results are undefined if the source collection is modified during the operation. In this case, ArrayList.addAll()
does an array-copy operation, so it ends up duplicating itself, which is sort-of what one would expect, I guess. (Note that other List implementations might have completely different behavior.) Anyway, this explains the weird results and duplicated elements in the destination.
You might say, "I'll just make sure to run my stream sequentially" and go ahead and write code like this
stream.collect(Collectors.toCollection(() -> existingList))
anyway. I'd recommend against doing this. If you control the stream, sure, you can guarantee that it won't run in parallel. I expect that a style of programming will emerge where streams get handed around instead of collections. If somebody hands you a stream and you use this code, it'll fail if the stream happens to be parallel. Worse, somebody might hand you a sequential stream and this code will work fine for a while, pass all tests, etc. Then, some arbitrary amount of time later, code elsewhere in the system might change to use parallel streams which will cause your code to break.
OK, then just make sure to remember to call sequential()
on any stream before you use this code:
stream.sequential().collect(Collectors.toCollection(() -> existingList))
Of course, you'll remember to do this every time, right? :-) Let's say you do. Then, the performance team will be wondering why all their carefully crafted parallel implementations aren't providing any speedup. And once again they'll trace it down to your code which is forcing the entire stream to run sequentially.
Don't do it.
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions
I was facing same issue and I just started app with new port and everything looks good.
ng serve --port 4201
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
Since MySQL 5.6.X you can do this:
ALTER TABLE `schema`.`users`
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
That way your column will be updated with the current timestamp when a new row is inserted, or updated.
If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
in the DEFAULT value field, like so:
http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html
You can use reference type in generic arguments, not primitive type. So here you should use
Map<String, Integer> myMap = new HashMap<String, Integer>();
and store value as
myMap.put("abc", 5);
I ran into this error while trying to get a project to run on my local dev box (OSX 10.6), using Sinatra and Postgresql (through activerecord), running on an rvm'd ruby 2.1. I found my answer here: https://github.com/wayneeseguin/rvm/issues/2511
My exact problem (after the first block of log entries):
I also get an error when trying to build native extensions for gems
The answer:
rvm reinstall 2.1.0 --disable-binary
The explanation:
OSX does not have a package manager so all libraries have to be installed manually by user, this makes it virtually impossible to link the binary dynamically, and as you can see there are problems with the (pseudo)statically linked binary.
For the sake of completeness, I had first forgotten to update rvm (rvm get head
), which yielded some other errors, but still needed the --disable-binary
flag once I had done so.
To get Current timezone of the mysql you can do following things:
SELECT @@system_time_zone; # from this you can get the system timezone
SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone) # This will give you time zone if system timezone is different from global timezone
Now if you want to change the mysql timezone then:
SET GLOBAL time_zone = '+00:00'; # this will set mysql timezone in UTC
SET @@session.time_zone = "+00:00"; # by this you can chnage the timezone only for your particular session
Force Stop the application in the device settings.
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
If you just need to search for one string within another, use the index
function (or rindex
if you want to start scanning from the end of the string):
if (index($string, $substring) != -1) {
print "'$string' contains '$substring'\n";
}
To search a string for a pattern match, use the match operator m//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}
How would I accomplish the nextsibling and is there an easier way of doing this?
You may use:
tr/td[@class='name']/following-sibling::td
but I'd rather use directly:
tr[td[@class='name'] ='Brand']/td[@class='desc']
This assumes that:
The context node, against which the XPath expression is evaluated is the parent of all tr
elements -- not shown in your question.
Each tr
element has only one td
with class
attribute valued 'name'
and only one td
with class
attribute valued 'desc'
.
3 steps:
Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);
Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;
Use the code to download stream:
URL u = null;
InputStream is = null;
try {
u = new URL(url);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
int size = huc.getContentLength();
if(huc != null) {
String fileName = "FILE.mp4";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len1 = 0;
if(is != null) {
while ((len1 = is.read(buffer)) > 0) {
fos.write(buffer,0, len1);
}
}
if(fos != null) {
fos.close();
}
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null) {
is.close();
}
} catch (IOException ioe) {
// just going to ignore this one
}
}
That's all, most of stuff you'll find on the web!!!
Note -- Note
do not use "http://www.domain.xxx" or "http://localhost/" or "IP >> 127.0.0.1" for URL in ajax. only use path(directory) and page name without address.
false state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'http://www.example.com/dir/getSecurityCode.php', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
true state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'dir/getSecurityCode.php', true); // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
Use getChildFragmentManager(), follow the link : Nested Fragment
Here's a command to get you started:
FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO @ECHO TaskKill.exe /PID %%P
When you're confident in your batch file, remove @ECHO
.
FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %%P
Note that you might need to change this slightly for different OS's. For example, on Windows 7 you might need tokens=5
instead of tokens=4
.
How this works
FOR /F ... %variable IN ('command') DO otherCommand %variable...
This lets you execute command
, and loop over its output. Each line will be stuffed into %variable
, and can be expanded out in otherCommand
as many times as you like, wherever you like. %variable
in actual use can only have a single-letter name, e.g. %V
.
"tokens=4 delims= "
This lets you split up each line by whitespace, and take the 4th chunk in that line, and stuffs it into %variable
(in our case, %%P
). delims
looks empty, but that extra space is actually significant.
netstat -a -n -o
Just run it and find out. According to the command line help, it "Displays all connections and listening ports.", "Displays addresses and port numbers in numerical form.", and "Displays the owning process ID associated with each connection.". I just used these options since someone else suggested it, and it happened to work :)
^|
This takes the output of the first command or program (netstat
) and passes it onto a second command program (findstr
). If you were using this directly on the command line, instead of inside a command string, you would use |
instead of ^|
.
findstr :8080
This filters any output that is passed into it, returning only lines that contain :8080
.
TaskKill.exe /PID <value>
This kills a running task, using the process ID.
%%P instead of %P
This is required in batch files. If you did this on the command prompt, you would use %P
instead.
Try padding-right
. You're not allowed to put margin
's between cells.
<table>
<tr>
<td style="padding-right: 10px;">one</td>
<td>two</td>
</tr>
</table>
As others have said, only firefox supports this. Here is a work around that does the same thing, and even works with dashed outlines.
.has-outline {_x000D_
display: inline-block;_x000D_
background: #51ab9f;_x000D_
border-radius: 10px;_x000D_
padding: 5px;_x000D_
position: relative;_x000D_
}_x000D_
.has-outline:after {_x000D_
border-radius: 10px;_x000D_
padding: 5px;_x000D_
border: 2px dashed #9dd5cf;_x000D_
position: absolute;_x000D_
content: '';_x000D_
top: -2px;_x000D_
left: -2px;_x000D_
bottom: -2px;_x000D_
right: -2px;_x000D_
}
_x000D_
<div class="has-outline">_x000D_
I can haz outline_x000D_
</div>
_x000D_
You're on the right track. The two constructors accept arguments, or you can specify them post-construction with ProcessBuilder#command(java.util.List)
and ProcessBuilder#command(String...)
.
You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input name="q1_a" type="text" value="1A"/>
<input name="q1_b" type="text" value="1B"/>
<input name="q1_c" type="text" value="1C"/>
<input name="q2_d" type="text" value="2D"/>
<script type="text/javascript">
var inputs = document.getElementsByTagName("input");
for (x = 0 ; x < inputs.length ; x++){
myname = inputs[x].getAttribute("name");
if(myname.indexOf("q1_")==0){
alert(myname);
// do more stuff here
}
}
</script>
</body>
</html>
After git commit
command, you entered to the editor, so first hit i
then start typing. After committing your message hit Ctrl + c
then :wq
Just to be different, changed my answer so that this question doesn't have 5 answers with the same code.
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
var select = $("body").append('<form></form>').children('form')
.append('<input type="hidden" value="" />').children('input[type=hidden]')
.attr('id', 'hiddenValue').end()
.append('<select></select>').children('select')
.attr('id', 'dropdown')
.change(function() {
alert($(this).val());
});
$.each({ one: 1, two: 2, three: 3, four: 4, five: 5 }, function(txt, val) {
select.append('<option value="' + val + '">' + txt + '</option>');
});
});
</script>
</head>
<body></body>
</html>
Regarding number of days in month just use static switch command and check if (year % 4 == 0)
in which case February will have 29 days.
Minute, hour, day etc:
var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));
There are a number of answers talking about Array.prototype.push.apply. Here is a clear example:
var dataArray1 = [1, 2];_x000D_
var dataArray2 = [3, 4, 5];_x000D_
var newArray = [ ];_x000D_
Array.prototype.push.apply(newArray, dataArray1); // newArray = [1, 2]_x000D_
Array.prototype.push.apply(newArray, dataArray2); // newArray = [1, 2, 3, 4, 5]_x000D_
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]
_x000D_
If you have ES6 syntax:
var dataArray1 = [1, 2];_x000D_
var dataArray2 = [3, 4, 5];_x000D_
var newArray = [ ];_x000D_
newArray.push(...dataArray1); // newArray = [1, 2]_x000D_
newArray.push(...dataArray2); // newArray = [1, 2, 3, 4, 5]_x000D_
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]
_x000D_
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
you need to add Content-Length: 0
in your request header.
a very descriptive example of how to test is given here
you can see the solution on http://jsfiddle.net/CBQCA/1/
OR
<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
<tr style="height: 25%;">
<td>Region</td>
</tr>
<tr style="height: 75%;">
<td>100.00%</td>
</tr>
</table>?
I removed the font size, to show that columns are expanded.
I added border:1px solid
just to make sure table is expanded. you can remove it.
function currencyFormat (num) {
return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}
console.info(currencyFormat(2665)); // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00
For someone who want to use onchange event directly on file input, set onchange="somefunction()
, example code from the link:
<html>
<body>
<script language="JavaScript">
function inform(){
document.form1.msg.value = "Filename has been changed";
}
</script>
<form name="form1">
Please choose a file.
<input type="file" name="uploadbox" size="35" onChange='inform()'>
<br><br>
Message:
<input type="text" name="msg" size="40">
</form>
</body>
</html>
You must reference Context name before using getResources()
in Android.
String user=getApplicationContext().getResources().getString(R.string.muser);
OR
Context mcontext=getApplicationContext();
String user=mcontext.getResources().getString(R.string.muser);
this works for ubuntu 15.10:
sudo locale-gen "en_US.UTF-8"
sudo dpkg-reconfigure locales
Isn't the platform solution for this implementation to use a context menu that shows on a long press?
Is the question author aware of context menus? Stacking up buttons in a listview has performance implications, will clutter your UI and violate the recommended UI design for the platform.
On the flipside; context menus - by nature of not having a passive representation - are not obvious to the end user. Consider documenting the behaviour?
This guide should give you a good start.
http://www.mikeplate.com/2010/01/21/show-a-context-menu-for-long-clicks-in-an-android-listview/
Hey This was my problem with my Visual basic net 2005 This is How i got it solved:
1.Click start :-> type run (Or press win+r) 2.Type regedit 3.Click HKEY_CLASSES_ROOT 4.Click Licenses 5.Double click (Default) 6.clear all text written in Value data field 6.Press Ok 7.Run again Microsoft visual studio
Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.
void Main()
{
var x = new
{
items = new[]
{
new
{
name = "command", index = "X", optional = "0"
},
new
{
name = "command", index = "X", optional = "0"
}
}
};
JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
Console.WriteLine(js.Serialize(x));
}
result :
{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}
I'm not sure why you're avoiding the AND clause. It is the simplest solution.
Otherwise, you would need to do an INTERSECT of multiple queries:
SELECT word FROM table WHERE word NOT LIKE '%a%'
INTERSECT
SELECT word FROM table WHERE word NOT LIKE '%b%'
INTERSECT
SELECT word FROM table WHERE word NOT LIKE '%c%';
Alternatively, you can use a regular expression if your version of SQL supports it.
You have a couple of problems here.
First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.
Change:
<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/>
To:
<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/>
And:
Stock
Stock
So:
<xsd:element name="Stock">
<xsd:complexType>
To:
<xsd:complexType name="Stock">
Make sure you fix the xml closing tags.
The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:
INCORRECT: (the way you showed it)
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
CORRECT:
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />
</schema>
</types>
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.
It would be better if you go the WS-I way when it comes to WSDL authoring.
Other issues may be related to the use of relative vs. absolute URIs in locating external content.
You're targeting the wrong item with that jQuery selector. The name
of your search bar is searchBar
, not the id
. What you want to use is $('#main_search').val('hi')
.
You need to use the Thread.sleep()
method.
This is used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.
FYI (Summary taken from here)
Java Thread Sleep important points
You can try the display:inline-block and :after.Like this:
<ul>
<li><a href="">I would like this text centered vertically</a></li>
</ul>
li a {
width: 300px;
height: 100px;
margin: auto 0;
display: inline-block;
vertical-align: middle;
background: red;
}
li a:after {
content:"";
display: inline-block;
width: 1px solid transparent;
height: 100%;
vertical-align: middle;
}
Please view the demo.
Solutions proposed here either didn't work for me or where to large, so I was looking for something else and found the solution proposed by @dighan on bountysource.com/issues/
So here is the code that solved my problem:
var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
playPromise.catch(() => { media.play(); })
}
It still throws an error into console, but at least the video is playing :)
Invisible: The widget takes physical space on the screen but not visible to user.
Gone: The widget doesn't take any physical space and is completely gone.
Invisible example
Visibility(
child: Text("Invisible"),
maintainSize: true,
maintainAnimation: true,
maintainState: true,
visible: false,
),
Gone example
Visibility(
child: Text("Gone"),
visible: false,
),
Alternatively, you can use if
condition for both invisible and gone.
Column(
children: <Widget>[
if (show) Text("This can be visible/not depending on condition"),
Text("This is always visible"),
],
)
There will not be any harm deleting the forked repositories. You can again fork that. It won't change the original code. The flow is like this...
1) You fork a repository. Just think of this as another copy of code which you can access or make changes to. The url of this repository will be of the form https://github.com/your-user-name/original-repo
.
2) You make some changes to that in your local machine and push them. Now the copy you created will be updated, but not the original one from which you have forked your repo.
3) If you want the changes you added to your forked repo to be applied to original repo(this may be helpful to the people who are organizing the repo) then you have to create a pull request
which you can do through UI. Then if they like your contribution, they will merge
that with their code.
Generally this is what open source organizations do.
No, there is no way to only set the opacity of a border with css.
For example, if you did not know the color, there is no way to only change the opacity of the border by simply using rgba()
.
res.json
forces the argument to JSON. res.send
will take an non-json object or non-json array and send another type. For example:
This will return a JSON number.
res.json(100)
This will return a status code and issue a warning to use sendStatus.
res.send(100)
If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json
.
mysql -uroot -psecret mysql < mydatabase.sql
SELECT employee_id,department_id AS department
FROM employees
order by department
SELECT employee_id,department_id AS "department"
FROM employees
order by department
--error on oracle--
so better to use AS without double quotation if you use ORDER BY clause
Screen.lockOrientation()
solves this problem, though support is less than universal at the time (April 2017):
https://www.w3.org/TR/screen-orientation/
https://developer.mozilla.org/en-US/docs/Web/API/Screen.lockOrientation
Numbers have higher precedence than strings so of course the +
operators want to convert your strings into numbers before adding.
You could do:
print 'There are ' + CONVERT(varchar(10),@Number) +
' alias combinations did not match a record'
or use the (rather limited) formatting facilities of RAISERROR
:
RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT
This works as well for me
string path = TextFile + ".txt";
if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("{0}", "Hello World");
w.Flush();
w.Close();
}
PyFilesystem with its sshfs is one option. It uses Paramiko under the hood and provides a nicer paltform independent interface on top.
import fs
sf = fs.open_fs("sftp://[user[:password]@]host[:port]/[directory]")
sf.makedir('my_dir')
or
from fs.sshfs import SSHFS
sf = SSHFS(...
You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.
Configure Win7 as authoritative time server. Configure RasPi time server lookup.
You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.
Example using state:
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
getInitialState() {_x000D_
return {email: ''}_x000D_
},_x000D_
handleChange(e) {_x000D_
this.setState({email: e.target.value})_x000D_
},_x000D_
render() {_x000D_
return <div>_x000D_
<input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
<button type="button" disabled={!this.state.email}>Button</button>_x000D_
</div>_x000D_
}_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
using System;
using System.Data;
using System.Data.SqlClient;
namespace SqlCommend
{
class sqlcreateapp
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
conn.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Table Created Successfully...");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
EntityFunctions
is obsolete. Consider using DbFunctions
instead.
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => DbFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
My solution was to put same value (path to JDK bin folder) in JAVA_HOME
and Path
The HTTP spec and Firebug were very useful for me when I had to do it for my homework.
Good luck with yours. :)
As stated in many other responses, m_ is a prefix that denotes member variables. It is/was commonly used in the C++ world and propagated to other languages too, including Java.
In a modern IDE it is completely redundant as the syntax highlighting makes it evident which variables are local and which ones are members. However, by the time syntax highlighting appeared in the late 90s, the convention had been around for many years and was firmly set (at least in the C++ world).
I do not know which tutorials you are referring to, but I will guess that they are using the convention due to one of two factors:
In XCode 4.0 main workspace, at the top left side & just after the "Stop Button", there is scheme selector, click on it and change your scheme to IPhone Simulator. That's it
followers_df.reset_index()
followers_df.reindex(index=range(0,20))
It happened to me when I deployed my main.jar, without checking the add directory entries box in the export jar menu in Eclipse.
Use CSS's :disabled
selector (for CSS3):
checkbox-style { }
checkbox-style:disabled { }
Or you need to use javascript to alter the style based on when you enable/disable it (Assuming it is being enabled/disabled based on your question).
I was able to override compatibility mode by specifying the meta tag as THE FIRST TAG in the head section, not just the first meta tag but as and only as the VERY FIRST TAG.
Thanks to @stefan.s for putting me on to it in your excellent answer. Prior to reading that I had:
THIS DID NOT WORK
<head>
<link rel="stylesheet" type="text/css" href="/qmuat/plugins/editors/jckeditor/typography/typography.php"/>
<meta http-equiv="x-ua-compatible" content="IE=9" >
moved the link tag out of the way and it worked
THIS WORKS:
<head><meta http-equiv="x-ua-compatible" content="IE=9" >
So an IE8 client set to use compatibility renders the page as IE8 Standard mode - the content='IE=9' means use the highest standard available up to and including IE9.
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.This is answering a slightly different question, but since I got stuck on this myself, I hope it might be useful for someone else.
If you want to use allow_redirects=False
and get directly to the first redirect object, rather than following a chain of them, and you just want to get the redirect location directly out of the 302 response object, then r.url
won't work. Instead, it's the "Location" header:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)
So if I understand it correctly.
A class
method does not need you to allocate instance of that object to use / process it. A class
method is self contained and can operate without any dependence of the state of any object of that class. A class
method is expected to allocate memory for all its own work and deallocate when done, since no instance of that class will be able to free any memory allocated in previous calls to the class method.
A instance
method is just the opposite. You cannot call it unless you allocate a instance of that class. Its like a normal class that has a constructor and can have a destructor (that cleans up all the allocated memory).
In most probability (unless you are writing a reusable library, you should not need a class
variable.
As pointed out by Tanis.7x, the support library version (23) does not match the targetSdkVersion (22)
You can fix this by doing the following:
In the build.grade
file of your app module, change the following line of code
compile 'com.android.support:appcompat-v7:23.0.0'
To
compile 'com.android.support:appcompat-v7:22.+'
This will use the latest version of the appcompat version that is compatible with SdkVersion 22.
While it can be annoying when used as an anti-piracy measure, I can see there might be some instances where it'd be legitimate, so:
function disableCopyPaste(elm) {
// Disable cut/copy/paste key events
elm.onkeydown = interceptKeys
// Disable right click events
elm.oncontextmenu = function() {
return false
}
}
function interceptKeys(evt) {
evt = evt||window.event // IE support
var c = evt.keyCode
var ctrlDown = evt.ctrlKey||evt.metaKey // Mac support
// Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
if (ctrlDown && evt.altKey) return true
// Check for ctrl+c, v and x
else if (ctrlDown && c==67) return false // c
else if (ctrlDown && c==86) return false // v
else if (ctrlDown && c==88) return false // x
// Otherwise allow
return true
}
I've used event.ctrlKey
rather than checking for the key code as on most browsers on Mac OS X Ctrl/Alt "down" and "up" events are never triggered, so the only way to detect is to use event.ctrlKey
in the e.g. c event after the Ctrl key is held down. I've also substituted ctrlKey
with metaKey
for macs.
Limitations of this method:
edit
->copy
menu item in e.g. Firefox can still allow copy/pasting.In case if you are using checkstyle from qulice
mvn plugin (https://github.com/teamed/qulice) you may use the following suppresion:
// @checkstyle <Rulename> (N lines)
... code with violation(s)
or
/**
* ...
* @checkstyle <Rulename> (N lines)
* ...
*/
... code with violation(s)
you can also use this code
public static double roundToDecimals(double d, int c)
{
int temp = (int)(d * Math.pow(10 , c));
return ((double)temp)/Math.pow(10 , c);
}
It gives you control of how many numbers after the point are needed.
d = number to round;
c = number of decimal places
think it will be helpful
Select value from drop down.
<select class="form-control" name="category" id="sel1">
<?php
foreach($data as $key =>$value){
?>
<option value="<?php echo $data[$key]->name; ?>"<?php if($id_name[0]->p_name==$data[$key]->name) echo 'selected="selected"'; ?>><?php echo $data[$key]->name; ?></option>
<?php } ?>
</select>
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
There is a way that's pretty memory inefficient.
single file:
import hashlib
def file_as_bytes(file):
with file:
return file.read()
print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()
list of files:
[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:
[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
If you only want 128 bits worth of digest you can do .digest()[:16]
.
This will give you a list of tuples, each tuple containing the name of its file and its hash.
Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.
Here is a way that is more complex, but memory efficient:
import hashlib
def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
for block in bytesiter:
hasher.update(block)
return hasher.hexdigest() if ashexstr else hasher.digest()
def file_as_blockiter(afile, blocksize=65536):
with afile:
block = afile.read(blocksize)
while len(block) > 0:
yield block
block = afile.read(blocksize)
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
for fname in fnamelst]
And, again, since MD5 is broken and should not really ever be used anymore:
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
for fname in fnamelst]
Again, you can put [:16]
after the call to hash_bytestr_iter(...)
if you only want 128 bits worth of digest.
Here is a recent example of how to implement a table with rounded-corners from http://medialoot.com/preview/css-ui-kit/demo.html. It's based on the special selectors suggested by Joel Potter above. As you can see, it also includes some magic to make IE a little happy. It includes some extra styles to alternate the color of the rows:
table-wrapper {
width: 460px;
background: #E0E0E0;
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#E9E9E9', endColorstr='#D7D7D7');
background: -webkit-gradient(linear, left top, left bottom, from(#E9E9E9), to(#D7D7D7));
background: -moz-linear-gradient(top, #E9E9E9, #D7D7D7);
padding: 8px;
-webkit-box-shadow: inset 0px 2px 2px #B2B3B5, 0px 1px 0 #fff;
-moz-box-shadow: inset 0px 2px 2px #B2B3B5, 0px 1px 0 #fff;
-o-box-shadow: inset 0px 2px 2px #B2B3B5, 0px 1px 0 #fff;
-khtml-box-shadow: inset 0px 2px 2px #B2B3B5, 0px 1px 0 #fff;
box-shadow: inset 0px 2px 2px #B2B3B5, 0px 1px 0 #fff;
-webkit-border-radius: 10px;
/*-moz-border-radius: 10px; firefox doesn't allow rounding of tables yet*/
-o-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
margin-bottom: 20px;
}
.table-wrapper table {
width: 460px;
}
.table-header {
height: 35px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
text-align: center;
line-height: 34px;
text-decoration: none;
font-weight: bold;
}
.table-row td {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
text-align: left;
text-decoration: none;
font-weight: normal;
color: #858585;
padding: 10px;
border-left: 1px solid #ccc;
-khtml-box-shadow: 0px 1px 0px #B2B3B5;
-webkit-box-shadow: 0px 1px 0px #B2B3B5;
-moz-box-shadow: 0px 1px 0px #ddd;
-o-box-shadow: 0px 1px 0px #B2B3B5;
box-shadow: 0px 1px 0px #B2B3B5;
}
tr th {
border-left: 1px solid #ccc;
}
tr th:first-child {
-khtml-border-top-left-radius: 8px;
-webkit-border-top-left-radius: 8px;
-o-border-top-left-radius: 8px;
/*-moz-border-radius-topleft: 8px; firefox doesn't allow rounding of tables yet*/
border-top-left-radius: 8px;
border: none;
}
tr td:first-child {
border: none;
}
tr th:last-child {
-khtml-border-top-right-radius: 8px;
-webkit-border-top-right-radius: 8px;
-o-border-top-right-radius: 8px;
/*-moz-border-radius-topright: 8px; firefox doesn't allow rounding of tables yet*/
border-top-right-radius: 8px;
}
tr {
background: #fff;
}
tr:nth-child(odd) {
background: #F3F3F3;
}
tr:nth-child(even) {
background: #fff;
}
tr:last-child td:first-child {
-khtml-border-bottom-left-radius: 8px;
-webkit-border-bottom-left-radius: 8px;
-o-border-bottom-left-radius: 8px;
/*-moz-border-radius-bottomleft: 8px; firefox doesn't allow rounding of tables yet*/
border-bottom-left-radius: 8px;
}
tr:last-child td:last-child {
-khtml-border-bottom-right-radius: 8px;
-webkit-border-bottom-right-radius: 8px;
-o-border-bottom-right-radius: 8px;
/*-moz-border-radius-bottomright: 8px; firefox doesn't allow rounding of tables yet*/
border-bottom-right-radius: 8px;
}
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
MYSQL 8.0:
Search my.ini
in disk, we will find this folder:
C:\ProgramData\MySQL\MySQL Server 8.0
It'sProgramData
, notProgram file
Data is in sub-folder: \Data
.
Each database
owns a folder, each table
is file, each index
is 1+ files.
This can't be done in just HTML (with form elements into option
elements).
Or you can just use a standard select multiple
field.
<select multiple>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
Use 'a'
, 'a'
means append
. Anything written to a file opened with 'a'
attribute is written at the end of the file.
with open('file.txt', 'a') as file:
file.write('input')
With the Java libraries for dealing with files, you can safely use /
(slash, not backslash) on all platforms. The library code handles translating things into platform-specific paths internally.
You might want to use File.separator
in UI, however, because it's best to show people what will make sense in their OS, rather than what makes sense to Java.
Update: I have not been able, in five minutes of searching, to find the "you can always use a slash" behavior documented. Now, I'm sure I've seen it documented, but in the absense of finding an official reference (because my memory isn't perfect), I'd stick with using File.separator
because you know that will work.
This procedure works even if ADB is not available.
Also it's worth knowing that you may need to include .\
in front of the script name. For example:
.\scriptname.ps1
From the document
This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.
which means it will call the start scripts inside the package.json
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite --baseDir ./app --port 8001\" ",
"lite": "lite-server",
...
}
Provided by angular/angular-cli to start angular2 apps which created by angular-cli. when you install angular-cli, it will create ng.cmd under C:\Users\name\AppData\Roaming\npm
(for windows) and execute "%~dp0\node.exe" "%~dp0\node_modules\angular-cli\bin\ng" %*
So using npm start
you can make your own execution where is ng serve
is only for angular-cli
See Also : What happens when you run ng serve?
When the post-link
function is called, all previous steps have taken place - binding, transclusion, etc.
This is typically a place to further manipulate the rendered DOM.
You can also use guava Table implementation for this.
Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.
//create a table
Table<String, String, String> employeeTable = HashBasedTable.create();
//initialize the table with employee details
employeeTable.put("IBM", "101","Mahesh");
employeeTable.put("IBM", "102","Ramesh");
employeeTable.put("IBM", "103","Suresh");
employeeTable.put("Microsoft", "111","Sohan");
employeeTable.put("Microsoft", "112","Mohan");
employeeTable.put("Microsoft", "113","Rohan");
employeeTable.put("TCS", "121","Ram");
employeeTable.put("TCS", "122","Shyam");
employeeTable.put("TCS", "123","Sunil");
//get Map corresponding to IBM
Map<String,String> ibmEmployees = employeeTable.row("IBM");
Use Application.StartupPath
for the best result imo.
In the most general way :
isset
tests if a variable (or an element of an array, or a property of an object) exists (and is not null)empty
tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str
exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET
/ $_POST
, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty
.
the worked proposition for me is __call__
on class who create list of little numbers:
import itertools
class SmallNumbers:
def __init__(self, how_much):
self.how_much = int(how_much)
self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
start = 10
end = 100
for cmb in range(2, len(str(self.how_much)) + 1):
self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
start *= 10
end *= 10
def __call__(self, number, *args, **kwargs):
return self.generated_list[number]
def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
multi_work_list = eval(str('self.work_list,') * combinations)
nbr = 0
for subset in itertools.product(*multi_work_list):
if is_upper_then <= nbr < is_under_then:
self.generated_list.append(''.join(subset))
if self.how_much == nbr:
break
nbr += 1
and to run it:
if __name__ == '__main__':
sm = SmallNumbers(56)
print(sm.generated_list)
print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
print('The Best', sm(15), sm(55), sm(49), sm(0))
result
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0
Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link
Youtube video about entire process.
Writeup with pictures about installing SQL Server
How to select a local server:
When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:
1) Make sure you have Server Type: Database
2) Make sure you have Authentication: Windows Authentication (no username & password)
3) For the server name field look to the right and select the drop down arrow, click 'browse for more'
4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14
How do I create a local database inside of Microsoft SQL Server 2014?
1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)
2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!
Do not use $('title').text('hi')
, because IE doesn't support it.
It is better to use document.title = 'new title';
On my system, I was just missing the Linux package.
sudo apt install libopenmpi-dev
pip install mpi4py
(example of something that uses it that is a good instant test to see if it succeeded)
Succeded.
This ridiculous error message merely means there's a binding to an array that doesn't exist.
<option
*ngFor="let option of setting.options"
[value]="option"
>{{ option }}
</option>
In the example above the value of setting.options is undefined. To fix, press F12 and open developer window. When the the get request returns the data look for the values to contain data.
If data exists, then make sure the binding name is correct
//was the property name correct?
setting.properNamedOptions
If the data exists, is it an Array?
If the data doesn't exist then fix it on the backend.
I decided to hide the badge on all pages except my contact page (using Wordpress):
/* Hides the reCAPTCHA on every page */
.grecaptcha-badge {
visibility: hidden !important;
}
/* Shows the reCAPTCHA on the Contact page */
/* Obviously change the page number to your own */
.page-id-17 .grecaptcha-badge {
visibility: visible !important;
}
I'm not a web developer so please correct me if there's something wrong.
EDIT: Updated to use visibility instead of display.
You are calling setTimeout()
ten times in a row, so they all expire almost at the same time. What you actually want is this:
window.onload = function start() {
slide(10);
}
function slide(repeats) {
if (repeats > 0) {
document.getElementById('container').style.marginLeft='-600px';
document.getElementById('container').style.marginLeft='-1200px';
document.getElementById('container').style.marginLeft='-1800px';
document.getElementById('container').style.marginLeft='0px';
window.setTimeout(
function(){
slide(repeats - 1)
},
3000
);
}
}
This will call slide(10), which will then set the 3-second timeout to call slide(9), which will set timeout to call slide(8), etc. When slide(0) is called, no more timeouts will be set up.
In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick
property as an alternative. The defaultChecked
, the condition may leave a fixed state for v16 IINM.
class CrossOutCheckbox extends Component {
constructor(init){
super(init);
this.handleChange = this.handleChange.bind(this);
}
handleChange({target}){
if (target.checked){
target.removeAttribute('checked');
target.parentNode.style.textDecoration = "";
} else {
target.setAttribute('checked', true);
target.parentNode.style.textDecoration = "line-through";
}
}
render(){
return (
<span>
<label style={{textDecoration: this.props.complete?"line-through":""}}>
<input type="checkbox"
onClick={this.handleChange}
defaultChecked={this.props.complete}
/>
</label>
{this.props.text}
</span>
)
}
}
I hope this helps someone in the future.
This may be just me being really, really picky, but I like to only define constants once. If you use any of the approaches defined above, your action constant will be defines multiple times.
To avoid this, you can do the following:
public class Url
{
public string LocalUrl { get; }
public Url(string localUrl)
{
LocalUrl = localUrl;
}
public override string ToString()
{
return LocalUrl;
}
}
public abstract class Controller
{
public Url RootAction => new Url(GetUrl());
protected abstract string Root { get; }
public Url BuildAction(string actionName)
{
var localUrl = GetUrl() + "/" + actionName;
return new Url(localUrl);
}
private string GetUrl()
{
if (Root == "")
{
return "";
}
return "/" + Root;
}
public override string ToString()
{
return GetUrl();
}
}
Then create your controllers, say for example the DataController:
public static readonly DataController Data = new DataController();
public class DataController : Controller
{
public const string DogAction = "dog";
public const string CatAction = "cat";
public const string TurtleAction = "turtle";
protected override string Root => "data";
public Url Dog => BuildAction(DogAction);
public Url Cat => BuildAction(CatAction);
public Url Turtle => BuildAction(TurtleAction);
}
Then just use it like:
// GET: Data/Cat
[ActionName(ControllerRoutes.DataController.CatAction)]
public ActionResult Etisys()
{
return View();
}
And from your .cshtml (or any code)
<ul>
<li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
<li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>
This is definitely a lot more work, but I rest easy knowing compile time validation is on my side.
In your User
model, add the following line in the User
class:
public $timestamps = true;
Now, whenever you save or update a user, Laravel will automatically update the created_at
and updated_at
fields.
Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s
. The problem is that the format you have used is not the same as Laravel uses for the created_at
field.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
You are looking for something like the following
ALTER TABLE dbo.doc_exz
ADD CONSTRAINT col_b_def
UNIQUE column_b
Find the IP address of the first eth/wlan entry in ifconfig that's RUNNING:
import itertools
import os
import re
def get_ip():
f = os.popen('ifconfig')
for iface in [' '.join(i) for i in iter(lambda: list(itertools.takewhile(lambda l: not l.isspace(),f)), [])]:
if re.findall('^(eth|wlan)[0-9]',iface) and re.findall('RUNNING',iface):
ip = re.findall('(?<=inet\saddr:)[0-9\.]+',iface)
if ip:
return ip[0]
return False
for car,info in cars.items():
print(car)
for key,value in info.items():
print(key, ":", value)
This error of Cannot find the declaration of element 'beans' but for a whole different reason
It turs out my internet connection was not very reliable, so i decided to check first for this url
http://www.springframework.org/schema/context/spring-context-4.0.xsd
Once I saw that the xsd was open succesfully I clean the Eclipse(IDE) project and the error was gone
If you try this steps and still get the error then check the Spring version so that it matches as mentioned by another answer
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-**[MAYOR.MINOR]**.xsd">
Replace [MAYOR.MINOR] on the last line with whatever major.minor Spring version that you are using
For Spring 4.0 http://www.springframework.org/schema/context/spring-context-4.0.xsd
For Sprint 3.1 http://www.springframework.org/schema/beans spring-beans-3.1.xsd
All the contexts are available here http://www.springframework.org/schema/context/
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
Warning: Adam Matan discourages this use in pip > 10.0. Also, read @sinoroc's comment below
This was inspired by Adam Matan's answer (the accepted one):
import tabulate
try:
from pip import get_installed_distributions
except:
from pip._internal.utils.misc import get_installed_distributions
tabpackages = []
for _, package in sorted([('%s %s' % (i.location, i.key), i) for i in get_installed_distributions()]):
tabpackages.append([package.location, package.key, package.version])
print(tabulate.tabulate(tabpackages))
which then prints out a table in the form of
19:33 pi@rpi-v3 [iot-wifi-2] ~/python$ python installed_packages.py
------------------------------------------- -------------- ------
/home/pi/.local/lib/python2.7/site-packages enum-compat 0.0.2
/home/pi/.local/lib/python2.7/site-packages enum34 1.1.6
/home/pi/.local/lib/python2.7/site-packages pexpect 4.2.1
/home/pi/.local/lib/python2.7/site-packages ptyprocess 0.5.2
/home/pi/.local/lib/python2.7/site-packages pygatt 3.2.0
/home/pi/.local/lib/python2.7/site-packages pyserial 3.4
/usr/local/lib/python2.7/dist-packages bluepy 1.1.1
/usr/local/lib/python2.7/dist-packages click 6.7
/usr/local/lib/python2.7/dist-packages click-datetime 0.2
/usr/local/lib/python2.7/dist-packages construct 2.8.21
/usr/local/lib/python2.7/dist-packages pyaudio 0.2.11
/usr/local/lib/python2.7/dist-packages tabulate 0.8.2
------------------------------------------- -------------- ------
which lets you then easily discern which packages you installed with and without sudo
.
A note aside: I've noticed that when I install a packet once via sudo
and once without, one takes precedence so that the other one isn't being listed (only one location is shown). I believe that only the one in the local directory is then listed. This could be improved.
Use update instead of stop
http://api.jqueryui.com/sortable/
update( event, ui )
Type: sortupdate
This event is triggered when the user stopped sorting and the DOM position has changed.
.
stop( event, ui )
Type: sortstop
This event is triggered when sorting has stopped. event Type: Event
Piece of code:
<script type="text/javascript">
var sortable = new Object();
sortable.s1 = new Array(1, 2, 3, 4, 5);
sortable.s2 = new Array(1, 2, 3, 4, 5);
sortable.s3 = new Array(1, 2, 3, 4, 5);
sortable.s4 = new Array(1, 2, 3, 4, 5);
sortable.s5 = new Array(1, 2, 3, 4, 5);
sortingExample();
function sortingExample()
{
// Init vars
var tDiv = $('<div></div>');
var tSel = '';
// ul
for (var tName in sortable)
{
// Creating ul list
tDiv.append(createUl(sortable[tName], tName));
// Add selector id
tSel += '#' + tName + ',';
}
$('body').append('<div id="divArrayInfo"></div>');
$('body').append(tDiv);
// ul sortable params
$(tSel).sortable({connectWith:tSel,
start: function(event, ui)
{
ui.item.startPos = ui.item.index();
},
update: function(event, ui)
{
var a = ui.item.startPos;
var b = ui.item.index();
var id = this.id;
// If element moved to another Ul then 'update' will be called twice
// 1st from sender list
// 2nd from receiver list
// Skip call from sender. Just check is element removed or not
if($('#' + id + ' li').length < sortable[id].length)
{
return;
}
if(ui.sender === null)
{
sortArray(a, b, this.id, this.id);
}
else
{
sortArray(a, b, $(ui.sender).attr('id'), this.id);
}
printArrayInfo();
}
}).disableSelection();;
// Add styles
$('<style>')
.attr('type', 'text/css')
.html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
.appendTo('head');
printArrayInfo();
}
function printArrayInfo()
{
var tStr = '';
for ( tName in sortable)
{
tStr += tName + ': ';
for(var i=0; i < sortable[tName].length; i++)
{
// console.log(sortable[tName][i]);
tStr += sortable[tName][i] + ', ';
}
tStr += '<br>';
}
$('#divArrayInfo').html(tStr);
}
function createUl(tArray, tId)
{
var tUl = $('<ul>', {id:tId, class:'sortableClass'})
for(var i=0; i < tArray.length; i++)
{
// Create Li element
var tLi = $('<li>' + tArray[i] + '</li>');
tUl.append(tLi);
}
return tUl;
}
function sortArray(a, b, idA, idB)
{
var c;
c = sortable[idA].splice(a, 1);
sortable[idB].splice(b, 0, c);
}
</script>
Modify password for role postgres:
sudo -u postgres psql postgres
alter user postgres with password 'postgres';
Now connect to pgadmin using username postgres and password postgres
Now you can create roles & databases using pgAdmin
In MySQL, It should be like this
INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';
DateTimePicker1.value = Format(Date.Now)
This is very simple.
Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..
Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.
Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.
Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.
You can try running the following command again:
ng serve --open
change parent="android:Theme.Holo.Dark"
to parent="android:Theme.Holo"
The holo dark theme is called Holo