I make it work like a charm with this:
function HideLayer(theEvent){
var MyDiv=document.getElementById('MyDiv');
if(MyDiv==(!theEvent?window.event:theEvent.target)){
MyDiv.style.display='none';
}
}
Ah, and MyDiv
tag is like this:
<div id="MyDiv" onmouseout="JavaScript: HideLayer(event);">
<!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>
This way, when onmouseout goes to a child, grand-child, etc... the style.display='none'
is not executed; but when onmouseout goes out of MyDiv it runs.
So no need to stop propagation, use timers, etc...
Thanks for examples, i could make this code from them.
Hope this helps someone.
Also can be improved like this:
function HideLayer(theLayer,theEvent){
if(theLayer==(!theEvent?window.event:theEvent.target)){
theLayer.style.display='none';
}
}
And then the DIVs tags like this:
<div onmouseout="JavaScript: HideLayer(this,event);">
<!-- Here whatever divs, inputs, links, images, anything you want... -->
<div>
So more general, not only for one div and no need to add id="..."
on each layer.
Alternative simple way is to use parsename
:
select full_name,
parsename(replace(full_name, ' ', '.'), 3) as FirstName,
parsename(replace(full_name, ' ', '.'), 2) as MiddleName,
parsename(replace(full_name, ' ', '.'), 1) as LastName
from YourTableName
I used some of the answers and found one that fit my case ( make sure all tasks are in the release branch).
Other methods works as well but I found that they might add lines that I do not need, like merge commits that add no value.
git fetch
git log origin/master..origin/release-1.1 --oneline --no-merges
or you can compare your current with master
git fetch
git log origin/master..HEAD --oneline --no-merges
git fetch
is there to make sure you are using updated info.
In this way each commit will be on a line and you can copy/paste that into an text editor and start comparing the tasks with the commits that will be merged.
A slightly other way of iterating through each column of each line of a CSV-file would be
$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path
foreach($line in $csv)
{
$properties = $line | Get-Member -MemberType Properties
for($i=0; $i -lt $properties.Count;$i++)
{
$column = $properties[$i]
$columnvalue = $line | Select -ExpandProperty $column.Name
# doSomething $column.Name $columnvalue
# doSomething $i $columnvalue
}
}
so you have the choice: you can use either $column.Name
to get the name of the column, or $i
to get the number of the column
Use the vectorised str
method replace
:
In [30]:
df['range'] = df['range'].str.replace(',','-')
df
Out[30]:
range
0 (2-30)
1 (50-290)
EDIT
So if we look at what you tried and why it didn't work:
df['range'].replace(',','-',inplace=True)
from the docs we see this desc:
str or regex: str: string exactly matching to_replace will be replaced with value
So because the str values do not match, no replacement occurs, compare with the following:
In [43]:
df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)
df['range']
Out[43]:
0 (2,30)
1 -
Name: range, dtype: object
here we get an exact match on the second row and the replacement occurs.
First I went with the Rich Bradshaw's approach, but then problems started to appear. By doing the e.preventDefault() on 'touchstart' event, the page no longer scrolls and, neither the long press is able to fire the options menu nor double click zoom is able to finish executing.
A solution could be finding out which event is being called and just e.preventDefault() in the later one, 'touchend'. Since scroll's 'touchmove' comes before 'touchend' it stays as by default, and 'click' is also prevented since it comes afterwords in the event chain applied to mobile, like so:
// Binding to the '.static_parent' ensuring dynamic ajaxified content
$('.static_parent').on('touchstart touchend', '.link', function (e) {
// If event is 'touchend' then...
if (e.type == 'touchend') {
// Ensuring we event prevent default in all major browsers
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
// Add class responsible for :hover effect
$(this).toggleClass('hover_effect');
});
But then, when options menu appears, it no longer fires 'touchend' responsible for toggling off the class, and next time the hover behavior will be the other way around, totally mixed up.
A solution then would be, again, conditionally finding out which event we're in, or just doing separate ones, and use addClass() and removeClass() respectively on 'touchstart' and 'touchend', ensuring it always starts and ends by respectively adding and removing instead of conditionally deciding on it. To finish we will also bind the removing callback to the 'focusout' event type, staying responsible for clearing any link's hover class that might stay on and never revisited again, like so:
$('.static_parent').on('touchstart', '.link', function (e) {
$(this).addClass('hover_effect');
});
$('.static_parent').on('touchend focusout', '.link', function (e) {
// Think double click zoom still fails here
e.preventDefault ? e.preventDefault() : e.returnValue = false;
$(this).removeClass('hover_effect');
});
Atention: Some bugs still occur in the two previous solutions and, also think (not tested), double click zoom still fails too.
Now, for a second, cleaner, tidier and responsive, approach just using javascript (no mix between .hover class and pseudo :hover) and from where you could call directly your ajax behavior on the universal (mobile and desktop) 'click' event, I've found a pretty well answered question from which I finally understood how I could mix touch and mouse events together without several event callbacks inevitably changing each other's ones up the event chain. Here's how:
$('.static_parent').on('touchstart mouseenter', '.link', function (e) {
$(this).addClass('hover_effect');
});
$('.static_parent').on('mouseleave touchmove click', '.link', function (e) {
$(this).removeClass('hover_effect');
// As it's the chain's last event we only prevent it from making HTTP request
if (e.type == 'click') {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
// Ajax behavior here!
}
});
A simple DIY way would be to make the grid yourself:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3], [2,3,4], 'ro')
for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')
for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()
Just a quick suggestion.. As indexing costs you additional writes and storage space, so if your application requires more insert/update operation, you might want to use tables without indexes, but if it requires more data retrieval operations, you should go for indexed table.
Include jQuery migration plugin along with your jQuery library.
The default values for minOccurs
and maxOccurs
are 1. Thus:
<xsd:element minOccurs="1" name="asdf"/>
cardinality is [1-1] Note: if you specify only minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.
<xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>
invalid
<xsd:element maxOccurs="2" name="asdf"/>
cardinality is [1-2] Note: if you specify only maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.
<xsd:element minOccurs="0" maxOccurs="0"/>
is a valid combination which makes the element prohibited.
For more info see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints
The documentation has the complete answer. Anyway this is how it is done:
<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>
will filter only age
in data
array and true
is for exact match.
For deep filtering,
<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>
The $
is a special property for deep filter and the true
is for exact match like above.
You need to execute a alter table statement for each table. The statement would follow this form:
ALTER TABLE tbl_name
[[DEFAULT] CHARACTER SET charset_name]
[COLLATE collation_name]
Now to get all the tables in the database you would need to execute the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="YourDataBaseName"
AND TABLE_TYPE="BASE TABLE";
So now let MySQL write the code for you:
SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," COLLATE your_collation_name_here;") AS ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="YourDatabaseName"
AND TABLE_TYPE="BASE TABLE";
You can copy the results and execute them. I have not tested the syntax but you should be able to figure out the rest. Think of it as a little exercise.
Hope That Helps!
If this still isn't working try unchecking "Enable Protected Mode" in IE.
Add your site to Local Intranet in
Tools -> Internet Option -> Security Tab
Then uncheck "Enable Protected Mode"
Restart IE
The 1*y
method works in Numpy too:
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)
>>> 1*y # Method 1
array([0, 0, 1, 1])
>>> y.astype(int) # Method 2
array([0, 0, 1, 1])
If you are asking for a way to convert Python lists from Boolean to int, you can use map
to do it:
>>> testList = [False, False, True, True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]
Or using list comprehensions:
>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]
JPanel pnlCircle = new JPanel() {
public void paintComponent(Graphics g) {
int X=100;
int Y=100;
int d=200;
g.drawOval(X, Y, d, d);
}
};
you can change X,Y coordinates and radius what you want.
There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).
Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.
Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.
Old question but here's the code on how to do what you are asking. In this case I am passing data from a selected cell in a table view to another view controller.
in the .h file of the trget view:
@property(weak, nonatomic) NSObject* dataModel;
in the .m file:
@synthesize dataModel;
dataModel
can be string
, int
, or like in this case it's a model that contains many items
- (void)someMethod {
[self performSegueWithIdentifier:@"loginMainSegue" sender:self];
}
OR...
- (void)someMethod {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"storyDetailsSegway"]) {
UITableViewCell *cell = (UITableViewCell *) sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSDictionary *storiesDict =[topStories objectAtIndex:[indexPath row]];
StoryModel *storyModel = [[StoryModel alloc] init];
storyModel = storiesDict;
StoryDetails *controller = (StoryDetails *)segue.destinationViewController;
controller.dataModel= storyModel;
}
}
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
It's been solved.
The losses only save to the History over the epochs. I was running iterations instead of using the Keras built in epochs option.
so instead of doing 4 iterations I now have
model.fit(......, nb_epoch = 4)
Now it returns the loss for each epoch run:
print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, h1.3758836857303727]}
These days, once you have LINQ available, you can convert the dictionary keys and their values to a single string.
You can use the following code:
// convert the dictionary to an array of strings
string[] strArray = dict.Select(x => ("Key: " + x.Key + ", Value: " + x.Value)).ToArray();
// convert a string array to a single string
string result = String.Join(", ", strArray);
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
I did a test using the Chrome address bar and a $QUERY_STRING
in bash, and observed the following:
~!@$%^&*()-_=+[{]}\|;:',./?
and grave (backtick)
are passed through as plaintext.
,
"
, <
and >
are converted to %20
, %22
, %3C
and %3E
respectively.
#
is ignored, since it is used by ye olde anchor.
Personally, I'd say bite the bullet and encode with base64 :)
I had this issue too. I deleted the extra images from my project's drawable folder.
I have found that 6 decimal places is sometimes required (at least in Chrome) for the 1/3 to return a perfect result.
E.g., 1140px / 3 = 380px
If you had 3 elements within the 1140 container, they would need to have a width set to 33.333333% before Chrome's inspector tool shows that they are at 380px. Any less amount of decimal places, and Chrome returns a lesser width of 379.XXXpx
You can use Google Guava's ImmutableMap. This works as long as you don't care about modifying the Map later (you can't call .put() on the map after constructing it using this method):
import com.google.common.collect.ImmutableMap;
// For up to five entries, use .of()
Map<String, Integer> littleMap = ImmutableMap.of(
"One", Integer.valueOf(1),
"Two", Integer.valueOf(2),
"Three", Integer.valueOf(3)
);
// For more than five entries, use .builder()
Map<String, Integer> bigMap = ImmutableMap.<String, Integer>builder()
.put("One", Integer.valueOf(1))
.put("Two", Integer.valueOf(2))
.put("Three", Integer.valueOf(3))
.put("Four", Integer.valueOf(4))
.put("Five", Integer.valueOf(5))
.put("Six", Integer.valueOf(6))
.build();
See also: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableMap.html
A somewhat related question: ImmutableMap.of() workaround for HashMap in Maps?
You need the action that corresponds to the controller to not have a parameter.
Looks like for the controller / action combination you have:
public ActionResult Action(int parameter)
{
}
but you need
public ActionResult Action()
{
}
Also, check out Phil Haack's Route Debugger to troubleshoot routes.
I am a very good iPhone app developer, and I charge over $150 per hour for my services. I have a ton of experience building iPhone apps and their server side components. I have also been called in on several occasions to fix offshore developed apps. Here's my take.
I'm just about to release a shopping app for a client. The design work was done by 2 client in-house designers over 2 weeks, quick because they had all the image assets already. Think 2 people x 10 days x 8 hours = ~$24,000. The server side had to be modified to provide data for the iPhone app. We used their in-house team and in-house platform and in-house API, 2 developers, 4 weeks, or about $50,000 and that's because they already have a web shop and API. Cost them about $400,000 to get there (excluding platform). And I wrote the app side in 3 weeks, given that a lot of my code is duplicated from previous projects, another ~$25,000, the cheapest app I ever did.
Total spent: ~$100,000, and that's insanely cheap!
And they will give this away for free so clients will buy from their store from their iPhones.
For your app, Peter, if you have the servers and the APIs and the design, I'd guess at $30,000 to $60,000 depending on complexity. If you do not have the design, double it. If you do not have the APIs, double again...
I just searched a text with following command which listed me all the file names containing my specified 'search text'.
C:\Users\ak47\Desktop\trunk>findstr /S /I /M /C:"search text" *.*
You can use sklearn.feature_extraction.text.CountVectorizer:
import sklearn.feature_extraction.text # FYI http://scikit-learn.org/stable/install.html
ngram_size = 4
string = ["I really like python, it's pretty awesome."]
vect = sklearn.feature_extraction.text.CountVectorizer(ngram_range=(ngram_size,ngram_size))
vect.fit(string)
print('{1}-grams: {0}'.format(vect.get_feature_names(), ngram_size))
outputs:
4-grams: [u'like python it pretty', u'python it pretty awesome', u'really like python it']
You can set to ngram_size
to any positive integer. I.e. you can split a text in four-grams, five-grams or even hundred-grams.
Since it is difficult to do 3rd party cookies and also some browsers won't allow that.
You can try storing them in HTML5 local storage and then sending them with every request from your front end app.
Usually, activating a virtualenv gives you a shell function named:
$ deactivate
which puts things back to normal.
I have just looked specifically again at the code for virtualenvwrapper
, and, yes, it too supports deactivate
as the way to escape from all virtualenvs.
If you are trying to leave an Anaconda environment, the command depends upon your version of conda
. Recent versions (like 4.6) install a conda
function directly in your shell, in which case you run:
conda deactivate
Older conda versions instead implement deactivation using a stand-alone script:
source deactivate
You wouldn’t: it’s messy and hard to read.
You’re looking for the switch
statement in the first case. The second is fine as it is but still could be converted for consistency
Ternary statements are much more suited to boolean values and alternating logic.
Here is a script based on Yavuz Sert's answer. It deletes all tags that are not the latest version, and their tag is greater than 950.
#!/usr/bin/env bash
CheckTag(){
Name=$1
Tag=$2
Skip=0
if [[ "${Tag}" == "latest" ]]; then
Skip=1
fi
if [[ "${Tag}" -ge "950" ]]; then
Skip=1
fi
if [[ "${Skip}" == "1" ]]; then
echo "skip ${Name} ${Tag}"
else
echo "delete ${Name} ${Tag}"
Sha=$(curl -v -s -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X GET http://127.0.0.1:5000/v2/${Name}/manifests/${Tag} 2>&1 | grep Docker-Content-Digest | awk '{print ($3)}')
Sha="${Sha/$'\r'/}"
curl -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE "http://127.0.0.1:5000/v2/${Name}/manifests/${Sha}"
fi
}
ScanRepository(){
Name=$1
echo "Repository ${Name}"
curl -s http://127.0.0.1:5000/v2/${Name}/tags/list | jq '.tags[]' |
while IFS=$"\n" read -r line; do
line="${line%\"}"
line="${line#\"}"
CheckTag $Name $line
done
}
JqPath=$(which jq)
if [[ "x${JqPath}" == "x" ]]; then
echo "Couldn't find jq executable."
exit 2
fi
curl -s http://127.0.0.1:5000/v2/_catalog | jq '.repositories[]' |
while IFS=$"\n" read -r line; do
line="${line%\"}"
line="${line#\"}"
ScanRepository $line
done
If you get this error in a context of creating ForeignKey relations between models. Example below raises AppRegistryNotReady: Models aren't loaded yet
error.
from my_app.models import Workspace
workspace = models.ForeignKey(Workspace)
Then please try to reffer to a model as a string.
from my_app.models import Workspace
# One of these two lines might fix the problem.
workspace = models.ForeignKey('Workspace')
workspace = models.ForeignKey('my_app.Workspace')
In Django, it acts as a configuration class and keeps the configuration data in one place!!
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(444, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");
ToolStripButton btn = new ToolStripButton("m1");
btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
btn.Image = (Image)O;
this.toolStrip1.Items.Add(btn);
this.Controls.Add(this.toolStrip1);
You can consider using memory-mapped files, via FileChannels .
Generally a lot faster for large files. There are performance trade-offs that could make it slower, so YMMV.
Related answer: Java NIO FileChannel versus FileOutputstream performance / usefulness
Pass cls
parameter into @classmethod
to resolve this problem.
@classmethod
def test(cls):
return ''
Look up ?strftime
:
%A
Full weekday name in the current locale
df$day = strftime(df$date,'%A')
Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:
byte[] fullyReadFileToBytes(File f) throws IOException {
int size = (int) f.length();
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
FileInputStream fis= new FileInputStream(f);;
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e){
throw e;
} finally {
fis.close();
}
return bytes;
}
NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.
You must to have installed php_openssl.dll, if you use wampserver it's pretty easy, search and apply the extension for PHP.
In the example change this:
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
$mail->Port = 465;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl';
and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications here https://www.google.com/settings/security/lesssecureapps
I recommend you change the password and encrypt it constantly
in C++ expression a % b
returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:
5 % 2 = 1
13 % 5 = 3
With this knowledge we can try to understand your code. Condition count % 6 == 5
means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).
To get desired behaviour from your code, you should change condition to count % 5 == 4
, what will give you newline every 5 lines, starting at 5-th line (count = 4).
so, if you want to update parent component,
class ParentComponent extends React.Component {
constructor(props){
super(props);
this.state = {
page:0
}
}
handler(val){
console.log(val) // 1
}
render(){
return (
<ChildComponent onChange={this.handler} />
)
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
page:1
};
}
someMethod = (page) => {
this.setState({ page: page });
this.props.onChange(page)
}
render() {
return (
<Button
onClick={() => this.someMethod()}
> Click
</Button>
)
}
}
Here onChange is an attribute with "handler" method bound to it's instance. we passed the method handler to the Child class component, to receive via onChange property in its props argument.
The attribute onChange will be set in a props object like this:
props ={
onChange : this.handler
}
and passed to the child component
So the Child component can access the value of name in the props object like this props.onChange
Its done through the use of render props.
Now the Child component has a button “Click” with an onclick event set to call the handler method passed to it via onChnge in its props argument object. So now this.props.onChange in Child holds the output method in the Parent class Reference and credits: Bits and Pieces
I had the same problem. The problem with the Sublime Text's default console is that it does not support input.
To solve it, you have to install a package called SublimeREPL. SublimeREPL provides a Python interpreter which accepts input.
There is an article that explains the solution in detail.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace App_name
{
public class CustomTextBox : TextBox
{
private string Text_ = "";
public CustomTextBox() : base()
{}
public string setHint
{
get { return Text_; }
set { Text_ = value; }
}
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
if (Text_.Equals(this.Text))
this.Clear();
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if (String.IsNullOrWhiteSpace(this.Text))
this.Text = Text_;
}
}
}
> xmlns:local="clr-namespace:app_name"
> <local:CustomTextBox
> x:Name="id_number_txt"
> Width="240px"
> Height="auto"/>
After spending a couple of hours today trying every solution here, I was still unable to get past this exact error. I have used gmail many times in this way so I knew it was something dumb, but nothing I did fixed the problem. I finally stumbled across the solution in my case so thought I would share.
First, most of the answers above are also required, but in my case, it was a simple matter of ordering of the code while creating the SmtpClient
class.
In this first code snippet below, notice where the Credentials = creds
line is located. This implementation will generate the error referenced in this question even if you have everything else set up properly.
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient
{
Host = Emailer.Host,
Port = Emailer.Port,
Credentials = creds,
EnableSsl = Emailer.RequireSSL,
UseDefaultCredentials = false,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network
}
However, if you move the Credentials setter call to the bottom, the email will be sent without error. I made no changes to the surrounding code...ie...the username/password, etc. Clearly, either the EnableSSL, UseDefaultCredentials, or the DeliveryMethod
is dependent on the Credentials
being set first... I didn't test all to figure out which one it was though.
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient
{
Host = Emailer.Host,
Port = Emailer.Port,
EnableSsl = Emailer.RequireSSL,
UseDefaultCredentials = false,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
Credentials = creds
}
Hope this helps save someone else some headaches in the future.
It's now called rounded-circle
as explained here in the BS4 docs
<img src="img/gallery2.JPG" class="rounded-circle">
Here's what I did:
var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();
Where {{ time }}
is the utc timestamp.
json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
I can't answer all questions, but I will do my best.
As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.
Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.
WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).
In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.
Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.
About the protocol, as Wikipedia shows, it looks like this:
Client sends:
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
Server replies:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.
As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support
Upgrade: websocket
Connection: Upgrade
will reply with an error or with a page content.
Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:
IntStream.range(0, params.size())
.forEach(idx ->
query.bind(
idx,
params.get(idx)
)
)
;
The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
If copy assignment operator of foo and bar is cheap (eg. int, char, pointer etc), you can do the following:
foo f; bar b;
BOOST_FOREACH(boost::tie(f,b),testing)
{
cout << "Foo is " << f << " Bar is " << b;
}
The following produces a uniform distribution on {1, 2, 3, 4, 5, 6, 7} using a random number generator producing a uniform distribution on {1, 2, 3, 4, 5}. The code is messy, but the logic is clear.
public static int random_7(Random rg) {
int returnValue = 0;
while (returnValue == 0) {
for (int i = 1; i <= 3; i++) {
returnValue = (returnValue << 1) + SimulateFairCoin(rg);
}
}
return returnValue;
}
private static int SimulateFairCoin(Random rg) {
while (true) {
int flipOne = random_5_mod_2(rg);
int flipTwo = random_5_mod_2(rg);
if (flipOne == 0 && flipTwo == 1) {
return 0;
}
else if (flipOne == 1 && flipTwo == 0) {
return 1;
}
}
}
private static int random_5_mod_2(Random rg) {
return random_5(rg) % 2;
}
private static int random_5(Random rg) {
return rg.Next(5) + 1;
}
Where it is documented:
From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"
collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!
The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,
Class Dog
has_many :tags
belongs_to :person
end
Class Person
has_many :dogs
end
d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")
or even
t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")
You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)
How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
Try to use:
pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"
The second result set
have only one column but it should have 3 columns for it to be contented to the first result set
(columns must match when you use UNION
)
Try to add ID
as first column and PartOf_LOC_id
to your result set
, so you can do the UNION
.
;
WITH q AS ( SELECT ID ,
Location ,
PartOf_LOC_id
FROM tblLocation t
WHERE t.ID = 1 -- 1 represents an example
UNION ALL
SELECT t.ID ,
parent.Location + '>' + t.Location ,
t.PartOf_LOC_id
FROM tblLocation t
INNER JOIN q parent ON parent.ID = t.LOC_PartOf_ID
)
SELECT *
FROM q
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
C++ is a standardized language. Visual C++ is a product that more or less implements that standard. You can write portable C++ using Visual C++, but you can also use Microsoft-only extensions that destroy your portability but enhance your productivity. This is a trade-off. You have to decide what appeals most to you.
I've maintained big desktop apps that were written in Visual C++, so that is perfectly feasible. From what I know of Visual Basic, the main advantage seems to be that the first part of the development cycle may be done faster than when using Visual C++, but as the complexity of a project increases, C++ programs tend to be more maintainable (If the programmers are striving for maintainability, that is).
There is an other way to load jQuery dynamically (source). You could also use
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');
It's considered bad practice to use document.write
, but for sake of completion it's good to mention it.
See Why is document.write considered a "bad practice"? for the reasons. The pro is that document.write
does block your page from loading other assests, so there is no need to create a callback function.
In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:
@(String.IsNullOrEmpty(Model.MaidenName) ? " " : Model.MaidenName)
This would print me " " in my page, respectively generate the source &nbsp;
. Now there is a function Html.Raw(" ")
which is supposed to let you write source code, except in this constellation it throws a compiler error:
Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'
So I ended up writing a statement like the following, which is less nice but works even in my case:
@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw(" ") } else { @Model.MaidenName }
Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.
The error message states which logger it is using, so set that logger .level
:
[jasper] Jul 31, 2012 7:15:15 PM org.apache.jasper.compiler.TldLocationsCache tldScanJar
So the logger is org.apache.jasper.compiler.TldLocationsCache
. In your logging.properties
file, add this line:
org.apache.jasper.compiler.TldLocationsCache.level = FINE
Try indextank.
As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.
I wrote this function:
public static String encode(@NonNull String uriString) {
if (TextUtils.isEmpty(uriString)) {
Assert.fail("Uri string cannot be empty!");
return uriString;
}
// getQueryParameterNames is not exist then cannot iterate on queries
if (Build.VERSION.SDK_INT < 11) {
return uriString;
}
// Check if uri has valid characters
// See https://tools.ietf.org/html/rfc3986
Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
"=-]|%[0-9a-fA-F]{2})+");
Matcher matcher = allowedUrlCharacters.matcher(uriString);
String validUri = null;
if (matcher.find()) {
validUri = matcher.group();
}
if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
return uriString;
}
// The uriString is not encoded. Then recreate the uri and encode it this time
Uri uri = Uri.parse(uriString);
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(uri.getScheme())
.authority(uri.getAuthority());
for (String path : uri.getPathSegments()) {
uriBuilder.appendPath(path);
}
for (String key : uri.getQueryParameterNames()) {
uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
}
String correctUrl = uriBuilder.build().toString();
return correctUrl;
}
Here are some more examples where _
is used:
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums filter (_ % 2 == 0)
nums reduce (_ + _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)
You can use javac *.java
command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.
Yes, sort of.
Here you go by example :
void printA(int a){
printf("Hello world from printA : %d\n",a);
}
void printB(const char *buff){
printf("Hello world from printB : %s\n",buff);
}
#define Max_ITEMS() 6, 5, 4, 3, 2, 1, 0
#define __VA_ARG_N(_1, _2, _3, _4, _5, _6, N, ...) N
#define _Num_ARGS_(...) __VA_ARG_N(__VA_ARGS__)
#define NUM_ARGS(...) (_Num_ARGS_(_0, ## __VA_ARGS__, Max_ITEMS()) - 1)
#define CHECK_ARGS_MAX_LIMIT(t) if(NUM_ARGS(args)>t)
#define CHECK_ARGS_MIN_LIMIT(t) if(NUM_ARGS(args)
#define print(x , args ...) \
CHECK_ARGS_MIN_LIMIT(1) printf("error");fflush(stdout); \
CHECK_ARGS_MAX_LIMIT(4) printf("error");fflush(stdout); \
({ \
if (__builtin_types_compatible_p (typeof (x), int)) \
printA(x, ##args); \
else \
printB (x,##args); \
})
int main(int argc, char** argv) {
int a=0;
print(a);
print("hello");
return (EXIT_SUCCESS);
}
It will output 0 and hello .. from printA and printB.
Note: this solution and any other "edit the policy.xml" solution disables safety measures against arbitrary code execution vulnerabilities in ImageMagick. If you need to process input that you do not control 100%, you should use a different program (not ImageMagick).
If you're still here, you are trying to edit images that you have complete control over, know are safe, and cannot be edited by users.
There is an /etc/ImageMagick/policy.xml
file that is installed by yum. It disallows almost everything (for security and to protect your system from getting overloaded with ImageMagick calls).
If you're getting a ReadImage
error as above, you can change the line to:
<policy domain="coder" rights="read" pattern="LABEL" />
which should fix the issue.
The file has a bunch of documentation in it, so you should read that. For example, if you need more permissions, you can combine them like:
<policy domain="coder" rights="read|write" pattern="LABEL" />
...which is preferable to removing all permissions checks (i.e., deleting or commenting out the line).
System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip( Label1, "Label for Label1");
I had the same problem, after some Windows 8.0 crash and update, on msys git 1.9. I didn't find any msys/git in my path, so I just added it in windows local-user envinroment settings. It worked without restarting.
Basically, similiar to RobertB, but I didn't have any git/msys in my path.
Btw:
I tried using rebase -b blablabla msys.dll, but had error "ReBaseImage (msys-1.0.dll) failed with last error = 6"
if you need this quickly and don't have time debugging, I noticed "Git Bash.vbs" in Git directory successfuly starts bash shell.
If you don't want a fixed layout, specify a class for the column to be size appropriately.
CSS:
.special_column { width: 120px; }
HTML:
<td class="special_column">...</td>
You can consider leveraging React's Context feature.
class NavigationContainer extends React.Component {
constructor(props) {
super(props);
this.goTo = this.goTo.bind(this);
}
goTo(location) {
...
}
getChildContext() {
// returns the context to pass to children
return {
goTo: this.goTo
}
}
...
}
// defines the context available to children
NavigationContainer.childContextTypes = {
goTo: PropTypes.func
}
class SomeViewContainer extends React.Component {
render() {
// grab the context provided by ancestors
const {goTo} = this.context;
return <button onClick={evt => goTo('somewhere')}>
Hello
</button>
}
}
// Define the context we want from ancestors
SomeViewContainer.contextTypes = {
goTo: PropTypes.func
}
With context
, you can pass data through the component tree without having to pass the props down manually at every level. There is a big warning on this being an experimental feature and may break in the future, but I would imagine this feature to be around given the majority of the popular frameworks like Redux use context
extensively.
The main advantage of using context
v.s. a global variable is context
is "scoped" to a subtree (this means you can define different scopes for different subtrees).
Do note that you should not pass your model data via context
, as changes in context
will not trigger React's component render cycle. However, I do find it useful in some use case, especially when implementing your own custom framework or workflow.
This can be achieved using java.util.Date
. The following code will subtract 1 hour from your date.
Date date = new Date(yourdate in date format);
Date newDate = DateUtils.addHours(date, -1)
Similarly for subtracting 20 seconds from your date
newDate = DateUtils.addSeconds(date, -20)
Hi every one this code is workin for me please try with this for sending mail to multiple recepients
private String recipient = "[email protected] ,[email protected] ";
String[] recipientList = recipient.split(",");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipient : recipientList) {
recipientAddress[counter] = new InternetAddress(recipient.trim());
counter++;
}
message.setRecipients(Message.RecipientType.TO, recipientAddress);
I use git, and today I ported this (git-xlsx-textconv) to Python, since my project is based on Python code, and it interacts with Excel files. This works for at least .xlsx files, but I think it will work for .xls too. Here's the github link. I wrote two versions, one with each row on its own line, and another where each cell is on its own line (the latter was written because git diff doesn't like to wrap long lines by default, at least here on Windows).
This is my .gitconfig file (this allows the differ script to reside in my project's repo):
[diff "xlsx"]
binary = true
textconv = python `git rev-parse --show-toplevel`/src/util/git-xlsx-textconv.py
if you want the script to be available for many different repos, then use something like this:
[diff "xlsx"]
binary = true
textconv = python C:/Python27/Scripts/git-xlsx-textconv.py
my .gitattributes file:
*.xlsx diff=xlsx
I am using a UIView extension , approach is close to @ChrisB approach above
extension UIView {
func updateHeight(_ height:NSLayoutConstraint)
{
let newSize = CGSize(width: self.frame.size.width, height: CGFloat(MAXFLOAT))
let fitSize : CGSize = self.sizeThatFits(newSize)
height.constant = fitSize.height
}
}
implementation : :
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var myTableVieweHeight: NSLayoutConstraint!
//(call it whenever tableView is updated inside/outside delegate methods)
myTableView.updateHeight(myTableVieweHeigh)
Bonus : Can be used on any other UIViews eg:your own dynamic label
Boolean("true") will do the work too
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.0'
}
Just make your dependencies like above in build.gradle file, worked for me.
for log file you may date to enter into text data. following code may help
# declaring variables
Logfile="logfile.txt"
MAIL_LOG="Message to print in log file"
Location="were is u want to store log file"
cd $Location
if [ -f $Logfile ]
then
echo "$MAIL_LOG " >> $Logfile
else
touch $Logfile
echo "$MAIL_LOG" >> $Logfile
fi
ouput: 2. Log file will be created in first run and keep on updating from next runs. In case log file missing in future run , script will create new log file.
I spent almost two days on finding the solution for this problem and I found this at last.
This uses javascript and jquery.
(GitHub) pointer_events_polyfill
This could use a javascript plug-in to be downloaded/copied.
Just copy/download the codes from that site and save it as pointer_events_polyfill.js
. Include that javascript to your site.
<script src="JS/pointer_events_polyfill.js></script>
Add this jquery scripts to your site
$(document).ready(function(){
PointerEventsPolyfill.initialize({});
});
And don't forget to include your jquery plug-in.
It works! I can click elements under the transparent element. I'm using IE 10. I hope this can also work in IE 9 and below.
EDIT: Using this solution does not work when you click the textboxes below the transparent element. To solve this problem, I use focus when the user clicks on the textbox.
Javascript:
document.getElementById("theTextbox").focus();
JQuery:
$("#theTextbox").focus();
This lets you type the text into the textbox.
Right-click on toolbar then click on "choose item" in context menu. A dialog with registered components pops up. in this dialog click "Browse" to select your assembly with the usercontrol you want to use.
PS. This assembly should be registered before.
this can be done this way
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}
Range("$A$1").Value = "'01/01/13 00:00"
will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
As all "public variables" are in fact properties of the window object (of the window/tab you are looking at), you can just inspect the "window" object instead. If you have multiple frames, you will have to select the correct window object (like in Firebug) anyway.
.Net Core does not require mono in the sense of the mono framework. .Net Core is a framework that will work on multiple platforms including Linux. Reference https://dotnet.github.io/.
However the .Net core can use the mono framework. Reference https://docs.asp.net/en/1.0.0-rc1/getting-started/choosing-the-right-dotnet.html (note rc1 documentatiopn no rc2 available), however mono is not a Microsoft supported framework and would recommend using a supported framework
Now entity framework 7 is now called Entity Framework Core
and is available on multiple platforms including Linux. Reference https://github.com/aspnet/EntityFramework (review the road map)
I am currently using both of these frameworks however you must understand that it is still in release candidate stage (RC2
is the current version) and over the beta & release candidates there have been massive changes that usually end up with you scratching your head.
Here is a tutorial on how to install MVC .Net Core into Linux. https://docs.asp.net/en/1.0.0-rc1/getting-started/installing-on-linux.html
Finally you have a choice of Web Servers (where I am assuming the fast cgi
reference came from) to host your application on Linux. Here is a reference point for installing to a Linux enviroment. https://docs.asp.net/en/1.0.0-rc1/publishing/linuxproduction.html
I realise this post ends up being mostly links to documentation but at this point those are your best sources of information. .Net core is still relatively new in the .Net community and until its fully released I would be hesitant to use it in a product environment given the breaking changes between released version.
In most cases, you should use the instanceof
operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[]
or an int[]
. You'd want to guard your casts with instanceof
:
if (obj instanceof Integer[]) {
Integer[] array = (Integer[]) obj;
/* Use the boxed array */
} else if (obj instanceof int[]) {
int[] array = (int[]) obj;
/* Use the primitive array */
} else ...
At the JVM level, the instanceof
operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.
In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray()
method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.
There are two special cases: null references and references to primitive arrays.
A null reference will cause instanceof
to result false
, while the isArray
throws a NullPointerException
.
Applied to a primitive array, the instanceof
yields false
unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray()
will return true
for any component type.
There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
I had this problem before, and the reason is very simple: Check your variables, if there were strings, so put it in quotes '$your_string_variable_here' ,, if it were numerical keep it without any quotes. for example, if I had these data: $name ( It will be string ) $phone_number ( It will be numerical ) So, it will be like that:
$query = "INSERT INTO users
(name
, phone
) VALUES ('$name', $phone)";
Just like that and it will be fixed ^_^
JSON.parse()
is for "parsing" something that was received as JSON.
JSON.stringify()
is to create a JSON string out of an object/array.
The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.
Create it at the following location <your home folder>/.m2/settings.xml
e.g. C:\Users\YourUserName\.m2\settings.xml
on Windows or /home/YourUserName/.m2/settings.xml
on Linux
Here's an empty skeleton you can use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>
If you use Eclipse to edit it, it will give you auto-completion when editing it.
And here's the Maven settings.xml Reference page
cat script.sh
var1=$1
var2=$2
if [ "$#" -eq 2 ]
then
if [ -d $var1 ]
then
echo directory ${var1} exist
else
echo Directory ${var1} Does not exists
fi
if [ -d $var2 ]
then
echo directory ${var2} exist
else
echo Directory ${var2} Does not exists
fi
else
echo "Arguments are not equals to 2"
exit 1
fi
execute it like below -
./script.sh directory1 directory2
Output will be like -
directory1 exit
directory2 Does not exists
Put quite simply:
SELECT 'This is Ashok''s Pen.';
So inside the string, replace each single quote with two of them.
Or:
SELECT 'This is Ashok\'s Pen.'
Escape it =)
There isn’t really an ideal conversion, but I would like to supply a couple of options.
java.time
First, you should use LocalDate
from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date
and SimpleDateFormat
since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.
DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dateString = "13/06/1983";
LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
System.out.println(date);
The output is:
1983-06-13
Do you need to go any further? LocalDate.toString()
produces the format you asked about.
Format and parse
Assuming that you do require an XMLGregorianCalendar
the first and easy option for converting is:
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(date.toString());
System.out.println(xmlDate);
1983-06-13
Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.
Pass year, month and day of month individually
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);
The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED
specifies). In case someone is wondering, both LocalDate
and XMLGregorianCalendar
number months the way humans do, so there is no adding or subtracting 1.
Convert through GregorianCalendar
I only show you this option because I somehow consider it the official way: convert LocalDate
to ZonedDateTime
, then to GregorianCalendar
and finally to XMLGregorianCalendar
.
ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gregCal);
xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop. Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.
This may also help:
SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)
-- Oct 2 2008 11:01AM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
-- Oct 2 2008 11:02:44:013AM
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
-- 02 Oct 2008 11:02:07:577
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
-- 2008-10-02T10:52:47.513
-- SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd
SELECT convert(varchar(7), getdate(), 126) -- yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8) -- mon yyyy
Use a CURSOR in PostgreSQL or let the JDBC-driver handle this for you.
LIMIT and OFFSET will get slow when handling large datasets.
I was able to set the default value or whatever value using the following:
Template:
<mat-form-field>
<mat-label>Holiday Destination</mat-label>
<mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
<mat-option [value]="nyc">New York</mat-option>
<mat-option [value]="london">London</mat-option>
<mat-option [value]="india">Delhi</mat-option>
<mat-option [value]="Oslo">Oslo</mat-option>
</mat-select>
</mat-form-field>
Component:
export class WhateverComponent implements OnInit{
selectedCity: string;
}
ngOnInit() {
this.selectedCity = 'london';
}
}
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
With the reference of Biswajit Roy: Dynamic Programming firstly plans then Go. and Greedy algorithm uses greedy choice, it firstly Go then continuously Plans.
There are many solutions here but probably the best one that works. Check the version of the script you want to use.
Well at least I can give you my 100% working solution for
version : 4.17.45
bootstrap-datetimejs https://github.com/Eonasdan/bootstrap-datetimepicker Copyright (c) 2015 Jonathan Peterson
JavaScript
var startdate = $('#startdate').val();
The output looks like: 12.09.2018 03:05
Just use before and after Pseudo-elements - CSS
*{box-sizing: border-box; padding: 0; margin: 0}_x000D_
:root{background: white; transition: background .3s ease-in-out}_x000D_
:root:hover{background: red }_x000D_
div{_x000D_
margin: 20px auto;_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
position:relative_x000D_
}_x000D_
_x000D_
div:before, div:after{_x000D_
content: '';_x000D_
position: absolute;_x000D_
width: 75px;_x000D_
height: 20px;_x000D_
background: black;_x000D_
left: 40px_x000D_
}_x000D_
_x000D_
div:before{_x000D_
top: 45px;_x000D_
transform: rotateZ(45deg)_x000D_
}_x000D_
_x000D_
div:after{_x000D_
bottom: 45px;_x000D_
transform: rotateZ(-45deg)_x000D_
}
_x000D_
<div/>
_x000D_
I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.
An object
with a unencoded dataUri might have also fit your need if it was only to load a portion of data text:
The HTML
<object>
element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.
body {display:flex;min-height:25em;}
p {margin:auto;}
object {margin:0 auto;background:lightgray;}
_x000D_
<p>here My uploaded content: </p>
<object data='data:text/html,
<style>
.table {
display: table;
text-align:center;
width:100%;
height:100%;
}
.table > * {
display: table-row;
}
.table > main {
display: table-cell;
height: 100%;
vertical-align: middle;
}
</style>
<div class="table">
<header>
<h1>Title</h1>
<p>subTitle</p>
</header>
<main>
<p>Collection</p>
<p>Version</p>
<p>Id</p>
</main>
<footer>
<p>Edition</p>
</footer>'>
</object>
_x000D_
But keeping your Iframe idea, You could also load your HTML inside your iframe tag and set it as the srcdoc value.You should not have to mind about quotes nor turning it into a dataUri but only mind to fire onload once.
The HTML Inline Frame element (
<iframe>
) represents a nested browsing context, embedding another HTML page into the current one.
Both iframe below will render the same, one require extra javascript.
example loading a full document :
body {
display: flex;
min-height: 25em;
}
p {
margin: auto;
}
iframe {
margin: 0 auto;
min-height: 100%;
background:lightgray;
}
_x000D_
<p>here my uploaded contents =>:</p>
<iframe srcdoc='<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
html, body {
height: 100%;
margin:0;
}
body.table {
display: table;
text-align:center;
width:100%;
}
.table > * {
display: table-row;
}
.table > main {
display: table-cell;
height: 100%;
vertical-align: middle;
}
</style>
</head>
<body class="table">
<header>
<h1>title</h1>
<p>injected via <code>srcdoc</code></p>
</header>
<main>
<p>Collection</p>
<p>Version</p>
<p>Id</p>
</main>
<footer>
<p>Edition</p>
</footer>
</body>
</html>'>
</iframe>
<iframe onload="this.setAttribute('srcdoc', this.innerHTML);this.setAttribute('onload','')">
<!-- below html loaded -->
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style>
html,
body {
height: 100%;
margin: 0;
overflow:auto;
}
body.table {
display: table;
text-align: center;
width: 100%;
}
.table>* {
display: table-row;
}
.table>main {
display: table-cell;
height: 100%;
vertical-align: middle;
}
</style>
</head>
<body class="table">
<header>
<h1>Title</h1>
<p>Injected from <code>innerHTML</code></p>
</header>
<main>
<p>Collection</p>
<p>Version</p>
<p>Id</p>
</main>
<footer>
<p>Edition</p>
</footer>
</body>
</html>
</iframe>
_x000D_
You can't, you'll have to do something like
<script type="text/javascript">
var php_var = "<?php echo $php_var; ?>";
</script>
You can also load it with AJAX
rhino is right, the snippet lacks of a type for the sake of brevity.
Also, note that if $php_var
has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.
You can execute all the commands returned by the following query :
select 'ALTER TABLE '||substr(c.table_name,1,35)|| ' DISABLE CONSTRAINT '||constraint_name||' ;' from user_constraints c --where c.table_name = 'TABLE_NAME' ;
You can also use a text editor:
Try this in config.js
CKEDITOR.editorConfig = function( config )
{
config.enterMode = CKEDITOR.ENTER_BR;
config.shiftEnterMode = CKEDITOR.ENTER_BR;
};
Here are the all keycodes.
Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.
http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php
Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.
Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12
./gradlew clean
Uses your project's gradle wrapper to execute your project's clean
task. Usually, this just means the deletion of the build directory.
./gradlew clean assembleDebug
Again, uses your project's gradle wrapper to execute the clean
and assembleDebug
tasks, respectively. So, it will clean first, then execute assembleDebug
, after any non-up-to-date dependent tasks.
./gradlew clean :assembleDebug
Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.
Android Studio --> Build --> Clean
Is essentially the same as ./gradlew clean
. See here.
For more info, I suggest taking the time to read through the Android docs, especially this one.
Easiest Way To install PDT
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
record = int(input("Enter the student record need to add :"))
stud_data={}
for i in range(0,record):
Name = input("Enter the student name :").split()
Age = input("Enter the {} age :".format(Name))
Grade = input("Enter the {} grade :".format(Name)).split()
Nam_key = Name[0]
Age_value = Age[0]
Grade_value = Grade[0]
stud_data[Nam_key] = {Age_value,Grade_value}
print(stud_data)
Based on the official documentation:
dummies = pd.get_dummies(df['Category']).rename(columns=lambda x: 'Category_' + str(x))
df = pd.concat([df, dummies], axis=1)
df = df.drop(['Category'], inplace=True, axis=1)
There is also a nice post in the FastML blog.
The best way is to use:
$("#yourid option:selected").text();
Depending on the requirement, you could also use this way:
var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()
Use CDATA
tags:
<![CDATA[
This is some text with ampersands & other funny characters. >>
]]>
Here is how I do it by using HashSet
HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
String[] arr =
{
"Pluto",
"Earth",
"Neptune",
"Jupiter",
"Saturn",
"Mercury",
"Pluto",
"Earth",
"Neptune",
"Jupiter",
"Saturn",
"Mercury",
// etc.
};
ICollection<String> coll = arr;
String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();
HashSet is basically almost to O(1) so your complexity remains O(n).
The simplest method (inline, assuming a
and b
are two given arrays):
byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);
This, of course, works with more than two summands and uses a concatenation charset, defined somewhere in your code:
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;
Or, in more simple form, without this charset:
byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");
But you need to suppress UnsupportedEncodingException
which is unlikely to be thrown.
The fastest method:
public static byte[] concat(byte[] a, byte[] b) {
int lenA = a.length;
int lenB = b.length;
byte[] c = Arrays.copyOf(a, lenA + lenB);
System.arraycopy(b, 0, c, lenA, lenB);
return c;
}
Note that the function will ONLY work on STRING objects.
For instance, I was consuming a plugin, and was confused why I was getting a "extension.tolowercase is not a function" JS error.
onChange: function(file, extension)
{
alert("extension.toLowerCase()=>" + extension.toLowerCase() + "<=");
Which produced the error "extension.toLowerCase is not a function" So I tried this piece of code, which revealed the problem!
alert("(typeof extension)=>" + (typeof extension) + "<=");;
The output was"(typeof extension)=>object<=" - so AhHa, I was NOT getting a string var for my input. The fix is straight forward though - just force the darn thing into a String!:
var extension = String(extension);
After the cast, the extension.toLowerCase() function worked fine.
you can use bing maps soap services, where you can reference reverse geocode service to find lat/long from address here is the link http://msdn.microsoft.com/en-us/library/cc980922.aspx
You can annotate your bean with jaxb annotations.
@XmlRootElement
public class MyJaxbBean {
public String name;
public int age;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String name, int age) {
this.name = name;
this.age = age;
}
}
and then your method would look like this:
@GET @Produces("application/json")
public MyJaxbBean getMyBean() {
return new MyJaxbBean("Agamemnon", 32);
}
There is a chapter in the latest documentation that deals with this:
https://jersey.java.net/documentation/latest/user-guide.html#json
UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.
"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:
String text = "N/A";
int intVal = 0;
try {
intVal = Integer.parseInt(text);
} catch (NumberFormatException e) {
//Log it if needed
intVal = //default fallback value;
}
Like SplinterReality said: There's no reason not to use Dijkstra's algorithm here.
The code below I nicked from here and modified it to solve the example in the question.
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) { name = argName; }
public String toString() { return name; }
public int compareTo(Vertex other)
{
return Double.compare(minDistance, other.minDistance);
}
}
class Edge
{
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight)
{ target = argTarget; weight = argWeight; }
}
public class Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target)
{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args)
{
// mark all the vertices
Vertex A = new Vertex("A");
Vertex B = new Vertex("B");
Vertex D = new Vertex("D");
Vertex F = new Vertex("F");
Vertex K = new Vertex("K");
Vertex J = new Vertex("J");
Vertex M = new Vertex("M");
Vertex O = new Vertex("O");
Vertex P = new Vertex("P");
Vertex R = new Vertex("R");
Vertex Z = new Vertex("Z");
// set the edges and weight
A.adjacencies = new Edge[]{ new Edge(M, 8) };
B.adjacencies = new Edge[]{ new Edge(D, 11) };
D.adjacencies = new Edge[]{ new Edge(B, 11) };
F.adjacencies = new Edge[]{ new Edge(K, 23) };
K.adjacencies = new Edge[]{ new Edge(O, 40) };
J.adjacencies = new Edge[]{ new Edge(K, 25) };
M.adjacencies = new Edge[]{ new Edge(R, 8) };
O.adjacencies = new Edge[]{ new Edge(K, 40) };
P.adjacencies = new Edge[]{ new Edge(Z, 18) };
R.adjacencies = new Edge[]{ new Edge(P, 15) };
Z.adjacencies = new Edge[]{ new Edge(P, 18) };
computePaths(A); // run Dijkstra
System.out.println("Distance to " + Z + ": " + Z.minDistance);
List<Vertex> path = getShortestPathTo(Z);
System.out.println("Path: " + path);
}
}
The code above produces:
Distance to Z: 49.0
Path: [A, M, R, P, Z]
There's a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows http://idlex.sourceforge.net/
It includes line numbering and I find it quite handy & free.
Otherwise there are a bunch of other IDEs some of which are free: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
The way I use is:
git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master
There is a std::swap
in <algorithm>
I had to use Debug.print
instead of Print
, which works in the Immediate window.
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objHTTP = New MSXML2.XMLHTTP60
'Dim objHTTP As New MSXML2.XMLHTTP60
Dim objHTTP As New WinHttp.WinHttpRequest
'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
End Sub
This is about using the join function to save a multi-value parameter and then restoring the exact same selections from the database later.
I just finished a report that had requirements that the parameters must be saved, and when the report is opened again (the report is passed an OrderID paramater), the values previously chosen by the user must be once again selected.
The report used a half of dozen parameters, each one had its own data set and resulting drop down list. The parameters were dependent upon the previous parameters to narrow the scope of the final selection, and when the report was "viewed" a stored procedure was called to populate.
The stored procedure received each of the parameters passed to it from the report. It checked a storage table in the database to see if any parameters were saved for that OrderID. If not, then it saved all the parameters. If so, it updated all of the parameters for that order (this is the case where the user changes their mind later).
When the report runs, there is a dataset dsParameters which is SQL text that goes out and selects the single row for that orderID if there is one. Each of the parameters in the report gets its default value from this dataset, and its selection list from a dataset dedicated to that parameter.
I ran into trouble with the multi-select parameter. I used a join(@Value,",") command in the main dataset parameter list, passing to the stored procedure a comma delimited string. But how to restore it? You can't feed the comma delimited string back to the default values box of the parameter.
IF OBJECT_ID('tempdb..#Parse','U') IS NOT NULL DROP TABLE #Parse
DECLARE @Start int, @End int, @Desc varchar(255)
SELECT @Desc = fldDesc FROM dbCustomData.dbo.tblDirectReferralFormParameters WHERE fldFrom = @From and fldOrderID = @OrderID
CREATE TABLE #Parse (fldDesc varchar(255))
SELECT @Start = 1, @End = 1
WHILE @End > 0
BEGIN
SET @End = CHARINDEX(',',@Desc,@Start)
IF @End = 0
BEGIN
INSERT #Parse SELECT REPLACE(SUBSTRING(@Desc,@Start,LEN(@Desc)),',','') AS fldDesc
BREAK
END
ELSE
BEGIN
INSERT #Parse SELECT REPLACE(SUBSTRING(@Desc,@Start,@End-@Start),',','') AS fldDesc
END
SET @Start = @End + 1
END
SELECT * FROM #Parse
Every time the form opens, this dataset checks the database for a saved string for this multi-valued parameter. If there is not one, it returns null. If there is on, it parses out the commas and creates a row for each of the values.
Then the default values box is set to this dataset, and fldDesc. It works! When I choose one or many, they save and replenish when the form is opened again.
I hope this helps. I searched for a while and did not find any mention of saving the join string in a database and then parsing it out in a dataset.
Am adding few things related to jenkins configuration files storage.
As per my understanding all config file stores in the machine or OS that you have installed jenkins.
The jobs you are going to create in jenkins will be stored in jenkins server and you can find the config.xml etc., here.
After jenkins installation you will find jenkins workspace in server.
*cd>jenkins/jobs/`
cd>jenkins/jobs/$ls
job1 job2 job3 config.xml ....*
just in case someone looks for this, the path to the file on Sourav answer (httpd.conf) in linux is /opt/lampp/etc/httpd.conf
You can check the called
attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest
, you can check the contents of call_args_list
instead:
self.assertItemsEqual(my_var.call_args_list, [])
When it fails, it gives a message like this:
AssertionError: Element counts were not equal: First has 0, Second has 1: call('first argument', 4)
In Angular material label with checkbox
<mat-checkbox>Check me!</mat-checkbox>
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Check this:
let cloned = source.map(x => Object.assign({}, x));
What @deceze said is correct, it seems that your JSON is malformed, try this:
{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
}]
}
Use json_decode
to convert String into Object (stdClass
) or array: http://php.net/manual/en/function.json-decode.php
[edited]
I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?
assuming you have the following variable:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
You should convert it to Object (stdClass):
$manage = json_decode($data);
But working with stdClass
is more complicated than PHP-Array, then try this (use second param with true
):
$manage = json_decode($data, true);
This way you can use array functions: http://php.net/manual/en/function.array.php
adding an item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
echo '<br>After: <br>';
print_r($manage);
remove first item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);
any chance you want to save to json to a database or a file:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
$manage = json_decode($data, true);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
if (($id = fopen('datafile.txt', 'wb'))) {
fwrite($id, json_encode($manage));
fclose($id);
}
I hope I have understood your question.
Good luck.
You can use JavaScript functions like replace, and you can wrap the jQuery code in brackets:
var value = ($("#text").val()).replace(".", ":");
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
to merely set typeface of app to normal
, sans
, serif
or monospace
(not to a custom font!), you can do this.
define a theme and set the android:typeface
attribute to the typeface you want to use in styles.xml
:
<resources>
<!-- custom normal activity theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- other elements -->
<item name="android:typeface">monospace</item>
</style>
</resources>
apply the theme to the whole app in the AndroidManifest.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application
android:theme="@style/AppTheme" >
</application>
</manifest>
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
This question has already been marked answered, but I'd like to share some information that might help others with using FileList.
It would be convenient to treat a FileList as an array, but methods like sort, shift, pop, and slice don't work. As others have suggested, you can copy the FileList to an array. However, rather than using a loop, there's a simple one line solution to handle this conversion.
// fileDialog.files is a FileList
var fileBuffer=[];
// append the file list to an array
Array.prototype.push.apply( fileBuffer, fileDialog.files ); // <-- here
// And now you may manipulated the result as required
// shift an item off the array
var file = fileBuffer.shift(0,1); // <-- works as expected
console.info( file.name + ", " + file.size + ", " + file.type );
// sort files by size
fileBuffer.sort(function(a,b) {
return a.size > b.size ? 1 : a.size < b.size ? -1 : 0;
});
Tested OK in FF, Chrome, and IE10+
Angular 6.1 and later:
Angular 6.1 (released on 2018-07-25) added built-in support to handle this issue, through a feature called "Router Scroll Position Restoration". As described in the official Angular blog, you just need to enable this in the router configuration like this:
RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})
Furthermore, the blog states "It is expected that this will become the default in a future major release". So far this hasn't happened (as of Angular 11.0), but eventually you won't need to do anything at all in your code, and this will just work correctly out of the box.
You can see more details about this feature and how to customize this behavior in the official docs.
Angular 6.0 and earlier:
While @GuilhermeMeireles's excellent answer fixes the original problem, it introduces a new one, by breaking the normal behavior you expect when you navigate back or forward (with browser buttons or via Location in code). The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page obviously breaks this expectation.
The code below expands the logic to detect this kind of navigation by subscribing to Location's PopStateEvent sequence and skipping the scroll-to-top logic if the newly arrived-at page is a result of such an event.
If the page you navigate back from is long enough to cover the whole viewport, the scroll position is restored automatically, but as @JordanNelson correctly pointed out, if the page is shorter you need to keep track of the original y scroll position and restored it explicitly when you go back to the page. The updated version of the code covers this case too, by always explicitly restoring the scroll position.
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
private lastPoppedUrl: string;
private yScrollStack: number[] = [];
constructor(private router: Router, private location: Location) { }
ngOnInit() {
this.location.subscribe((ev:PopStateEvent) => {
this.lastPoppedUrl = ev.url;
});
this.router.events.subscribe((ev:any) => {
if (ev instanceof NavigationStart) {
if (ev.url != this.lastPoppedUrl)
this.yScrollStack.push(window.scrollY);
} else if (ev instanceof NavigationEnd) {
if (ev.url == this.lastPoppedUrl) {
this.lastPoppedUrl = undefined;
window.scrollTo(0, this.yScrollStack.pop());
} else
window.scrollTo(0, 0);
}
});
}
}
Try
var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);
you can use any of the following five ways to hide element, depends upon your requirements.
.hide {
opacity: 0;
}
.hide {
visibility: hidden;
}
.hide {
display: none;
}
.hide {
position: absolute;
top: -9999px;
left: -9999px;
}
.hide {
clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}
To show use any of the following: opacity: 1; visibility: visible; display: block;
Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/
Instead of any Array
you can load your data in DataTable
like:
using System.Data;
DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
using (var command = new SqlCommand("SELECT col1,col2" +
{
con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
dt.Load(dr);
}
}
}
You can also use SqlDataAdapater
to fill your DataTable like
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
Later you can iterate each row and compare like:
foreach (DataRow dr in dt.Rows)
{
if (dr.Field<string>("col1") == "yourvalue") //your condition
{
}
}
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
Try this
find . -type f -name some_file_name.xml -exec grep -H PUT_YOUR_STRING_HERE {} \;
For anyone returning to this question. The correct "Angular Way" to remove items from an array is with $filter. Just inject $filter into your controller and do the following:
$scope.items = $filter('filter')($scope.items, {name: '!ted'})
You don't need to load any additional libraries or resort to Javascript primitives.
The obvious thing to do is read the documentation.
But to help: substr($str, $start, $end);
$str
is your text
$start
is the character index to begin at. In your case, it is likely 0 which means the very beginning.
$end
is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:
<?php
$text = "long text that should be truncated";
echo substr($text, 0, 15);
?>
and you would get this:
long text that
makes sense?
EDIT
The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:
function truncate($text, $chars = 25) {
if (strlen($text) <= $chars) {
return $text;
}
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}
So in your case you would paste this function into the functions.php file and call it like this in your page:
$post = the_post();
echo truncate($post, 100);
This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
At least in Visual Studio Ultimate 2013, Version 12.0.30723.00 Update 3, it's not possible to separate an if/else statement with a line break:
works:
if '$(BuildingInsideVisualStudio)' == 'true' (echo local) else (echo server)
doesn't work:
if '$(BuildingInsideVisualStudio)' == 'true' (echo local)
else (echo server)
If you check Dockerfile from containers, for example fballiano/magento2-apache-php
you'll see that at the end of his file he adds the following command: while true; do sleep 1; done
Now, what I recommend, is that you do this
docker container ls --all | grep 127
Then, you will see if your docker image had an error, if it exits with 0, then it probably needs one of these commands that will sleep forever.
JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.
jsonCallback(
{
"sites":
[
{
"siteName": "JQUERY4U",
"domainName": "http://www.jquery4u.com",
"description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
},
{
"siteName": "BLOGOOLA",
"domainName": "http://www.blogoola.com",
"description": "Expose your blog to millions and increase your audience."
},
{
"siteName": "PHPSCRIPTS4U",
"domainName": "http://www.phpscripts4u.com",
"description": "The Blog of Enthusiastic PHP Scripters"
}
]
});
(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.
The set
statement doesn't treat spaces the way you expect; your variable is really named Pathname[space]
and is equal to [space]C:\Program Files
.
Remove the spaces from both sides of the =
sign, and put the value in double quotes:
set Pathname="C:\Program Files"
Also, if your command prompt is not open to C:\, then using cd
alone can't change drives.
Use
cd /d %Pathname%
or
pushd %Pathname%
instead.
Trying to JOIN in MongoDB would defeat the purpose of using MongoDB. You could, however, use a DBref and write your application-level code (or library) so that it automatically fetches these references for you.
Or you could alter your schema and use embedded documents.
Your final choice is to leave things exactly the way they are now and do two queries.
As mentioned in this post, just use generator expressions like so:
numpy.fromiter((<some_func>(x) for x in <something>),<dtype>,<size of something>)
instead of using dataframe.to_json(orient = “records”)
use dataframe.to_json(orient = “index”)
my above code convert the dataframe into json format of dict like {index -> {column -> value}}
I had the same error message so I went googling a bit I managed to fix it with the following code.
df<-data.frame(words = unlist(words))
words is a character list.
This just in case somebody else needs the output to be a data frame.
For Jetbrains IDE Users who migrated to VSCode , no problem.
Install:
1) JetBrains IDE Keymap: Extension
2) vscode-intellij-idea-keybindings Extension (Preferred)
Use this Intellij Darcula Theme
: Extension
The keymap has covered most of keyboard shortcuts of VS Code, and makes VS Code more 'JetBrains IDE like'.
Above extensions imports keybindings from JetBrains to VS Code. After installing the extension and restarting VS Code you can use VS Code just like IntelliJ IDEA, Webstorm, PyCharm, etc.
You can use the following code to hide a table column..
JQuery("tableName").hideCol("colName");
And you can use the following code to show it again.
JQuery("tableName").showCol("colName");
For your question, you can call the hideCol() code on the document.ready(), and you can bind the showCol() code on the dialog's edit/click event.
The fastest way to check if a string contains another string is using indexOf
:
if (code.indexOf('ST1') !== -1) {
// string code has "ST1" in it
} else {
// string code does not have "ST1" in it
}
You likely want urllib2. It can handle things like HTTPS, cookies, and authentication. You will probably also want BeautifulSoup to help parse the HTML pages.
Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.
Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)
server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst
3. If you want to make sure that date and time update at startup run this python script in rpi,
import os
try:
client = ntplib.NTPClient()
response = client.request('xxx.xxx.xxx.xxx', version=4)
print "===================================="
print "Offset : "+str(response.offset)
print "Version : "+str(response.version)
print "Date Time : "+str(ctime(response.tx_time))
print "Leap : "+str(ntplib.leap_to_text(response.leap))
print "Root Delay : "+str(response.root_delay)
print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
print "===================================="
except:
os.system("sudo date")
print "NTP Server Down Date Time NOT Set At The Startup"
pass
I found more info in raspberry pi forum.
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
_x000D_
If you want to get the ASCII value of a character, or just convert it into an int, you need to cast from a char to an int.
What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.
public class char_to_int
{
public static void main(String args[])
{
char myChar = 'a';
int i = (int) myChar; // cast from a char to an int
System.out.println ("ASCII value - " + i);
}
In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.
I set the PHPRC variable and uncommented zend_extension=php_opcache.dll
in php.ini
and all works well.
Another option is to set height: 0; overflow: visible;
to an element, though it won't be really outside the flow and therefore may break margin collapsing.
Another solution, very light with high performance with payload large:
Android Asynchronous Http Client library: http://loopj.com/android-async-http/
private static AsyncHttpClient client = new AsyncHttpClient();
private void uploadFileExecute(File file) {
RequestParams params = new RequestParams();
try { params.put("photo", file); } catch (FileNotFoundException e) {}
client.post(getUrl(), params,
new AsyncHttpResponseHandler() {
public void onSuccess(String result) {
Log.d(TAG,"uploadFile response: "+result);
};
public void onFailure(Throwable arg0, String errorMsg) {
Log.d(TAG,"uploadFile ERROR!");
};
}
);
}
I'm using 2d cross product in my calculation to find the new correct rotation for an object that is being acted on by a force vector at an arbitrary point relative to its center of mass. (The scalar Z one.)
String[][] shades = new String[intSize][intSize];
// print array in rectangular form
for (int r=0; r<shades.length; r++) {
for (int c=0; c<shades[r].length; c++) {
shades[r][c]="hello";//your value
}
}
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
Real programmers do it with semaphores.
Have a variable set to 0
. Increment it before each AJAX call. Decrement it in each success handler, and test for 0
. If it is, you're done.
Makefile part of the question
This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)
SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...
main.exe: $(OBJ_FILES)
g++ $(LDFLAGS) -o $@ $^
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
Automatic dependency graph generation
A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD
flag to CXXFLAGS
and -include $(OBJ_FILES:.o=.d)
to the end of the makefile body:
CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)
And as guys mentioned already, always have GNU Make Manual around, it is very helpful.
I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.
When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?
In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.
So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.
And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.
GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.
One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.
git diff > git-dif-file.diff
The easiest JavaScript way that I found to get the thumbnail, without searching for the video id is using:
//Get the video thumbnail via Ajax
$.ajax({
type:'GET',
url: 'https://vimeo.com/api/oembed.json?url=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
console.log(data.thumbnail_url);
}
});
Note: If someone need to get the video thumbnail related to the video id he can replace the $id
with the video id and get an XML with the video details:
http://vimeo.com/api/v2/video/$id.xml
Example:
http://vimeo.com/api/v2/video/198340486.xml
I solved it by global searching the missing directory in the project. then delete any files containing that keyword. it can clean successfully after I remove all the build
and .externalNativeBuild
directories manually.
For Ubuntu and running android-studio run to install the packages (these are not installed by default):
android update sdk
you should you use following code
$configValue = Mage::getStoreConfig(
'sectionName/groupName/fieldName',
Mage::app()->getStore()
);
Mage::app()->getStore()
this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.
if we have more then one store or multiple views configured then this will insure that we are getting values for current store
Use the hex code for a non-breaking space. Something like this:
.breadcrumbs a:before {
content: '>\00a0';
}
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
If you want "physical" access, we're developing this API that will eventually allows you to communicate with storage devices. It's open source and you can see the current code for some information. Check back for more features: https://github.com/virtium/vtStor
Right click on your my computer icon and the CPU will be listed on the properties page. Or open device manager and look at the CPU.
It must be an Intel processor that supports VT and NX bit (XD) - you can check your CPU # at http://ark.intel.com
Also make sure hyperV off bcdedit /set hypervisorlaunchtype off
XD bit is on bcdedit /set nx AlwaysOn
Use the installer from https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager
If you're using Avast, disable "Enable hardware-assisted virtualization" under: Settings > Troubleshooting. Restart the PC and try to run the HAXM installation again
This should get your sorted:
Ctrl + H
to bring up the 'Find and Replace' window.\r\n
Here's how it should look:
If you want the margin-left
to work on a span
element you'll need to make it display: inline-block
or display:block
as well.
My first post... UDF I managed quickly to compile. Usage: Select 3D range as normal and enclose is into quotation marks like below...
=CountIf3D("'StartSheet:EndSheet'!G16:G878";"Criteria")
Advisably sheets to be adjacent to avoid unanticipated results.
Public Function CountIf3D(SheetstoCount As String, CriteriaToUse As Variant)
Dim sStarSheet As String, sEndSheet As String, sAddress As String
Dim lColonPos As Long, lExclaPos As Long, cnt As Long
lColonPos = InStr(SheetstoCount, ":") 'Finding ':' separating sheets
lExclaPos = InStr(SheetstoCount, "!") 'Finding '!' separating address from the sheets
sStarSheet = Mid(SheetstoCount, 2, lColonPos - 2) 'Getting first sheet's name
sEndSheet = Mid(SheetstoCount, lColonPos + 1, lExclaPos - lColonPos - 2) 'Getting last sheet's name
sAddress = Mid(SheetstoCount, lExclaPos + 1, Len(SheetstoCount) - lExclaPos) 'Getting address
cnt = 0
For i = Sheets(sStarSheet).Index To Sheets(sEndSheet).Index
cnt = cnt + Application.CountIf(Sheets(i).Range(sAddress), CriteriaToUse)
Next
CountIf3D = cnt
End Function
Try this:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
android:id="@+id/tool_drawer"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
toolbar:navigationIcon="@drawable/ic_navigation">
</android.support.v7.widget.Toolbar>
I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing }
character. What's the length of result1
versus result2
? I'll note that result2
as you've quoted it has 169 characters.
GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t
, \n
, \r
, and space count as whitespace. In particular, note that trailing NUL (\0
) characters do not count as whitespace and will cause this error.
If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);
One additional reason to add final to parameter declarations is that it helps to identify variables that need to be renamed as part of a "Extract Method" refactoring. I have found that adding final to each parameter prior to starting a large method refactoring quickly tells me if there are any issues I need to address before continuing.
However, I generally remove them as superfluous at the end of the refactoring.
since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of
"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()
In my answer,I have stored the plot in mygraph variable and then I have used
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
And the work is done. Below is the complete answer.
install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)
ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) +
scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
plot.title = element_text(color="Blue", size=30, hjust = 0.5),
# change the styling of both the axis simultaneously from this-
axis.title = element_text(color = "Green", size = 20, family="Courier",)
# you can change the axis title from the code below
mygraph$labels$x="Discharge of materials" #changes x axis title
mygraph$labels$y="Area Affected" # changes y axis title
mygraph
Also, you can change the labels title from the same formula used above -
mygraph$labels$size= "N2" #size contains the nitrogen level
Here is something I learnt after a long time of having issues with pip when I had several versions of Python installed (valid especially for OS X users which are probably using brew to install python blends.)
I assume that most python developers do have at the beginning of their scripts:
#!/bin/env python
You may be surprised to find out that this is not necessarily the same python as the one you run from the command line >python
To be sure you install the package using the correct pip instance for your python interpreter you need to run something like:
>/bin/env python -m pip install --upgrade mymodule
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex
which you can set to limit the number of files. For example:
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.
In addition to Jon Skeet's answer, I'd like to explain why most of the time when using ==
you actually get the answer true
on different string instances with the same value:
string a = "Hell";
string b = "Hello";
a = a + "o";
Console.WriteLine(a == b);
As you can see, a
and b
must be different string instances, but because strings are immutable, the runtime uses so called string interning to let both a
and b
reference the same string in memory. The ==
operator for objects checks reference, and since both a
and b
reference the same instance, the result is true
. When you change either one of them, a new string instance is created, which is why string interning is possible.
By the way, Jon Skeet's answer is not complete. Indeed, x == y
is false
but that is only because he is comparing objects and objects compare by reference. If you'd write (string)x == (string)y
, it will return true
again. So strings have their ==-operator overloaded, which calls String.Equals
underneath.
if (someString.indexOf("Hey")>=0)
doSomething();
Adding the option insides Eclipse immediately resolves the issue. To add the option
open preferences via application menu Window => Preferences (or on OSX Eclipse => Settings). Navigate to Team => Git => Configuration click Add entry..., then put http.sslVerify in the key box and false in the value box.