Here is another solution. This function will take a single argument and appropriately quote it using the single-quote character, just as the voted answer above explains:
single_quote() {
local quoted="'"
local i=0
while [ $i -lt ${#1} ]; do
local ch="${1:i:1}"
if [[ "$ch" != "'" ]]; then
quoted="$quoted$ch"
else
local single_quotes="'"
local j=1
while [ $j -lt ${#1} ] && [[ "${1:i+j:1}" == "'" ]]; do
single_quotes="$single_quotes'"
((j++))
done
quoted="$quoted'\"$single_quotes\"'"
((i+=j-1))
fi
((i++))
done
echo "$quoted'"
}
So, you can use it this way:
single_quote "1 2 '3'"
'1 2 '"'"'3'"'"''
x="this text is quoted: 'hello'"
eval "echo $(single_quote "$x")"
this text is quoted: 'hello'
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()
Here is a recursive implementation - as an extension method, mimicing the format of the framework method(s):
public static int IndexOfNth(
this string input, string value, int startIndex, int nth)
{
if (nth < 1)
throw new NotSupportedException("Param 'nth' must be greater than 0!");
if (nth == 1)
return input.IndexOf(value, startIndex);
return input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
}
Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):
[Test]
public void TestIndexOfNthWorksForNth1()
{
const string input = "foo<br />bar<br />baz<br />";
Assert.AreEqual(3, input.IndexOfNth("<br />", 0, 1));
}
[Test]
public void TestIndexOfNthWorksForNth2()
{
const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
Assert.AreEqual(21, input.IndexOfNth("<br />", 0, 2));
}
[Test]
public void TestIndexOfNthWorksForNth3()
{
const string input = "foo<br />whatthedeuce<br />kthxbai<br />";
Assert.AreEqual(34, input.IndexOfNth("<br />", 0, 3));
}
The correct syntax ( as tested in VS 2008 SP1), is this:
public static class ErrorCode
{
public static IDictionary<string, string> ErrorCodeDic;
static ErrorCode()
{
ErrorCodeDic = new Dictionary<string, string>()
{ {"1", "User name or password problem"} };
}
}
Not php.ini file, but a way around it. Go to GoDaddy's
Files > Backup > Restore a MySQL Database Backup
Choose your file and click Upload. No timeouts. Rename the DB if needed, and assign a user in
Databases > MySQL Databases
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
Watch out for case sensitivity. If you have a file
/Content/bootstrap.css
and you redirect in your Bundle.config to
.Include("~/Content/Bootstrap.css")
it will not load the css.
For me the mtime (modification time) is also earlier than the create date in a lot of (most) cases since, as you say, any reorganisation modifies the create time. However, the mtime AFAIUI is an accurate reflection of when the file contents were actually changed so should be an accurate record of video capture date.
After discovering this metadata failure for movie files, I am going to be renaming my videos based on their mtime so I have this stored in a more robust way!
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:
# In general
$ echo "foo" \
> "bar"
foo bar
# Pipes
$ echo foo |
> cat
foo
# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar
Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.
$ x="foo
> bar"
$ echo "$x"
foo
bar
With a backslash, you are again splitting the logical line into multiple logical lines.
$ x="foo\
> bar"
$ echo "$x"
foobar
This question has been asked long ago, anyway i would write an easy answer may it help someone.
The easiest way to attach a clickListener to items of RecyclerView is within the Adapter as below:
public class MyAdapter extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
....
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), YourActivity.Class);
startActivity(intent);
}
});
}
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
Structs are good for atomic representation of data, where the said data can be copied multiple times by the code. Cloning an object is in general more expensive than copying a struct, as it involves allocating the memory, running the constructor and deallocating/garbage collection when done with it.
You can use ax.figure.savefig()
:
import pandas as pd
s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
I wanted a function that would join tables without requiring you to define the columns using an anonymous type selector, but had a hard time finding any. I ended up having to make my own. Hopefully this will help anyone in the future who searches for this:
private DataTable JoinDataTables(DataTable t1, DataTable t2, params Func<DataRow, DataRow, bool>[] joinOn)
{
DataTable result = new DataTable();
foreach (DataColumn col in t1.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataColumn col in t2.Columns)
{
if (result.Columns[col.ColumnName] == null)
result.Columns.Add(col.ColumnName, col.DataType);
}
foreach (DataRow row1 in t1.Rows)
{
var joinRows = t2.AsEnumerable().Where(row2 =>
{
foreach (var parameter in joinOn)
{
if (!parameter(row1, row2)) return false;
}
return true;
});
foreach (DataRow fromRow in joinRows)
{
DataRow insertRow = result.NewRow();
foreach (DataColumn col1 in t1.Columns)
{
insertRow[col1.ColumnName] = row1[col1.ColumnName];
}
foreach (DataColumn col2 in t2.Columns)
{
insertRow[col2.ColumnName] = fromRow[col2.ColumnName];
}
result.Rows.Add(insertRow);
}
}
return result;
}
An example of how you might use this:
var test = JoinDataTables(transactionInfo, transactionItems,
(row1, row2) =>
row1.Field<int>("TransactionID") == row2.Field<int>("TransactionID"));
One caveat: This is certainly not optimized, so be mindful when getting to row counts above 20k. If you know that one table will be larger than the other, try to put the smaller one first and the larger one second.
The problem seems to be that you expect plt.show()
to show the window and then to return. It does not do that. The program will stop at that point and only resume once you close the window. You should be able to test that: If you close the window and then another window should pop up.
To resolve that problem just call plt.show()
once after your loop. Then you get the complete plot. (But not a 'real-time plotting')
You can try setting the keyword-argument block
like this: plt.show(block=False)
once at the beginning and then use .draw()
to update.
Haven't seen any fully-native solutions, so here's one:
return str == null || str.chars().allMatch(Character::isWhitespace);
Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):
return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
Or, to be really optimal (but hecka ugly):
int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
One thing I like to do:
Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
The Process static class has a method GetProcessesByName() which you can use to search through running processes. Just search for any other process with the same executable name.
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
MY example . DoWork is below:
DoLengthyWork();
//this is never executed
if(bgWorker.CancellationPending)
{
MessageBox.Show("Up to here? ...");
e.Cancel = true;
}
inside DoLenghtyWork :
public void DoLenghtyWork()
{
OtherStuff();
for(int i=0 ; i<10000000; i++)
{ int j = i/3; }
}
inside OtherStuff() :
public void OtherStuff()
{
for(int i=0 ; i<10000000; i++)
{ int j = i/3; }
}
What you want to do is modify both DoLenghtyWork and OtherStuff() so that they become:
public void DoLenghtyWork()
{
if(!bgWorker.CancellationPending)
{
OtherStuff();
for(int i=0 ; i<10000000; i++)
{
int j = i/3;
}
}
}
public void OtherStuff()
{
if(!bgWorker.CancellationPending)
{
for(int i=0 ; i<10000000; i++)
{
int j = i/3;
}
}
}
The iFrame attribute does not support percent in HTML5. It only supports pixels. http://www.w3schools.com/tags/att_iframe_height.asp
As martijn-courteaux said, create a custom component it's the better option. In C# exists a component called PictureBox and I tried to create this component for Java, here is the code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
public class JPictureBox extends JComponent {
private Icon icon = null;
private final Dimension dimension = new Dimension(100, 100);
private Image image = null;
private ImageIcon ii = null;
private SizeMode sizeMode = SizeMode.STRETCH;
private int newHeight, newWidth, originalHeight, originalWidth;
public JPictureBox() {
JPictureBox.this.setPreferredSize(dimension);
JPictureBox.this.setOpaque(false);
JPictureBox.this.setSizeMode(SizeMode.STRETCH);
}
@Override
public void paintComponent(Graphics g) {
if (ii != null) {
switch (getSizeMode()) {
case NORMAL:
g.drawImage(image, 0, 0, ii.getIconWidth(), ii.getIconHeight(), null);
break;
case ZOOM:
aspectRatio();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
break;
case STRETCH:
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
break;
case CENTER:
g.drawImage(image, (int) (this.getWidth() / 2) - (int) (ii.getIconWidth() / 2), (int) (this.getHeight() / 2) - (int) (ii.getIconHeight() / 2), ii.getIconWidth(), ii.getIconHeight(), null);
break;
default:
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
}
public Icon getIcon() {
return icon;
}
public void setIcon(Icon icon) {
this.icon = icon;
ii = (ImageIcon) icon;
image = ii.getImage();
originalHeight = ii.getIconHeight();
originalWidth = ii.getIconWidth();
}
public SizeMode getSizeMode() {
return sizeMode;
}
public void setSizeMode(SizeMode sizeMode) {
this.sizeMode = sizeMode;
}
public enum SizeMode {
NORMAL,
STRETCH,
CENTER,
ZOOM
}
private void aspectRatio() {
if (ii != null) {
newHeight = this.getHeight();
newWidth = (originalWidth * newHeight) / originalHeight;
}
}
}
If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image. If you want to change the sizeMode property then choose the JPictureBox, after that go to Properties and find "sizeMode" property, you can choose some values:
If you want to learn more about this topic, you can check this video.
Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
I had this issue today, I find the Facebook documentation and SDK disrespectful and arogant towards other developers to say the least.
Besides having the "app domains" in two different locations without much information (3 if you add a "web" platform), you also need to go to app products / facebook login / settings and add your redirect URL under Valid OAuth Redirect URIs
The error says NOTHING about the oauth settings.
I don't know if it will help anyone, but based on Charx (thanks!) answer I have created simple cache service. Feel free to use, remix and share:
angular.service('cache', function() {
var _cache, _store, _get, _set, _clear;
_cache = {};
_store = function(data) {
angular.merge(_cache, data);
};
_set = function(data) {
_cache = angular.extend({}, data);
};
_get = function(key) {
if(key == null) {
return _cache;
} else {
return _cache[key];
}
};
_clear = function() {
_cache = {};
};
return {
get: _get,
set: _set,
store: _store,
clear: _clear
};
});
Yes, you can include custom fonts. Refer to the documentation on UIFont, specifically, the fontWithName:size:
method.
1) Make sure you include the font in your resources folder.
2) The "name" of the font is not necessarily the filename.
3) Make sure you have the legal right to use that font. By including it in your app, you're also distributing it, and you need to have the right to do that.
2017-05 update:
I just found that if you add the following line into your vimrc file,
set clipboard=unnamed
then Vim is using the system clipboard.
I just found the yank way won't work on the way where I copy contents between different Vim instance windows. (At least, it doesn't work based on my Vim knowledge. I don't know if there is another way to enable it to work).
The yank way only works on the way where multiple files are opened in the same window according to my test.
If you want to do that, you'd better use OS cut-copy-past way such as Ctrl + x, Ctrl + c (under Windows).
It seems that the good-old ENVIRON
awk built-in hash is not mentioned at all. An example of its usage:
$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt
Assuming your have a value like the following
var obj = {"0":"1","1":"2","2":"3","3":"4"};
Then you can turn this into a javascript array using the following
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array
This works for converting json into multi-diminsional javascript arrays as well.
None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.
I think it's quite dangerous to rely on the order of the values in a enum and to assume that the first is always the default. This would be good practice if you are concerned about protecting the default value.
enum E
{
Foo = 0, Bar, Baz, Quux
}
Otherwise, all it takes is a careless refactor of the order and you've got a completely different default.
I ran into this issue over the past couple days. Like Omri Aharon said in their answer above, it is important to add definitions for your prop types similar to:
SomeClass.propTypes = {
someProp: PropTypes.number,
onTap: PropTypes.func,
};
Don't forget to add the prop definitions outside of your class. I would place it right below/above my class. If you are not sure what your variable type or suffix is for your PropType (ex: PropTypes.number), refer to this npm reference. To Use PropTypes, you must import the package:
import PropTypes from 'prop-types';
If you get the linting error:someProp is not required, but has no corresponding defaultProps declaration
all you have to do is either add .isRequired
to the end of your prop definition like so:
SomeClass.propTypes = {
someProp: PropTypes.number.isRequired,
onTap: PropTypes.func.isRequired,
};
OR add default prop values like so:
SomeClass.defaultProps = {
someProp: 1
};
If you are anything like me, unexperienced or unfamiliar with reactjs, you may also get this error: Must use destructuring props assignment
. To fix this error, define your props before they are used. For example:
const { someProp } = this.props;
If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.
However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.
Look at the widgets documentation. Basically it would look like:
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
More writing, yes, but the separation allows for better abstraction of more complicated cases.
You can also declare a widgets
attribute containing a <field name> => <widget instance>
mapping directly on the Meta
of your ModelForm
sub-class.
ALTER TABLE Protocols
ADD ProtocolTypeID int NOT NULL DEFAULT(1)
GO
The inclusion of the DEFAULT fills the column in existing rows with the default value, so the NOT NULL constraint is not violated.
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
I think this should work:
#open file for reading
fn = input("Enter file to open: ")
try:
fh = open(fn,'r')
except:
# if file does not exist, create it
fh = open(fn,'w')
Also, you incorrectly wrote fh = open ( fh, "w")
when the file you wanted open was fn
d.keys()[0] to get the individual key.
Update:- @AlejoBernardin , am not sure why you said it didn't work. here I checked and it worked. import collections
prices = collections.OrderedDict((
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
))
prices.keys()[0]
'banana'
Your question is a a bit vague. This is a shell command that does what I think you want to do:
echo >> name_of_file
There's much simpler solution today — pem. This tool makes life much easier.
For example, to generate or renew your push notification certificate just enter:
fastlane pem
and it's done in under a minute. In case you need a sandbox certificate, enter:
fastlane pem --development
And that's pretty it.
If you want to add magic comments on all the source files of a project easily, you can use the magic_encoding
gem
sudo gem install magic_encoding
then just call magic_encoding
in the terminal from the root of your app.
For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:
Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.
just parse as an array:
Review[] reviews = new Gson().fromJson(jsonString, Review[].class);
then if you need you can also create a list in this way:
List<Review> asList = Arrays.asList(reviews);
P.S. your json string should be look like this:
[
{
"reviewerID": "A2SUAM1J3GNN3B1",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano.",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
},
{
"reviewerID": "A2SUAM1J3GNN3B2",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano.",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
},
[...]
]
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
When using with a reactive bootstrap table, i did not find that the
table.classname td {
syntax worked as there was no <table>
tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead>
and <tbody>
for grouping at most.
Simply specifying like this worked great though
td.classname {
max-width: 500px;
text-overflow: initial;
white-space: wrap;
word-wrap: break-word;
}
as it directly overrides the <td>
and can be used only on the elements you want to change. Maybe in your case use
thead.medium td {
font-size: 40px;
}
tbody.small td {
font-size:25px;
}
for consistent font sizing with a bigger header.
If you're looking for a solution to hide a scrollbar for mobile devices, follow Peter's answer!
Here's a jsfiddle, which uses the solution below to hide a horizontal scrollbar.
.scroll-wrapper{
overflow-x: scroll;
}
.scroll-wrapper::-webkit-scrollbar {
display: none;
}
It was tested on a Samsung tablet with Android 4.0.4 (Ice Cream Sandwich, both in the native browser and Chrome) and on an iPad with iOS 6 (both in Safari and Chrome).
(Edit 7 years later: Google Gears is gone. Ignore this answer.)
The Google Gears team ran into the lack-of-binary-data-types problem and has attempted to address it:
JavaScript has a built-in data type for text strings, but nothing for binary data. The Blob object attempts to address this limitation.
Maybe you can weave that in somehow.
For Java 8 and above, it's easy:
when(mock.process(Matchers.anyList()));
For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz)
:
when(mock.process(Matchers.anyListOf(Bar.class)));
Most likely persistent connections that are kept alive by the connection manager become stale. That is, the target server shuts down the connection on its end without HttpClient being able to react to that event, while the connection is being idle, thus rendering the connection half-closed or 'stale'. Usually this is not a problem. HttpClient employs several techniques to verify connection validity upon its lease from the pool. Even if the stale connection check is disabled and a stale connection is used to transmit a request message the request execution usually fails in the write operation with SocketException and gets automatically retried. However under some circumstances the write operation can terminate without an exception and the subsequent read operation returns -1 (end of stream). In this case HttpClient has no other choice but to assume the request succeeded but the server failed to respond most likely due to an unexpected error on the server side.
The simplest way to remedy the situation is to evict expired connections and connections that have been idle longer than, say, 1 minute from the pool after a period of inactivity. For details please see this section of the HttpClient tutorial.
Identify the library which is causing syntax error in Studio.
For Example if AppCompatActivity
is showing error then you will perform below operation on AppCompat Dependency.
That's It, error gone!
If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.
if [ -h $file ]
then
base=$(dirname $(readlink $file))
else
base=$(dirname $file)
fi
Quick solution I found was inside the pgAdmin program for windows. Under Tools menu there is a "Query Tool". Inside the Query Tool there is a Graphical Query Builder that can quickly show the database tables details. Good for a basic view
It should be noted that math.floor()
always rounds down, and therefore does not yield a sensible result for negative floating point values.
For example, -10.4 represented as an integer would usually be either truncated or rounded to -10. Yet the result of math.floor() is not the same:
math.floor(-10.4) => -11
For truncation with type conversion, the following helper function will work:
function tointeger( x )
num = tonumber( x )
return num < 0 and math.ceil( num ) or math.floor( num )
end
Reference: http://lua.2524044.n2.nabble.com/5-3-Converting-a-floating-point-number-to-integer-td7664081.html
Karan has posted the answer but that didn't work for me. So, I am posting what worked for me. If that didn't work then user can try this
<configuration>
<system.webServer>
<defaultDocument enabled="true">
<files>
<add value="myFile.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
If using XML configuration you can use
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security">
<security:http>
<security:headers>
<security:frame-options disabled="true"></security:frame-options>
</security:headers>
</security:http>
</beans>
/*Step 1*/
myFunction(){ this.props.history.push("/home"); }
/**/
<button onClick={()=>this.myFunction()} className={'btn btn-primary'}>Go
Home</button>
I was having a lot of problems with justify-content, and I figured out the problem was "margin: 0 auto"
The auto part overrides the justify-content so its always displayed according to the margin and not to the justify-content.
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.
{
"name": "mobileapp",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@angular-devkit/architect": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
"integrity": "sha512-2zi6S9tPlk52vyqNFg==",
"dev": true,
"requires": {
"@angular-devkit/core": "7.1.4",
"rxjs": "6.3.3"
}
},
}
I have three approaches,
Here you can use both <input>
or <textarea>
as per your requirements.
1. Use Input in <td>
.
Using <input>
element in all <td>
s,
<tr><td><input type="text"></td>....</tr>
Also, you might want to resize the input to the size of its td
. ex.,
input { width:100%; height:100%; }
You can additionally change the colour of the border of the input box when it is not being edited.
2. Use contenteditable='true'
attribute. (HTML5)
However, if you want to use contenteditable='true'
, you might also want to save the appropriate values to the database. You can achieve this with ajax.
You can attach keyhandlers keyup
, keydown
, keypress
etc to the <td>
. Also, it is good to use some delay() with those events when user continuously types, the ajax event won't fire with every key user press. for example,
$('table td').keyup(function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(saveData, 500); // delay after user types
$(this).data('timer', wait);
});
function saveData() {
// ... ajax ...
}
3. Append <input>
to <td>
when it is clicked.
Add the input element in td
when the <td>
is clicked, replace its value according to the td
's value. When the input is blurred, change the `td's value with the input's value. All this with javascript.
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
Using:
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
//do your ReconTool stuff
}
}
will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.
Using maven just use mvn spring-boot:run
while in gradle it would be gradle bootRun
An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner
. That would look like:
@Component
public class ReconTool implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
//implement your business logic here
}
}
Check out this guide from Spring's official guide repository.
The full Spring Boot documentation can be found here
Setting Tomcat to listen to port 80 is WRONG , for development the 8080 is a good port to use. For production use, just set up an apache that shall forward your requests to your tomcat. Here is a how to.
Well we can not exactly do what your trying. But something likely to below can be done.
function multiReturnValues(){
return {x:10,y:20};
}
Then when calling the method
const {x,y} = multiReturnValues();
console.log(x) ---> 10
console.log(y) ---> 20
I like to use Action in place of MethodInvoker, it is shorter and looks cleaner.
Invoke((Action)(() => {
DoSomething();
}));
// OR
Invoke((Action)delegate {
DoSomething();
});
Eg.
// Thread-safe update on a form control
public void DisplayResult(string text){
if (txtResult.InvokeRequired){
txtResult.Invoke((Action)delegate {
DisplayResult(text);
});
return;
}
txtResult.Text += text + "\r\n";
}
The purpose of a view is to use the query over and over again. To that end, SQL Server, Oracle, etc. will typically provide a "cached" or "compiled" version of your view, thus improving its performance. In general, this should perform better than a "simple" query, though if the query is truly very simple, the benefits may be negligible.
Now, if you're doing a complex query, create the view.
I think an elegant solution is to use the where
method (also see the API docs
):
In [37]: values = df.Prices * df.Amount
In [38]: df['Values'] = values.where(df.Action == 'Sell', other=-values)
In [39]: df
Out[39]:
Prices Amount Action Values
0 3 57 Sell 171
1 89 42 Sell 3738
2 45 70 Buy -3150
3 6 43 Sell 258
4 60 47 Sell 2820
5 19 16 Buy -304
6 56 89 Sell 4984
7 3 28 Buy -84
8 56 69 Sell 3864
9 90 49 Buy -4410
Further more this should be the fastest solution.
I just want to add what worked for me, I added height and width to both divs and used bootstrap to make it responsive
<div class="col-lg-1 mapContainer">
<div id="map"></div>
</div>
#map{
height: 100%;
width:100%;
}
.mapContainer{
height:200px;
width:100%
}
in order for col-lg-1
to work add bootstrap reference located
Here
if you have parent element than your parent element must have overflow: hidden; property because if your children content is getting oveflowed from parent border than your border will be visible .otherwise your borderradius is working but it is hide by your children content.
.outer {
width: 200px;
height: 120px;
border: 1px solid black;
margin-left: 50px;
overflow: hidden;
border-radius: 30px;
}
.inner1 {
width: 100%;
height: 100%;
background-image: linear-gradient(#FF9933,white, green);
border: 1px solid black;
}
_x000D_
<div class="outer">
<div class="inner1">
</div>
</div>
_x000D_
Another solution is the one described here at the end of this post by "enlian": http://springinpractice.com/2013/10/07/handling-json-error-object-responses-with-springs-resttemplate
try{
restTemplate.exchange(...)
} catch(HttpStatusCodeException e){
String errorpayload = e.getResponseBodyAsString();
//do whatever you want
} catch(RestClientException e){
//no response payload, tell the user sth else
}
When spring boot application starts, the embedded server such as Tomcat starts with a default port. The embedded tomcat starts with 8080 port as default. There are many ways to change default server port.
Using Property File (.properties/.yml)
To change server port using property file, we need to configure server.port property.
a. Using application.properties in classpath such as src\main\resources\application.properties
server.port = 8585
The server will start with 8585 port. To get random server port, assign 0 to the property.
server.port = 0
Now spring boot will start the server on a port that is not being used currently by any server in the system.
b. Using application.yml in classpath such as src\main\resources\application.yml.
server:
port: 8585
Server will start with 8585 port.
For random port, assign 0.
server:
port: 0
Using java Command with --server.port or -Dserver.port
Suppose we have an executable JAR named as my-app.jar, then while starting spring boot application using java command we can use the argument as follows.
Using --server.port
java -jar my-app.jar --server.port=8585
Using -Dserver.port
java -jar -Dserver.port=8585 my-app.jar
Server will start with 8585 port.
Using java Command with --port or -Dport in Short
To make --server.port and -Dserver.port in short, we can remove server keyword and make it any short keyword such as --port and -Dport. We can use any short keyword. Here we are using port as short keyword. To achieve it we need to configure placeholder in property file as follows.
Using application.properties
server.port=${port:8282}
Using application.yml
server:
port: ${port:8282}
If we do not pass the port as the argument then by default server will start with 8282. If we want a different port, then we need to pass desired port in argument as follows. Suppose we have an executable JAR named as my-app.jar.
Using --port
java -jar my-app.jar --port=8585
Using -Dport
java -jar -Dport=8585 my-app.jar
Server will start with 8585 port.
Using SERVER_PORT with SpringApplication Programmatically
SpringApplication has a method as setDefaultProperties() that is used to change spring boot default properties. Suppose we want to change default port then we need to create a Map and put a port with SERVER_PORT key. Find the example.
MyApplication.java
package com.humoyun;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
Map<String, Object> map = new HashMap<>();
map.put("SERVER_PORT", "8585");
application.setDefaultProperties(map);
application.run(args);
}
}
Spring boot will start the server with 8585 port.
With this command I had poor image quality
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4
With this, almost without delay, I got good image quality.
ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi
you can use for example:
>>> test_list = ['title', 'email', 'password2', 'password1', 'first_name',
'last_name', 'next', 'newsletter']
>>> reorder_func = lambda x: x.insert(x.index('password2'), x.pop(x.index('password2')+1))
>>> reorder_func(test_list)
>>> test_list
... ['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']
A Collection
is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet
which has a last()
method. Or you can use a List
and call mylist.get(mylist.size()-1);
If you really need the last element you should use a List
or a SortedSet
. But if all you have is a Collection
and you really, really, really need the last element, you could use toArray()
or you could use an Iterator
and iterate to the end of the list.
For example:
public Object getLastElement(final Collection c) {
final Iterator itr = c.iterator();
Object lastElement = itr.next();
while(itr.hasNext()) {
lastElement = itr.next();
}
return lastElement;
}
In my case it is a different issue. The database turned into single user mode and a second connection to the database was showing this exception. To resolve this issue follow below steps.
exec sp_who2
and find all the connections to database ‘my_db’. Kill all the connections by doing KILL { session id }
where session id is the SPID listed by sp_who2.USE MASTER;
EXEC sp_who2
USE MASTER;
ALTER DATABASE [my_db] SET MULTI_USER
GO
Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.
As in "CocoaPods - pod setup http request failed", a 503 error on accessing (cloning) a public repository is likely to be the result of a GitHub glitch (availability issue)
Retrying later usually works.
My Windows home directory is on the network, and I suspected that Git Bash commands were looking there first. Sure enough, when I looked at $PATH
, it listed /h/bin
first, where /h
is a share on a Windows file server, even though /h/bin
doesn't exist.
I edited /etc/profile
and commented out the export command that puts it first in $PATH
:
#export PATH="$HOME/bin:$PATH"
This made my commands run much faster, probably because Git Bash is no longer looking across the network for the executables. My /etc/profile
was c:\Program Files (x86)\Git\etc\profile
.
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
Easy fix for this might be editing config/mail.php and turning off TLS
'encryption' => env('MAIL_ENCRYPTION', ''), //'tls'),
Basically by doing this
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
You should loose security also, but in first option there is no need to dive into Vendor's code.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
The ISO C99 standard specifies that these macros must only be defined if explicitly requested.
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
... now PRIu64 will work
NOTE: Pure Swift 3 (Xcode 8) example:
Please try out the following sample code. It is the simple example of dataTask
function of URLSession
.
func simpleDataRequest() {
//Get the url from url string
let url:URL = URL(string: "YOUR URL STRING")!
//Get the session instance
let session = URLSession.shared
//Create Mutable url request
var request = URLRequest(url: url as URL)
//Set the http method type
request.httpMethod = "POST"
//Set the cache policy
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
//Post parameter
let paramString = "key=value"
//Set the post param as the request body
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let _:Data = data as Data?, let _:URLResponse = response , error == nil else {
//Oops! Error occured.
print("error")
return
}
//Get the raw response string
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//Print the response
print(dataString!)
}
//resume the task
task.resume()
}
You can also use IHtmlHelper.GetEnumSelectList.
// Summary:
// Returns a select list for the given TEnum.
//
// Type parameters:
// TEnum:
// Type to generate a select list for.
//
// Returns:
// An System.Collections.Generic.IEnumerable`1 containing the select list for the
// given TEnum.
//
// Exceptions:
// T:System.ArgumentException:
// Thrown if TEnum is not an System.Enum or if it has a System.FlagsAttribute.
IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct;
Like timber said - "Java 8 Collection has a nice method called removeIf that makes things easier and safer"
Here is the code that solve your problem:
set.removeIf((Integer element) -> {
return (element % 2 == 0);
});
Now your set contains only odd values.
You need to try one of the following:
They offer many more features and will be easier to get what you are looking for.
nan = float('nan')
And now you have the constant, nan
.
You can similarly create NaN values for decimal.Decimal.:
dnan = Decimal('nan')
Answer from 2020 year :
dependencies {
implementation "androidx.core:core-ktx:1.2.0"
}
and cal it simply in your code
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
setMargins(5)
}
"".join([i for i in my_list])
This should work just like you asked!
$("#save").click(function () {
debugger
var xx = [];
var dd = { "firstname": "", "lastname": "", "address": "" };
var otable1 = $("#table1").dataTable().fnGetData();
for (var i = 0; i < otable1.length; i++) {
dd.firstname = otable1[i][0];
dd.lastname = otable1[i][1];
dd.address = otable1[i][2];
xx.push(dd);
var dd = { "firstname": "", "lastname": "", "address": "" };
}
JSON.stringify(alert(xx));
$.ajax({
url: '../Home/save',
type: 'POST',
data: JSON.stringify({ u: xx }),
contentType: 'application/json;',
dataType: 'json',
success: function (event) {
alert(event);
$("#table2").dataTable().fnDraw();
location.reload();
}
});
});
You could also use the coalesce function. I tested this in PostgreSQL, but it should also work for MySQL or MS SQL server.
INNER JOIN x ON coalesce(x.qid, -1) = coalesce(y.qid, -1)
This will replace NULL
with -1
before evaluating it. Hence there must be no -1
in qid
.
As already stated there is nothing you can do except restore from a backup. At least now you will have learned to always wrap statements in a transaction to see what happens before you decide to commit. Also, if you don't have a backup of your database this will also teach you to make regular backups of your database.
While we haven't been much help for your imediate problem...hopefully these answers will ensure you don't run into this problem again in the future.
Just saying: numpy
has this too. So no need to import math
if you already did import numpy as np
:
>>> np.exp(1)
2.718281828459045
Probably part of Open Graph Protocol for Facebook.
Edit: guess not only Facebook - that's only one example of using it.
You can also apply multiple transforms using an extra layer of markup e.g.:
<h3 class="rotated-heading">
<span class="scaled-up">Hey!</span>
</h3>
<style type="text/css">
.rotated-heading
{
transform: rotate(10deg);
}
.scaled-up
{
transform: scale(1.5);
}
</style>
This can be really useful when animating elements with transforms using Javascript.
An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)
'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).
An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!
'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
From Here
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
This will work, or the previous examples will, too. @"..." means treat everything between the quote marks literally, so you can do
@"Hello
world"
To include a literal newline. I'm more old school and prefer to escape "\" with "\\"
I use this function:
gcaa() { git add --all && git commit -m "$*" }
In my zsh config file, so i can just do:
> gcaa This is the commit message
To automatically stage and commit all files.
You may also use the stringr
package
library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))
You may not use '^'
(starts with) in this case, to obtain the results you need
Set the socket non-blocking, and use select()
(which takes a timeout parameter). If a non-blocking socket is trying to connect, then select()
will indicate that the socket is writeable when the connect()
finishes (either successfully or unsuccessfully). You then use getsockopt()
to determine the outcome of the connect()
:
int main(int argc, char **argv) {
u_short port; /* user specified port number */
char *addr; /* will be a pointer to the address */
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
if (argc != 3) {
fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]);
return EXIT_FAILURE;
}
port = atoi(argv[1]);
addr = argv[2];
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 10; /* 10 second timeout */
tv.tv_usec = 0;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
printf("%s:%d is open\n", addr, port);
}
}
close(sock);
return 0;
}
BigDecimal
, not double
The Answer by adatapost is right about using String::split
but wrong about using double
to represent your longitude-latitude values. The float
/Float
and double
/Double
types use floating-point technology which trades away accuracy for speed of execution.
Instead use BigDecimal
to correctly represent your lat-long values.
Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.
Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split
for the writing. And the app uses BigDecimal
objects to represent your lat-long values.
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class LatLong
{
//----------| Write |-----------------------------
public void write ( final Path path )
{
List < String > inputs =
List.of(
"28.515046280572285,77.38258838653564" ,
"28.51430151808072,77.38336086273193" ,
"28.513566177802456,77.38413333892822" ,
"28.512830832397192,77.38490581512451" ,
"28.51208605426073,77.3856782913208" ,
"28.511341270865113,77.38645076751709" );
// Use try-with-resources syntax to auto-close the `CSVPrinter`.
try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
{
for ( String input : inputs )
{
String[] fields = input.split( "," );
printer.printRecord( fields[ 0 ] , fields[ 1 ] );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Read |-----------------------------
public void read ( Path path )
{
// TODO: Add a check for valid file existing.
try
{
// Read CSV file.
BufferedReader reader = Files.newBufferedReader( path );
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
for ( CSVRecord record : records )
{
BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
System.out.println( "lat: " + latitude + " | long: " + longitude );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Main |-----------------------------
public static void main ( String[] args )
{
LatLong app = new LatLong();
// Write
Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.write( pathOutput );
System.out.println( "Writing file: " + pathOutput );
// Read
Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.read( pathInput );
System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
}
}
Does the user that you are using to connect to the database (user A
in this example) have SELECT
access on the objects in the PCT
schema? Assuming that A
does not have this access, you would get the "table or view does not exist" error.
Most likely, you need your DBA to grant user A
access to whatever tables in the PCT
schema that you need. Something like
GRANT SELECT ON pct.pi_int
TO a;
Once that is done, you should be able to refer to the objects in the PCT
schema using the syntax pct.pi_int
as you demonstrated initially in your question. The bracket syntax approach will not work.
How about just chaining the greps?
grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
This does not work any more - as an exercise, see if you can replace it with the Github API:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
alert(JSON.stringify(data));
You can also use the jQuery.getJSON method. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
Well, if you are still having the problem, you can download the installer from http://code.google.com/p/soemin/downloads/detail?name=MySQL-python-1.2.3.win32-py2.7.exe
foo="Hello"
foo="${foo} World"
echo "${foo}"
> Hello World
In general to concatenate two variables you can just write them one after another:
a='Hello'
b='World'
c="${a} ${b}"
echo "${c}"
> Hello World
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
When you change your passwords in the security tab, there are two sections, one above and one below. I think the common mistake here is that others try to log-in with the account they have set "below" the one used for htaccess, whereas they should log in to the password they set on the above section. That's how I fixed mine.
Working with thicker strokes gets a bit messy, if you have the pleasure of sass try this mixin, not perfect and depending on stroke weight it generates a fair amount of css.
@mixin stroke($width, $colour: #000000) {
$shadow: 0 0 0 $colour; // doesn't do anything but I couldn't work out how to create a blank string and maintain commas
@for $i from 0 through $width {
$shadow: $shadow,
-$i + px -$width + px 0 $colour,
$i + px -$width + px 0 $colour,
-$i + px $width + px 0 $colour,
$i + px $width + px 0 $colour,
-$width + px -$i + px 0 $colour,
$width + px -$i + px 0 $colour,
-$width + px $i + px 0 $colour,
$width + px $i + px 0 $colour,
}
text-shadow: $shadow;
}
This worked for me:
:% s/\r\n/\r
$('select').val() // Get's the value
$('select option:selected').val() ; // Get's the value
$('select').find('option:selected').val() ; // Get's the value
$('select option:selected').text() // Gets you the text of the selected option
There are 2 different places you can set it:
php.ini
post_max_size=20M
upload_max_filesize=20M
.htaccess / httpd.conf / virtualhost include
php_value post_max_size 20M
php_value upload_max_filesize 20M
Which one to use depends on what you have access to.
.htaccess will not require a server restart, but php.ini and the other apache conf files will.
I had a similar dilemma and didn't want to use 're' module.
def my_split(s, seps):
res = [s]
for sep in seps:
s, res = res, []
for seq in s:
res += seq.split(sep)
return res
print my_split('1111 2222 3333;4444,5555;6666', [' ', ';', ','])
['1111', '', '2222', '3333', '4444', '5555', '6666']
First thing, at the time the question was asked, uintptr_t
was not in C++. It's in C99, in <stdint.h>
, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>
, where again it is optional, and which refers to C99 for the definition.
In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".
Take this to mean what it says. It doesn't say anything about size.
uintptr_t
might be the same size as a void*
. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void*
is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t
which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.
As @kgr mentioned, MySQL 8.0.11 made some changes to the authentication method.
I've opened a phpMyAdmin bug report about this: https://github.com/phpmyadmin/phpmyadmin/issues/14220.
MySQL 8.0.4-rc was working fine for me, and I kind of think it's ridiculous for MySQL to make such a change in a patch level release.
const a = [1, 2, 3]; // -> [2, 3]
// Mutable solutions: update array 'a', 'c' will contain the removed item
const c = a.shift(); // prefered mutable way
const [c] = a.splice(0, 1);
// Immutable solutions: create new array 'b' and leave array 'a' untouched
const b = a.slice(1); // prefered immutable way
const b = a.filter((_, i) => i > 0);
const [c, ...b] = a; // c: the removed item
I've found this page on their github repo, I'll just paste the content here.
There are two main approaches for serializing and restoring a model.
The first (recommended) saves and loads only the model parameters:
torch.save(the_model.state_dict(), PATH)
Then later:
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
The second saves and loads the entire model:
torch.save(the_model, PATH)
Then later:
the_model = torch.load(PATH)
However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.
Along the same lines as some of the suggestions you would need to do at least the following:
An example CSS could be as simple as this:
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.
Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Print Portion Example</title>
<style type="text/css">
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<h1>Print Section Example</h1>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>
<div id="div4">Div 4</div>
<div id="div5">Div 5</div>
<div id="div6">Div 6</div>
<p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
</body>
</html>
Well, first of all that code doesn't compile.
After removing the extra semicolon after i++, it compiles and runs fine for me.
Just complementing @PeterBechP 's answer.
Don't forget to scape the special chars. https://stackoverflow.com/a/6969486
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var name = 'Peter+with+special+chars';
model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
//Do your action here..
});
You can check with null or Number.
First, add a reference to Microsoft.VisualBasic
in your application.
Then, use the following code:
bool b = Microsoft.VisualBasic.Information.IsNumeric("null");
bool c = Microsoft.VisualBasic.Information.IsNumeric("abc");
In the above, b
and c
should both be false
.
For the block element not occupy the whole line, set it's width to something small and the white-space:nowrap
label
{
width:10px;
display:block;
white-space:nowrap;
}
While debugging, when you hit a break-point.
CTRL+ALT+C
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
For two objects, Foo
and Bar
the relationships can be defined
Association - I have a relationship with an object. Foo
uses Bar
public class Foo {
void Baz(Bar bar) {
}
};
Composition - I own an object and I am responsible for its lifetime. When Foo
dies, so does Bar
public class Foo {
private Bar bar = new Bar();
}
Aggregation - I have an object which I've borrowed from someone else. When Foo
dies, Bar
may live on.
public class Foo {
private Bar bar;
Foo(Bar bar) {
this.bar = bar;
}
}
Place this css in your page:
<style>
#client_logos {
display: inline-block;
width:100%;
}
</style>
Replace
<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>
To
<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>
I've used MongoDB extensively (for the past 6 months), building a hierarchical data management system, and I can vouch for both the ease of setup (install it, run it, use it!) and the speed. As long as you think about indexes carefully, it can absolutely scream along, speed-wise.
I gather that Cassandra, due to its use with large-scale projects like Twitter, has better scaling functionality, although the MongoDB team is working on parity there. I should point out that I've not used Cassandra beyond the trial-run stage, so I can't speak for the detail.
The real swinger for me, when we were assessing NoSQL databases, was the querying - Cassandra is basically just a giant key/value store, and querying is a bit fiddly (at least compared to MongoDB), so for performance you'd have to duplicate quite a lot of data as a sort of manual index. MongoDB, on the other hand, uses a "query by example" model.
For example, say you've got a Collection (MongoDB parlance for the equivalent to a RDMS table) containing Users. MongoDB stores records as Documents, which are basically binary JSON objects. e.g:
{
FirstName: "John",
LastName: "Smith",
Email: "[email protected]",
Groups: ["Admin", "User", "SuperUser"]
}
If you wanted to find all of the users called Smith who have Admin rights, you'd just create a new document (at the admin console using Javascript, or in production using the language of your choice):
{
LastName: "Smith",
Groups: "Admin"
}
...and then run the query. That's it. There are added operators for comparisons, RegEx filtering etc, but it's all pretty simple, and the Wiki-based documentation is pretty good.
If the contents of the list are primitive data types, you can use a comprehension
new_list = [i for i in old_list]
You can nest it for multidimensional lists like:
new_grid = [[i for i in row] for row in grid]
PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
While it may work on some platforms, be aware that platform.architecture
is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize
on Python 2.6, 2.7, Python 3.x.
$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)
var linkGo = function(item) {_x000D_
$(item).on('click', function() {_x000D_
var _$this = $(this);_x000D_
var _urlBlank = _$this.attr("data-link");_x000D_
var _urlTemp = _$this.attr("data-url");_x000D_
if (_urlBlank === "_blank") {_x000D_
window.open(_urlTemp, '_blank');_x000D_
} else {_x000D_
// cross-origin_x000D_
location.href = _urlTemp;_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
linkGo(".button__main[data-link]");
_x000D_
.button{cursor:pointer;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<span class="button button__main" data-link="" data-url="https://stackoverflow.com/">go stackoverflow</span>
_x000D_
With the help of jquery it can be done as follows.
$("#color").prop('disabled', true);
If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation. It works pretty well. http://www.wingware.com/
You can do this,
User.query.filter_by(id=123).delete()
or
User.query.filter(User.id == 123).delete()
Make sure to commit
for delete()
to take effect.
I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:
public class RoomService {
public Room findByName(String roomName) {...}
public void persist(Room room) {...}
}
The service mock uses a map to store the Room instances.
RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();
// mock for method persist
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
Room room = (Room) arguments[0];
roomMap.put(room.getName(), room);
}
return null;
}
}).when(roomService).persist(any(Room.class));
// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
@Override
public Room answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if (arguments != null && arguments.length > 0 && arguments[0] != null) {
String key = (String) arguments[0];
if (roomMap.containsKey(key)) {
return roomMap.get(key);
}
}
return null;
}
});
We can now run our tests on this mock. For example:
String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));
For Ubuntu Users, the code_editor.xml
is in
/usr/share/mysql-workbench/data
edit as you need, In Ubuntu which is a must need, some default used colours lacks contrast and it is unable to read, For a quick workaround you can also use this solution.
Visit this repo to get the full XML file.
Swift
// create button
var backButton = UIButton(type: 101)
// left-pointing shape!
backButton.addTarget(self, action: #selector(self.backAction), for: .touchUpInside)
backButton.setTitle("Back", for: .normal)
// create button item -- possible because UIButton subclasses UIView!
var backItem = UIBarButtonItem(customView: backButton)
// add to toolbar, or to a navbar (you should only have one of these!)
toolbar.items = [backItem]
navItem.leftBarButtonItem = backItem
I give an example up on Group By between two table in Sql:
Select cn.name,ct.name,count(ct.id) totalcity
from city ct left join country cn on ct.countryid = cn.id
Group By cn.name,ct.name
Having totalcity > 2
According to composer's manual:
require-dev (root-only)
Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both
install
orupdate
support the--no-dev
option that prevents dev dependencies from being installed.
So running composer install
will also download the development dependencies.
The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
This is a Bash line that prints all available mac addresses, except the loopback:
for x in `ls /sys/class/net |grep -v lo`; do cat /sys/class/net/$x/address; done
Can be executed from a C program.
Check the namespace from where we are importing
import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**
I'm late to the party, but this is (unbelievably) still a problem as of the 11.05.2017. Here is a simple solution which will also work cross-platform with linear gradients:
.backgroundFixed {_x000D_
background: linear-gradient(160deg, #2db4a8 0%, #13af3d 100%);_x000D_
background-size: 100vw 100vh;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100vh;_x000D_
width: 100vw;_x000D_
z-index: -1000;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>title</title>_x000D_
</head>_x000D_
<body>_x000D_
<div class="backgroundFixed"></div>_x000D_
<div class="paragraphContainer">_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
<p>We're here to make the body scroll</p>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The universal solution is to connect your device to Mac and to observe what's going on during installation. I got an error:
Could not load download manifest with underlying error: Error Domain=NSURLErrorDomain Code=-1202 "Cannot connect to the Store" UserInfo=0x146635d0 {NSLocalizedDescription=Cannot connect to the Store, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, NSLocalizedFailureReason=A secure connection could not be established. Please check your Date & Time settings., NSErrorFailingURLStringKey=https://myserver.com/app/manifest.plist, NSUnderlyingError=0x14678880 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myserver.com” which could put your confidential information at risk.", NSURLErrorFailingURLPeerTrustErrorKey=, NSErrorFailingURLKey=https://myserver.com/app/manifest.plist}
There was even the suggestion in that error to check date settings. For some reason the date was 1 January 1970. Setting correct date solved the problem.
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Comparison of strings is very easy in Ruby:
v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true
Make sure your var2 is not an array (which seems to be like)
The traditional method for checking for packages in Python is "it's better to beg forgiveness than ask permission", or rather, "it's better to catch an exception than test a condition."
try:
import numpy
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
The lookup time is slow because when you use mmap
to does not load content of array to memory when you invoke load
method. Data is lazy loaded when particular data is needed.
And this happens in lookup in your case. But second lookup won`t be so slow.
This is nice feature of mmap
when you have a big array you do not have to load whole data into memory.
To solve your can use joblib you can dump any object you want using joblib.dump
even two or more numpy arrays
, see the example
firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')
It means that the method accepts a variable number of arguments ("varargs") of type JID
. Within the method, recipientJids
is presented.
This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.
It also enables idioms such as sprintf
from C; see String.format()
, for example.
JSON in any HTML tag except <script>
tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
I took the idiot route. Added these to the end of /etc/profile
for environment in `find /etc/environments.d -type f`
do
. $environment
done
created a folder /etc/environments create a file in it called "oracle" or "whatever" and added the stuff I needed set globally to it.
/etc$ cat /etc/environments.d/Oracle
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export DYLD_LIBRARY_PATH=/Library/Oracle/instantclient_11_2
export SQLPATH=/Library/Oracle/instantclient_11_2
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export TNS_ADMIN=/Library/Oracle/instantclient_11_2/network/admin
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words. Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings. Hope that helps!
You can easily do it using Regex
>>> import re
>>> re.sub("\D","","£70,000")
70000
you can use this way
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: { lat: parseFloat(lat), lng: parseFloat(lng) },
mapTypeId: 'terrain',
disableDefaultUI: true
});
EX : center: { lat: parseFloat(lat), lng: parseFloat(lng) },
A perfect 1/3 cannot exist in CSS with full cross browser support (anything below IE9). I personally would do: (It's not the perfect solution, but it's about as good as you'll get for all browsers)
#c1, #c2 {
width: 33%;
}
#c3 {
width: auto;
}
instead of using
session.delete(object)
use
getHibernateTemplate().delete(object)
In both place for select
query and also for delete
use getHibernateTemplate()
In select
query you have to use DetachedCriteria
or Criteria
Example for select query
List<foo> fooList = new ArrayList<foo>();
DetachedCriteria queryCriteria = DetachedCriteria.forClass(foo.class);
queryCriteria.add(Restrictions.eq("Column_name",restriction));
fooList = getHibernateTemplate().findByCriteria(queryCriteria);
In hibernate avoid use of session,here I am not sure but problem occurs just because of session use
The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:
$ brew tap SynthiNet/synthinet
$ brew install gcc47
Found it on a post here.
You can also use SET
to create a null byte
file as follows
set x=x > EmptyFile.txt
Or if you don't want to create an extra variable reassign an existing variable like
set PROMPT=%PROMPT% > EmptyFile.txt
or like this:
set "PROMPT=%PROMPT%" > EmptyFile.txt
Well /etc/crontab
just an ascii file so the simplest is to just
echo "*/15 * * * * root date" >> /etc/crontab
which will add a job which will email you every 15 mins. Adjust to taste, and test via grep
or other means whether the line was already added to make your script idempotent.
On Ubuntu et al, you can also drop files in /etc/cron.*
which is easier to do and test for---plus you don't mess with (system) config files such as /etc/crontab
.
You can easily do this by adding the following piece of CSS code:
display: table-cell;
vertical-align: middle;
That means your CSS finally looks like:
#box {_x000D_
height: 90px;_x000D_
width: 270px;_x000D_
background: #000;_x000D_
font-size: 48px;_x000D_
font-style: oblique;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
margin-top: 20px;_x000D_
margin-left: 5px;_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div id="box">_x000D_
Some text_x000D_
</div>
_x000D_
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
On BSD systems and Android you can also use fgetln
:
#include <stdio.h>
char *
fgetln(FILE *stream, size_t *len);
Like so:
size_t line_len;
const char *line = fgetln(stdin, &line_len);
The line
is not null terminated and contains \n
(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream.
Use "content:;" at the hover.This works.
Java version to create empty DataSet:
public Dataset<Row> emptyDataSet(){
SparkSession spark = SparkSession.builder().appName("Simple Application")
.config("spark.master", "local").getOrCreate();
Dataset<Row> emptyDataSet = spark.createDataFrame(new ArrayList<>(), getSchema());
return emptyDataSet;
}
public StructType getSchema() {
String schemaString = "column1 column2 column3 column4 column5";
List<StructField> fields = new ArrayList<>();
StructField indexField = DataTypes.createStructField("column0", DataTypes.LongType, true);
fields.add(indexField);
for (String fieldName : schemaString.split(" ")) {
StructField field = DataTypes.createStructField(fieldName, DataTypes.StringType, true);
fields.add(field);
}
StructType schema = DataTypes.createStructType(fields);
return schema;
}
Another thing you can do is to:
Item
model that returns the category name and ReadOnlyField
.Your model would look like this.
class Item(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, related_name='items')
def __unicode__(self):
return self.name
@property
def category_name(self):
return self.category.name
Your serializer would look like this. Note that the serializer will automatically get the value of the category_name
model property by naming the field with the same name.
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField()
class Meta:
model = Item
I want to register here what was my solution for this error which was a simple file not updated to Github.
I have a full stack project, and my files are structured both root directory for backend and client for the frontend (I am using React.js). All came down to the fact that I was mistakenly pushing the client folder only to Github and all my changes which had an error (missing a comma in a object's instance in my index.js) was not updated in the backend side. Since this Heroku fetches all updates from Github Repository, I couldn't access my server and the error persisted. Then all I had to do was to commit and push to the root directory and update all the changes of the project and everything came back to work again.
I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
Code for adding fragment
public Fragment getItem(int position) {
switch (position){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
default:
break;
}
return null;
}
Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
return view;
}
}
Later you can make necessary corrections.. It worked for me.
This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.
However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :
:not(.myclass1) + .myclass1
Full working code example:
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
<div>This text should appear as normal</div>_x000D_
<p>This text should be blue.</p>_x000D_
<p class="myclass1">This text should appear red.</p>_x000D_
<p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
You can do something like this to count from a list of things.
IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);
int count = methodNames.Where(x => names.Contains(x)).Count();
To count a single element
string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};
int count = words.Where(x => x.Equals(occur)).Count();
There are no underline even I deleted 'text-decoration: none;' from your code. But I had a similar experience.
Then I added a Code
a{
text-decoration: none;
}
and
a:hover{
text-decoration: none;
}
So, try your code with :hover.
None of these worked for me, but this did (and it had the added benefit of being able to have a better description for the name of each enum). I'm not sure if it's due to .net updates or not, but regardless I think this is the best way. You'll need to add a reference to:
using System.ComponentModel;
enum MyEnum
{
[Description("Red Color")]
Red = 10,
[Description("Blue Color")]
Blue = 50
}
....
private void LoadCombobox()
{
cmbxNewBox.DataSource = Enum.GetValues(typeof(MyEnum))
.Cast<Enum>()
.Select(value => new
{
(Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
value
})
.OrderBy(item => item.value)
.ToList();
cmbxNewBox.DisplayMember = "Description";
cmbxNewBox.ValueMember = "value";
}
Then when you want to access the data use these two lines:
Enum.TryParse<MyEnum>(cmbxNewBox.SelectedValue.ToString(), out MyEnum proc);
int nValue = (int)proc;
Expanding on Abdul's answer, you can obtain a KeyedTuple
instead of a discrete collection of rows by joining the columns:
q = Session.query(*User.__table__.columns + Document.__table__.columns).\
select_from(User).\
join(Document, User.email == Document.author).\
filter(User.email == 'someemail').all()
=============UPDATE=============
Since Android Studio introduce a new build system: Gradle. Android developers can now use a simple, declarative DSL to have access to a single, authoritative build that powers both the Android Studio IDE and builds from the command-line.
Edit your build.gradle
like this:
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion "19.0.3"
defaultConfig {
minSdkVersion 18
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:21.+'
}
NOTES: Use + in compile 'com.android.support:support-v4:21.+'
so that gradle can always use the newest version.
==========DEPRECATED==========
Because Android Studio is based on IntelliJ IDEA, so the procedure is just same like on IntelliJ IDEA 12 CE
1.Open Project Structure (Press F4 on PC and Command+; on MAC) on your project).
2.Select Modules on the left pane.
3.Choose your project and you will see Dependencies TAB above the third Column.
4.Click on the plus sign in the bottom. Then a tree-based directory chooser dialog will pop up, navigate to your folder containing android-support-v4.jar, press OK.
5.Press OK.
Just:
c:\>(for /r %f in (*.java) do @type %f ) | find /c /v ""
Font: https://superuser.com/questions/959036/what-is-the-windows-equivalent-of-wc-l
There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
You can try :
echo -e "newpasswd123\nnnewpasswd123" | passwd user
Here's my bash implementation (with bits taken from other SO ;-)
function countTimeDiff() {
timeA=$1 # 09:59:35
timeB=$2 # 17:32:55
# feeding variables by using read and splitting with IFS
IFS=: read ah am as <<< "$timeA"
IFS=: read bh bm bs <<< "$timeB"
# Convert hours to minutes.
# The 10# is there to avoid errors with leading zeros
# by telling bash that we use base 10
secondsA=$((10#$ah*60*60 + 10#$am*60 + 10#$as))
secondsB=$((10#$bh*60*60 + 10#$bm*60 + 10#$bs))
DIFF_SEC=$((secondsB - secondsA))
echo "The difference is $DIFF_SEC seconds.";
SEC=$(($DIFF_SEC%60))
MIN=$((($DIFF_SEC-$SEC)%3600/60))
HRS=$((($DIFF_SEC-$MIN*60)/3600))
TIME_DIFF="$HRS:$MIN:$SEC";
echo $TIME_DIFF;
}
$ countTimeDiff 2:15:55 2:55:16
The difference is 2361 seconds.
0:39:21
Not tested, may be buggy.
No need to add new plugin in pom.xml. Just run this command
mvn org.codehaus.mojo:exec-maven-plugin:1.5.0:java -Dexec.mainClass="com.example.Main" | grep -Ev '(^\[|Download\w+:)'
See the maven exec plugin for more usage.
This video tutorial worked for me:
$ curl https://bootstrap.pypa.io/get-pip.py | python
For me, I got this same error in VS 2015 and just installed the VS 2015 update 1, though from another answer, VS is actually up to Update 3, now (after which, they got the error and had to install .NET Core). Had issues when it hit certain packages, like the Windows SDK ones, and had to point the installer back at the paths in my original CD, and for some, even that didn't work and had to skip them and re-download from an internet-connected computer, transfer them over, and run them later manually (computer was not connected to the internet to be able to download updated versions of the packages), but after doing all that and doing a reboot, the error was gone and my project loaded fine.
I was about to advise to extract all the files at the same level, then to make a jar out of the result, since the package system should keep them neatly separated. That would be the manual way, I suppose the tools indicated by Steve will do that nicely.
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
This might happen due to various reasons
1) Check if you have VPN connected, you might get this error sometimes if yes
"Your hostname, localhost resolves to a loopback address: 127.0.0.1; using 10.xxx.1.193 instead (on interface cscotun0)"
2) Check your $HOSTNAME
3) try to ping $HOSTNAME on commandline and if it doesnt work, tweak the system settings to make your local host respond to pings
You can use selenium.Support
to use the SelectElement
class, this class have a property "Options" that is what you are looking for, I created an extension method to convert your web element to a select element
public static SelectElement AsDropDown(this IWebElement webElement)
{
return new SelectElement(webElement);
}
then you could use it like this
var elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
var options = elem.AsDropDown().Options
Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.
For i = 0 To d.Count - 1
s = d.Items()(i)
Debug.Print s
Next i()
KEYS works the same way
For i = 0 To d.Count - 1
Debug.Print d.Keys()(i), d.Items()(i)
Next i
This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".
Debug.Print Split("A,B,C,D", ",")(2)
SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.
Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.
You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list
Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.
check the symbolic links if they point to a valid library ...
You can add the path directly in /etc/ld.so.conf, without include...
run ldconfig -p
to see whether your library is well included in the cache.
To understand this question, you must first understand what SHA256 is. SHA256 is a Cryptographic Hash Function. A Cryptographic Hash Function is a one-way function, whose output is cryptographically secure. This means it is easy to compute a hash (equivalent to encrypting data), but hard to get the original input using the hash (equivalent to decrypting the data). Since using a Cryptographic hash function means decrypting is computationally infeasible, so therefore you cannot perform decryption with SHA256.
What you want to use is a two-way function, but more specifically, a Block Cipher. A function that allows for both encryption and decryption of data. The functions mcrypt_encrypt
and mcrypt_decrypt
by default use the Blowfish algorithm. PHP's use of mcrypt can be found in this manual. A list of cipher definitions to select the cipher mcrypt uses also exists. A wiki on Blowfish can be found at Wikipedia. A block cipher encrypts the input in blocks of known size and position with a known key, so that the data can later be decrypted using the key. This is what SHA256 cannot provide you.
$key = 'ThisIsTheCipherKey';
$ciphertext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, 'This is plaintext.', MCRYPT_MODE_CFB);
$plaintext = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $encrypted, MCRYPT_MODE_CFB);
I am using namespaces and rooms - I found
socket.broadcast.to('room1').emit('event', 'hi');
to work where
namespace.broadcast.to('room1').emit('event', 'hi');
did not
(should anyone else face that problem)
With parent::$bb;
you try to retrieve the static constant defined with the value of $bb
.
Instead, do:
echo $this->bb;
Note: you don't need to call parent::_construct
if B is the only class that calls it. Simply don't declare __construct in B class.
We should use any one depending upon our need. In case of ValueOf as it is instantiating an object. it will consume more resources if we only need value of some text then we should use parseInt,parseFloat etc.
Let me explain why you do you got this error "Bus error: 10"
char *str1 = "First string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY
char *str2 = "Second string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY
strcpy(str1, str2);
// This function will copy the content from str2 into str1, this is not possible because you are try to perform READ WRITE operation inside the READ-ONLY segment.Which was the root cause
If you want to perform string manipulation use automatic variables(STACK segment) or dynamic variables(HEAP segment)
Vasanth
Honestly, I had problems with bundler circular dependencies and the best way to go is rm -rf .bundle
. Save yourselves the headache and just use the hammer.
Reimeus is right, you see this because of in.close in your chooseCave(). Also, this is wrong.
if (playAgain == "yes") {
play = true;
}
You should use equals instead of "==".
if (playAgain.equals("yes")) {
play = true;
}
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.
private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
public static Document loadXMLFrom(String xml) throws Exception {
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
return doc;
}
You need this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<-- I absolutely don't know why, but go ahead, and add this code snippet to your CSS -->
*{
margin:0;
padding:0;
}
That's it, have fun removing all those white-spaces problems.
Use the built-in isinstance()
function.
import pandas as pd
def f(var):
if isinstance(var, pd.DataFrame):
print("do stuff")