Solution : 1.Project -> Build Path -> Configure Build Path
2.Select Java Build path on the left menu, and select "Source"
3.Under Project select Include(All) and click OK
Cause : The issue might because u might have deleted the CLASS files or dependencies on the project
MizardX's answer gives a good collection of multiple approaches.
This is what I came up with while thinking aloud:
mylist = [x for i,x in enumerate(mylist) if x not in mylist[i+1:]]
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
In Python-style regex, \d
matches any individual digit. If you're seeing something that doesn't seem to do that, please provide the full regex you're using, as opposed to just describing that one particular symbol.
>>> import re
>>> re.match(r'\d', '3')
<_sre.SRE_Match object at 0x02155B80>
>>> re.match(r'\d', '2')
<_sre.SRE_Match object at 0x02155BB8>
>>> re.match(r'\d', '1')
<_sre.SRE_Match object at 0x02155B80>
You can stash
and stash pop
the file:
git checkout branch1
git checkout branch2 file.py
git stash
git checkout branch1
git stash pop
This is very simple. Here is the code.
[yourLabel setFont:[UIFont boldSystemFontOfSize:15.0];
This will help you.
Try this:
WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)
For 2 use cases:
grep -m 2
is per file max occurrence. git grep
which doesn't take -m
A good alternative in these scenarios is grep | sed 2q
to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html
There are many ways to update the rows.
When it comes to UPDATE
the rows using subqueries, you can use any of these approaches.
UPDATE
<table1>
SET
customer=<table2>.customer,
address=<table2>.address,
partn=<table2>.partn
FROM
<table2>
WHERE
<table1>.address_id=<table2>.address_i;
Explanation:
table1
is the table which we want to update,table2
is the table, from which we'll get the value to be replaced/updated. We are usingFROM
clause, to fetch thetable2
's data.WHERE
clause will help to set the proper data mapping.
UPDATE
<table1>
SET
customer=subquery.customer,
address=subquery.address,
partn=subquery.partn
FROM
(
SELECT
address_id, customer, address, partn
FROM /* big hairy SQL */ ...
) AS subquery
WHERE
dummy.address_id=subquery.address_id;
Explanation: Here we are using subquerie inside the
FROM
clause, and giving an alias to it. So that it will act like the table.
UPDATE
<table1>
SET
customer=<table2>.customer,
address=<table2>.address,
partn=<table2>.partn
FROM
<table2> as t2
JOIN <table3> as t3
ON
t2.id = t3.id
WHERE
<table1>.address_id=<table2>.address_i;
Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the
FROM
clause.
Approach-4 [Using WITH statement]
WITH subquery AS (
SELECT
address_id,
customer,
address,
partn
FROM
<table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
WITH subquery AS (
SELECT address_id, customer, address, partn
FROM
<table1> as t1
JOIN
<table2> as t2
ON
t1.id = t2.id;
-- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
Explanation: From Postgres 9.1, this(
WITH
) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.
I hope, this would be helpful.
You're looking for:
animation-fill-mode: forwards;
More info on MDN and browser support list on canIuse.
There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.
I would suggest something like this:
int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
printf( "%d", my_array[index][jdex] );
printf( "\n" );
}
}
The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.
First type
nvidia-smi
then select the PID that you want to kill
sudo kill -9 PID
I think using the native URL API is better than a complex regex patterns as @pavlo suggested. It has some drawbacks though which we can fix by some extra code. This approach fails for the following valid url.
//cdn.google.com/script.js
We can add the missing protocol beforehand to avoid that. It also fails to detect following invalid url.
http://w
http://..
So why check the whole url? we can just check the domain. I borrowed the regex to verify domain from here.
function isValidUrl(string) {
if (string && string.length > 1 && string.slice(0, 2) == '//') {
string = 'http:' + string; //dummy protocol so that URL works
}
try {
var url = new URL(string);
return url.hostname && url.hostname.match(/^([a-z0-9])(([a-z0-9-]{1,61})?[a-z0-9]{1})?(\.[a-z0-9](([a-z0-9-]{1,61})?[a-z0-9]{1})?)?(\.[a-zA-Z]{2,4})+$/) ? true : false;
} catch (_) {
return false;
}
}
The hostname
attribute is empty string for javascript:void(0)
, so it works for that too, and you can also add IP address verifier too. I'd like to stick to native API's most, and hope it starts to support everything in near future.
Another thing you can do is cat
out what you are echoing and pipe with inline cut -c 1-1
Here are tests for a few methods:
%timeit np.where(np.isnan(df['b']))[0]
%timeit pd.isnull(df['b']).nonzero()[0]
%timeit np.where(df['b'].isna())[0]
%timeit df.loc[pd.isna(df['b']), :].index
And their corresponding timings:
333 µs ± 9.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
280 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
313 µs ± 128 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
6.84 ms ± 1.59 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
It would appear that pd.isnull(df['DRGWeight']).nonzero()[0]
wins the day in terms of timing, but that any of the top three methods have comparable performance.
I will use collection.save(the_changed_dict)
this way. I've just tested this, and it still works for me. The following is quoted directly from pymongo doc.
:
save(to_save[, manipulate=True[, safe=False[, **kwargs]]])
Save a document in this collection.
If to_save already has an "_id" then an update() (upsert) operation is performed and any existing document with that "_id" is overwritten. Otherwise an insert() operation is performed. In this case if manipulate is True an "_id" will be added to to_save and this method returns the "_id" of the saved document. If manipulate is False the "_id" will be added by the server but this method will return None.
This is possible if you have an existing Newline character in the row or another row.
Select the square-box that represents the existing Newline character, copy it (control-C), and then paste it (control-V) where you want it to be.
This is slightly cheesy, but I actually did get it to work in SSMS 2008 and I was not able to get any of the other suggestions (control-enter, alt-13, or any alt-##) to work.
You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.py
file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.
My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.
For numerical data you have the solution. But it is categorical data, you said. Then life gets a bit more complicated...
Well, first : The amount of association between two categorical variables is not measured with a Spearman rank correlation, but with a Chi-square test for example. Which is logic actually. Ranking means there is some order in your data. Now tell me which is larger, yellow or red? I know, sometimes R does perform a spearman rank correlation on categorical data. If I code yellow 1 and red 2, R would consider red larger than yellow.
So, forget about Spearman for categorical data. I'll demonstrate the chisq-test and how to choose columns using combn(). But you would benefit from a bit more time with Agresti's book : http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937
set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)
table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction
#Let's make a matrix with tons of columns
Data <- as.data.frame(
matrix(
sample(letters[1:3],2000,replace=T),
ncol=25
)
)
# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]
# say you need to know which ones are associated with each other.
out <- apply( combn(columns,2),2,function(x){
chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
})
out <- cbind(as.data.frame(t(combn(vars,2))),out)
Then you should get :
> out
V1 V2 out
1 V3 V7 0.8116733
2 V3 V11 0.1096903
3 V3 V24 0.1653670
4 V7 V11 0.3629871
5 V7 V24 0.4947797
6 V11 V24 0.7259321
Where V1 and V2 indicate between which variables it goes, and "out" gives the p-value for association. Here all variables are independent. Which you would expect, as I created the data at random.
Old question which has an accepted answer already, but I like to think of these two isolation levels in terms of how they change the locking behavior in SQL Server. This might be helpful for those who are debugging deadlocks like I was.
READ COMMITTED (default)
Shared locks are taken in the SELECT and then released when the SELECT statement completes. This is how the system can guarantee that there are no dirty reads of uncommitted data. Other transactions can still change the underlying rows after your SELECT completes and before your transaction completes.
REPEATABLE READ
Shared locks are taken in the SELECT and then released only after the transaction completes. This is how the system can guarantee that the values you read will not change during the transaction (because they remain locked until the transaction finishes).
Going to answer this myself (correct me if I'm wrong):
It is not possible to iterate over a group of rows (like an array) in Excel without VBA installed / macros enabled.
So there should be four choices to do so:
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid()
function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
Or you can access root terminal by typing sudo -s
On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words
\bmyWord\b
\<myWord\>
Hear me now and believe me later, this ugly syntax is what you need to use:
/[[:<:]]myWord[[:>:]]/
So, for example, to replace mint with minty for whole words only:
sed "s/[[:<:]]mint[[:>:]]/minty/g"
Source: re_format man page
Just thought i would share a solution also based on this that works with the Knowntype attribute using reflection , had to get derived class from any base class, solution can benefit from recursion to find the best matching class though i didn't need it in my case, matching is done by the type given to the converter if it has KnownTypes it will scan them all until it matches a type that has all the properties inside the json string, first one to match will be chosen.
usage is as simple as:
string json = "{ Name:\"Something\", LastName:\"Otherthing\" }";
var ret = JsonConvert.DeserializeObject<A>(json, new KnownTypeConverter());
in the above case ret will be of type B.
JSON classes:
[KnownType(typeof(B))]
public class A
{
public string Name { get; set; }
}
public class B : A
{
public string LastName { get; set; }
}
Converter code:
/// <summary>
/// Use KnownType Attribute to match a divierd class based on the class given to the serilaizer
/// Selected class will be the first class to match all properties in the json object.
/// </summary>
public class KnownTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return System.Attribute.GetCustomAttributes(objectType).Any(v => v is KnownTypeAttribute);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(objectType); // Reflection.
// Displaying output.
foreach (System.Attribute attr in attrs)
{
if (attr is KnownTypeAttribute)
{
KnownTypeAttribute k = (KnownTypeAttribute) attr;
var props = k.Type.GetProperties();
bool found = true;
foreach (var f in jObject)
{
if (!props.Any(z => z.Name == f.Key))
{
found = false;
break;
}
}
if (found)
{
var target = Activator.CreateInstance(k.Type);
serializer.Populate(jObject.CreateReader(),target);
return target;
}
}
}
throw new ObjectNotFoundException();
// Populate the object properties
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
while(dr.read())
{
returnPersonList.add(
new Person(dr.GetInt32(1), dr.GetInt32(0), dr.GetString(2)));
}
where:
public class Person
{
public Person(int age, int id, string name)
{
Age = age;
Id = id;
Name = name;
}
}
The accepted answer is incorrect.
createNativeQuery
will always return a Query
:
public Query createNativeQuery(String sqlString, Class resultClass);
Calling getResultList
on a Query
returns List
:
List getResultList()
When assigning (or casting) to List<MyEntity>
, an unchecked assignment warning is produced.
Whereas, createQuery
will return a TypedQuery
:
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);
Calling getResultList
on a TypedQuery
returns List<X>
.
List<X> getResultList();
This is properly typed and will not give a warning.
With createNativeQuery
, using ObjectMapper
seems to be the only way to get rid of the warning. Personally, I choose to suppress the warning, as I see this as a deficiency in the library and not something I should have to worry about.
You should do it in the xaml code:
<DataGrid ItemsSource="{Binding list}" [...]>
[...]
</DataGrid>
I would advise you to use an ObservableCollection
as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged
.
I tested eAccelerator and XCache with Apache, Lighttp and Nginx with a Wordpress site. eAccelerator wins every time. The bad thing is only the missing packages for Debian and Ubuntu. After a PHP update often the server doesn't work anymore if the eAccelerator modules are not recompiled.
eAccelerator last RC is from 2009/07/15 (0.9.6 rc1) with support for PHP 5.3
Code for A Breadth First Search to make sure both nodes are in the tree. Only then move forward with the LCA search. Please comment if you have any suggestions to improve. I think we can probably mark them visited and restart the search at a certain point where we left off to improve for the second node (if it isn't found VISITED)
public class searchTree {
static boolean v1=false,v2=false;
public static boolean bfs(Treenode root, int value){
if(root==null){
return false;
}
Queue<Treenode> q1 = new LinkedList<Treenode>();
q1.add(root);
while(!q1.isEmpty())
{
Treenode temp = q1.peek();
if(temp!=null) {
q1.remove();
if (temp.value == value) return true;
if (temp.left != null) q1.add(temp.left);
if (temp.right != null) q1.add(temp.right);
}
}
return false;
}
public static Treenode lcaHelper(Treenode head, int x,int y){
if(head==null){
return null;
}
if(head.value == x || head.value ==y){
if (head.value == y){
v2 = true;
return head;
}
else {
v1 = true;
return head;
}
}
Treenode left = lcaHelper(head.left, x, y);
Treenode right = lcaHelper(head.right,x,y);
if(left!=null && right!=null){
return head;
}
return (left!=null) ? left:right;
}
public static int lca(Treenode head, int h1, int h2) {
v1 = bfs(head,h1);
v2 = bfs(head,h2);
if(v1 && v2){
Treenode lca = lcaHelper(head,h1,h2);
return lca.value;
}
return -1;
}
}
If the size of the circles corresponds to the square of the parameter in s=parameter
, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24]
such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.
If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]
. Try list interpretation: s=[numpy.sqrt(i) for i in s]
On top of the answers already given, to open a new tab the javascript command window.open()
can be used.
For example:
# Opens a new tab
self.driver.execute_script("window.open()")
# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])
# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here
You're then able to close the original tab as follows
# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
# Close original tab
self.driver.close()
# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])
Or close the newly opened tab
# Close current tab
self.driver.close()
# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])
Hope this helps.
Your problem is caused by the lack of markers OpenGraph, as you say it is not possible that you implement for some reason.
For you, the only solution is to use the PHP Facebook API.
When creating the application you will have two key data for your code:
YOUR_APP_ID
YOUR_APP_SECRET
Download the Facebook PHP SDK from here.
You can start with this code for share content from your site:
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
// Give the user a logout link
echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
</html>
You can find more examples in the Facebook Developers site:
For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.
Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.
Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.
Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).
I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.
this works
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(soapResponse.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
System.out.println(sw.toString());
return sw.toString();
That CSS property is all you need it works for me...When previewing in Chrome you have the option to see it BW and Color(Color: Options- Color or Black and white) so if you don't have that option, then I suggest to grab this Chrome extension and make your life easier:
The site you added on fiddle needs this in your media print css (you have it just need to add it...
media print CSS in the body:
@media print {
body {-webkit-print-color-adjust: exact;}
}
UPDATE OK so your issue is bootstrap.css...it has a media print css as well as you do....you remove that and that should give you color....you need to either do your own or stick with bootstraps print css.
When I click print on this I see color.... http://jsfiddle.net/rajkumart08/TbrtD/1/embedded/result/
you may try using trigger() Reference Link
$('#form_id').trigger("reset");
Write this in your ViewDidLoad Method:
if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
self.edgesForExtendedLayout=UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars=NO;
self.automaticallyAdjustsScrollViewInsets=NO;
}
It fixed status bar color for me and other UI misplacements also to a extent.
I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.
I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"
When I import it to excel(google), excel understand it as string. It still not break new line.
We need to trigger excel to treat it as formula by: Format -> Number | Scientific.
This is not the good way but it resolve my issue.
How about this solution?
// other onload attached earlier
window.onload=function() {
alert('test');
};
tmpPreviousFunction=window.onload ? window.onload : null;
// our onload function
window.onload=function() {
alert('another message');
// execute previous one
if (tmpPreviousFunction) tmpPreviousFunction();
};
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
The cex
parameter will do that for you.
a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
col = 1:6, space = c(0, 2))
legend("topright",
legend = c("a", "b", "c", "d", "e", "f"),
fill = 1:6, ncol = 2,
cex = 0.75)
Past 10g the current answer no longer works for renaming views. The only method that still works is dropping and recreating the view. The best way I can think of to do this would be:
SELECT TEXT FROM ALL_VIEWS WHERE owner='some_schema' and VIEW_NAME='some_view';
Add this in front of the SQL returned
Create or replace view some_schema.new_view_name as ...
Drop the old view
Drop view some_schema.some_view;
I think you can propagate the tap to the view controller and let it handle it. This is more acceptable approach. As for accessing a view controller from its view, you should maintain a reference to a view controller, since there is no another way. See this thread, it might help: Accessing view controller from a view
I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:
It's a real short VB.Net app: I can post code if any one is interested.
You can get the example and sample code at the official site, as following:
<TextInput password={true} style={styles.default} value="abc" />
Reference: http://facebook.github.io/react-native/docs/textinput.html
I had the same problem and for me it was because the vc2010 redist x86 was too recent.
Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named
and check if you have the following error
Installation Blockers:
A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.
Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).
then go to Control Panel>Program & Features and uninstall all the
After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.
In vim open the file (e.g.: :e YOURFILE
ENTER), then
:set noendofline binary
:wq
DONE=false
until $DONE
do
read line || DONE=true
echo $line
done < blah.txt
I wouldn't recommended this is you've got a lot of "thinking" in your app, but using XSLT could be better (and potentially faster with XSLT-to-bytecode compilation) than Java manipulation.
If you want not to strip, but to actually convert latin accented to non-accented characters, take a look at this question: How do I translate 8bit characters into 7bit characters? (i.e. Ü to U)
The usage of ping is good, as long as you just want to "wait for a bit". This since you are dependent on other functions underneath, like your network working and the fact that there is nothing answering on 127.0.0.1. ;-) Maybe it is not very likely it fails, but it is not impossible...
If you want to be sure that you are waiting exactly the specified time, you should use the sleep
functionality (which also have the advantage that it doesn't use CPU power or wait for a network to become ready).
To find an already made executable for sleep is the most convenient way. Just drop it into your Windows folder or any other part of your standard path and it is always available.
Otherwise, if you have a compiling environment you can easily make one yourself.
The Sleep
function is available in kernel32.dll
, so you just need to use that one. :-)
For VB / VBA declare the following in the beginning of your source to declare a sleep function:
private Declare Sub Sleep Lib "kernel32" Alias "Sleep" (byval dwMilliseconds as Long)
For C#:
[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);
You'll find here more about this functionality (available since Windows 2000) in Sleep function (MSDN).
In standard C, sleep()
is included in the standard library and in Microsoft's Visual Studio C the function is named Sleep()
, if memory serves me. ;-) Those two takes the argument in seconds, not in milliseconds as the two previous declarations.
You could use an onclick
event handler in order to get the input value for the text field. Make sure you give the field an unique id
attribute so you can refer to it safely through document.getElementById()
:
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">
. Create new elements by means of document.createElement()
, and use appendChild()
to append each of them to the container. You might be interested in outputting a meaningful name
attribute (e.g. name="member"+i
for each of the dynamically generated <input>
s if they are to be submitted in a form.
Notice you could also create <br/>
elements with document.createElement('br')
. If you want to just output some text, you can use document.createTextNode()
instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()
and removeChild()
together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Number of inputs to create
var number = document.getElementById("member").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
_x000D_
See a working sample in this JSFiddle.
You should be able to do something like this:
http://maps.google.com/maps?q=24.197611,120.780512
Some more info on the query parameters available at this location
Here's another link to an SO thread
All you have to do is create a subset of your dataframe where the isin method evaluates to False:
df = df[df['Column Name'].isin(['Value']) == False]
When I have this problem it is because the client.config had its endpoints like:
https://myserver/myservice.svc
but the certificate was expecting
https://myserver.mydomain.com/myservice.svc
Changing the endpoints to match the FQDN of the server resolves my problem. I know this is not the only cause of this problem.
Pls check JobScheduler for apis above 26
WakeLock was the best option for this but it is deprecated in api level 26
Pls check this link if you consider api levels above 26
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)
It says
As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).
so as it says cosider JobScheduler
https://developer.android.com/reference/android/app/job/JobScheduler
if it is to do something than to start and to keep it you can receive the broadcast ACTION_BOOT_COMPLETED
If it isn't about foreground pls check if an Accessibility service could do
another option is to start an activity from broadcast receiver and finish it after starting the service within onCreate() , since newer android versions doesnot allows starting services from receivers
onclick="window.open('your_html', '_blank')"
Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?
If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.
If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.
You'll want to leave your session cookie as a cookie either way though.
As per the technical difference, and also my understanding:
Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domain — SO Question also mentions it.
localStorage
is an implementation of the Storage
Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.
Apart from having a Path
variable, the directory C:\data\db
is mandatory.
Create this and the error shall be solved.
See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:
shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"
Tuck this away in some utility class.
+ (void)dismissKeyboard {
[self globalResignFirstResponder];
}
+ (void) globalResignFirstResponder {
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
for (UIView * view in [window subviews]){
[self globalResignFirstResponderRec:view];
}
}
+ (void) globalResignFirstResponderRec:(UIView*) view {
if ([view respondsToSelector:@selector(resignFirstResponder)]){
[view resignFirstResponder];
}
for (UIView * subview in [view subviews]){
[self globalResignFirstResponderRec:subview];
}
}
if ($variable % 6 == 0) {
echo 'This number is divisible by 6.';
}:
Make divisible by 6:
$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors
An even more minimalistic example:
var linkedResource = new LinkedResource(@"C:\Image.jpg", MediaTypeNames.Image.Jpeg);
// My mail provider would not accept an email with only an image, adding hello so that the content looks less suspicious.
var htmlBody = $"hello<img src=\"cid:{linkedResource.ContentId}\"/>";
var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(linkedResource);
var mailMessage = new MailMessage
{
From = new MailAddress("[email protected]"),
To = { "[email protected]" },
Subject = "yourSubject",
AlternateViews = { alternateView }
};
var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
Try the below code for delay
//MARK: First Way
func delayForWork() {
delay(3.0) {
print("delay for 3.0 second")
}
}
delayForWork()
// MARK: Second Way
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// your code here delayed by 0.5 seconds
}
I've used this before to setup a query against another server and db via linked server:
EXEC sp_addlinkedserver @server='PWA_ProjectServer', @srvproduct='',
@provider='SQLOLEDB', @datasrc='SERVERNAME\PWA_ProjectServer'
per the comment above:
select * from [server].[database].[schema].[table]
e.g.
select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]
Extend TextView and override onDraw with the code below. It will keep text aspect ratio but size it to fill the space. You could easily modify code to stretch if necessary.
@Override
protected void onDraw(@NonNull Canvas canvas) {
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.drawableState = getDrawableState();
String text = getText().toString();
float desiredWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - 2;
float desiredHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - 2;
float textSize = textPaint.getTextSize();
for (int i = 0; i < 10; i++) {
textPaint.getTextBounds(text, 0, text.length(), rect);
float width = rect.width();
float height = rect.height();
float deltaWidth = width - desiredWidth;
float deltaHeight = height - desiredHeight;
boolean fitsWidth = deltaWidth <= 0;
boolean fitsHeight = deltaHeight <= 0;
if ((fitsWidth && Math.abs(deltaHeight) < 1.0)
|| (fitsHeight && Math.abs(deltaWidth) < 1.0)) {
// close enough
break;
}
float adjustX = desiredWidth / width;
float adjustY = desiredHeight / height;
textSize = textSize * (adjustY < adjustX ? adjustY : adjustX);
// adjust text size
textPaint.setTextSize(textSize);
}
float x = desiredWidth / 2f;
float y = desiredHeight / 2f - rect.top - rect.height() / 2f;
canvas.drawText(text, x, y, textPaint);
}
In addition to the answer already given and accepted, it is also possible to place a marker and then indent everything from the current cursor to the marker.
Thus, enter ma
where you want the top of your indented block, cursor down as far as you need and then type >'a
(note that "a
" can be substituted for any valid marker name). This is sometimes easier than 5>>
or vjjj>
.
Read all the answers.
There is another user case where final
keyword can be used i.e. in a method argument:
public void showCaseFinalArgumentVariable(final int someFinalInt){
someFinalInt = 9; // won't compile as the argument is final
}
Can be used for variable which should not be changed.
volatile:
volatile
is a keyword. volatile
forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.
AtomicXXX:
AtomicXXX
classes support lock-free thread-safe programming on single variables. These AtomicXXX
classes (like AtomicInteger
) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.
When to use: Multiple threads can read and modify data.
synchronized:
synchronized
is keyword used to guard a method or code block. By making method as synchronized has two effects:
First, it is not possible for two invocations of synchronized
methods on the same object to interleave. When one thread is executing a synchronized
method for an object, all other threads that invoke synchronized
methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized
method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized
method for the same object. This guarantees that changes to the state of the object are visible to all threads.
When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations
AtomicXXX
is equivalent of volatile + synchronized
even though the implementation is different. AmtomicXXX
extends volatile
variables + compareAndSet
methods but does not use synchronization.
Related SE questions:
Difference between volatile and synchronized in Java
Volatile boolean vs AtomicBoolean
Good articles to read: ( Above content is taken from these documentation pages)
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
When you run the sqlite3
cli, typing in:
sqlite3 -header
will also give the desired result
PuTTY Session Manager is a tool that allows system administrators to organise their PuTTY sessions into folders and assign hotkeys to favourite sessions. Multiple sessions can be launched with one click. Requires MS Windows and the .NET 2.0 Runtime.
This might help you.
<form id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" />
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="save()" />
</form>
<script>
function save(){
$('#myinput').val('1');
$('#form').submit();
}
</script>
Use csv.writer
:
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1
writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
if counter[row[0]] >= 4:
writer.writerow(row)
Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"
StringBuilder builder = new StringBuilder();
Enumerable
.Range(65, 26)
.Select(e => ((char)e).ToString())
.Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
.Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
.OrderBy(e => Guid.NewGuid())
.Take(11)
.ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();
It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.
0.001% duplicates in 100 million.
You could set it up as a Scheduled Task, and set the Task Trigger for "At Startup"
First, you need to call the owl.autoplay.js.
this code works for me : owl.trigger('play.owl.autoplay',[1000]);
You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)
function foo(&$arr) { # note the &
$arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6
That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?
I had two manifest.xml file in my app section,so I needed to change package name in both
you can suppress this error in eclipse: Window -> Preferences -> Maven -> Error/Warnings
Javascript has a random()
available. Take a look at Math.random().
You can get param from request.
@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
HttpServletResponse response, Model model){
String jsonString = request.getParameter("json");
}
I solve this problem by mixing the solutions above.
sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()
I think it works well
This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:
import pylab
datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]
for data, label in datalist:
pylab.plot( data[:,0], data[:,1], label=label )
pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")
You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.
Specify path after entered commit message, like:
git commit -m "commit message" path/to/file.extention
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
Also seems nobody noticed -x operator on symlinks. A symlink (chain) to a regular file (not classified as executable) fails the test.
When you call another .bat file, I think you need "call" in front of the call:
call otherCommand.bat
You can force the case sensitive, casting to a varbinary like that:
SELECT * FROM myTable
WHERE convert(varbinary, myField) = convert(varbinary, 'sOmeVal')
While I believe SJoshi (oracle guy) has the most complete answer, the SWIG project is a special case, interesting and useful one, at that, but not generalized for the majority of projects that have done well with the standard SDK ant based projects + NDK. We all would like to be using Android studio now most likely, or want a more CI friendly build toolchain for mobile, which gradle theoretically offers.
I've posted my approach, borrowed from somewhere (I found this on SO, but posted a gist for the app build.gradle: https://gist.github.com/truedat101/c45ff2b69e91d5c8e9c7962d4b96e841 ). In a nutshell, I recommend the following:
Gradle for Android has been a mess in my opinion, much as I like the maven concepts borrowed and the opinionated structure of directories for a project. This NDK feature has been "coming soon" for almost 3+ years.
Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.
For more collections, there is also the C5 Generic Collection Library.
Not sure if this might help.
Check that the Assembly name and the Default namespace in the Properies in your asemblies match. This resolved my issue which yielded the same error.
Ruby has no pre/post increment/decrement operator. For instance,
x++
orx--
will fail to parse. More importantly,++x
or--x
will do nothing! In fact, they behave as multiple unary prefix operators:-x == ---x == -----x == ......
To increment a number, simply writex += 1
.
Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)
That explains it better than I ever could.
EDIT: and the reason from the language author himself (source):
- ++ and -- are NOT reserved operator in Ruby.
- C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
- self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
simple using linq, change as you see fit for whatever control your dealing with.
private void DisableButtons()
{
foreach (var ctl in Controls.OfType<Button>())
{
ctl.Enabled = false;
}
}
private void EnableButtons()
{
foreach (var ctl in Controls.OfType<Button>())
{
ctl.Enabled = true;
}
}
The following was tested for IIS 8.5 and Windows 8.1.
As of IIS 7, Windows recommends restarting IIS via net stop/start
. Via the command prompt (as Administrator):
> net stop WAS
> net start W3SVC
net stop WAS
will stop W3SVC
as well. Then when starting, net start W3SVC
will start WAS
as a dependency.
I have created a horizontal ListView in every row of ListView if you want single You can do the following
Here I am just creating horizontalListView of Thumbnail of Videos Like this
The idea is just continuously add the ImageView to the child of LinearLayout in HorizontalscrollView
Note: remember to fire .removeAllViews(); before next time load other wise it will add duplicate child
Cursor mImageCursor = db.getPlaylistVideoImage(playlistId);
mVideosThumbs.removeAllViews();
if (mImageCursor != null && mImageCursor.getCount() > 0) {
for (int index = 0; index < mImageCursor.getCount(); index++) {
mImageCursor.moveToPosition(index);
ImageView iv = (ImageView) imageViewInfalter.inflate(
R.layout.image_view, null);
name = mImageCursor.getString(mImageCursor
.getColumnIndex("LogoDefaultName"));
logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
if (logoFile.exists()) {
Uri uri = Uri.fromFile(logoFile);
iv.setImageURI(uri);
}
iv.setScaleType(ScaleType.FIT_XY);
mVideosThumbs.addView(iv);
}
mImageCursor.close();
mImageCursor = null;
} else {
ImageView iv = (ImageView) imageViewInfalter.inflate(
R.layout.image_view, null);
String name = "";
File logoFile;
name = mImageCursor.getString(mImageCursor
.getColumnIndex("LogoMediumName"));
logoFile = new File(MyApplication.LOCAL_LOGO_PATH, name);
if (logoFile.exists()) {
Uri uri = Uri.fromFile(logoFile);
iv.setImageURI(uri);
}
}
My xml for HorizontalListView
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/linearLayoutTitle"
android:background="@drawable/shelf"
android:paddingBottom="@dimen/Playlist_TopBottom_margin"
android:paddingLeft="@dimen/playlist_RightLeft_margin"
android:paddingRight="@dimen/playlist_RightLeft_margin"
android:paddingTop="@dimen/Playlist_TopBottom_margin" >
<LinearLayout
android:id="@+id/linearLayoutVideos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
and Also my Image View as each child
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/imageViewThumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:adjustViewBounds="true"
android:background="@android:color/transparent"
android:contentDescription="@string/action_settings"
android:cropToPadding="true"
android:maxHeight="200dp"
android:maxWidth="240dp"
android:padding="@dimen/playlist_image_padding"
android:scaleType="centerCrop"
android:src="@drawable/loading" />
To learn More you can follow the following links which have some easy samples
A new paper has been released with several tests against reCAPTCHA:
Some highlights:
Google has already fixed the cookie vulnerability and is probably restricting some behaviors based on IPs.
Another interesting finding is that Google runs a VM in JavaScript that obfuscates much of reCAPTCHA code and behavior. This VM is known as botguard and is used to protect other services besides reCAPTCHA:
https://github.com/neuroradiology/InsideReCaptcha
UPDATE 2017
A recent paper (from August) was published on WOOT 2017 achieving 85% accuracy in solving noCAPTCHA reCAPTCHA audio challenges:
http://uncaptcha.cs.umd.edu/papers/uncaptcha_woot17.pdf
UPDATE 2018
Google is introducing reCAPTCHA v3, which looks like a "human score prediction engine" that is calibrated per website. It can be installed into different pages of a website (working like a Google Analytics script) to help reCAPTCHA and the website owner to understand the behaviour of humans vs. bots before filling a reCAPTCHA.
Use []
:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
You need to use the select new
LINQ keyword to explicitly convert your tbcourse
entity into the custom type course
. Example of select new
:
var q = from o in db.Orders
where o.Products.ProductName.StartsWith("Asset") &&
o.PaymentApproved == true
select new { name = o.Contacts.FirstName + " " +
o.Contacts.LastName,
product = o.Products.ProductName,
version = o.Products.Version +
(o.Products.SubVersion * 0.1)
};
Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,
Only these two are enough for performing Ajax operation.
Try to declare it in menifest file
<activity android:name=".HomeActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysHidden"
>
setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:
myObject.prototype.myMethodDeferred = function() {
var deferredObject = $.Deferred();
var that = this; // Because setTimeout won't work right with this
setTimeout(function() {
return myMethodActualWork.call(that, deferredObject);
}, 0);
return deferredObject.promise();
}
One way to do it if tagID
values are known upfront is to use conditional aggregation
SELECT TimeSeconds,
COALESCE(MAX(CASE WHEN TagID = 'A1' THEN Value END), 'n/a') A1,
COALESCE(MAX(CASE WHEN TagID = 'A2' THEN Value END), 'n/a') A2,
COALESCE(MAX(CASE WHEN TagID = 'A3' THEN Value END), 'n/a') A3,
COALESCE(MAX(CASE WHEN TagID = 'A4' THEN Value END), 'n/a') A4
FROM table1
GROUP BY TimeSeconds
or if you're OK with NULL
values instead of 'n/a'
SELECT TimeSeconds,
MAX(CASE WHEN TagID = 'A1' THEN Value END) A1,
MAX(CASE WHEN TagID = 'A2' THEN Value END) A2,
MAX(CASE WHEN TagID = 'A3' THEN Value END) A3,
MAX(CASE WHEN TagID = 'A4' THEN Value END) A4
FROM table1
GROUP BY TimeSeconds
or with PIVOT
SELECT TimeSeconds, A1, A2, A3, A4
FROM
(
SELECT TimeSeconds, TagID, Value
FROM table1
) s
PIVOT
(
MAX(Value) FOR TagID IN (A1, A2, A3, A4)
) p
Output (with NULL
s):
TimeSeconds A1 A2 A3 A4 ----------- ------- ------ ----- ----- 1378700244 3.75 NULL NULL NULL 1378700245 30.00 NULL NULL NULL 1378700304 1.20 NULL NULL NULL 1378700305 NULL 56.00 NULL NULL 1378700344 NULL 11.00 NULL NULL 1378700345 NULL NULL 0.53 NULL 1378700364 4.00 NULL NULL NULL 1378700365 14.50 NULL NULL NULL 1378700384 144.00 NULL NULL 10.00
If you have to figure TagID
values out dynamically then use dynamic SQL
DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX)
SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(TagID)
FROM Table1
ORDER BY 1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @sql = 'SELECT TimeSeconds, ' + @cols + '
FROM
(
SELECT TimeSeconds, TagID, Value
FROM table1
) s
PIVOT
(
MAX(Value) FOR TagID IN (' + @cols + ')
) p'
EXECUTE(@sql)
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
var url ='www.site.com/index.php#hello';
var type = url.split('#');
var hash = '';
if(type.length > 1)
hash = type[1];
alert(hash);
Working demo on jsfiddle
For those who have this possibility (VPS hosting not web hosting):
Connect to your hosting server via Remote Desktop. Open Web Browser from your remote desktop and you will see the detail description of the error.
You don't need to modify web.config or expose any details to anybody else.
If you are "getting data" from an application, the sensible thing would be to use the profiler and profile the database while running the application. Trace it, then search the results for that string.
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.
Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.
Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.
It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
If you have downloaded these files locally then you can change following classes in bootstrap-social.css, just added border-radius: 50%;
.btn-social-icon.btn-lg{height:45px;width:45px;
padding-left:0;padding-right:0; border-radius: 50%; }
And here is teh HTML
<a class="btn btn-social-icon btn-lg btn-twitter" >
<i class="fa fa-twitter"></i>
</a>
<a class=" btn btn-social-icon btn-lg btn-facebook">
<i class="fa fa-facebook sbg-facebook"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-google-plus">
<i class="fa fa-google-plus"></i>
</a>
It works smooth for me.
(5/9)
will by default be computed as an integer division and will be zero. Try (5.0/9)
Highest voted answer uses Lodash _.chain
function which is considered a bad practice now "Why using _.chain
is a mistake."
Here is a fewliner that approaches the problem from functional programming perspective:
import tap from "lodash/fp/tap";
import flow from "lodash/fp/flow";
import groupBy from "lodash/fp/groupBy";
const map = require('lodash/fp/map').convert({ 'cap': false });
const result = flow(
groupBy('color'),
map((users, color) => ({color, users})),
tap(console.log)
)(input)
Where input
is an array that you want to convert.
I found one Solution :
echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));
use utf8_encode()
hyperjaxb (versions 2 and 3) actually generates hibernate mapping files and related entity objects and also does a round trip test for a given XSD and sample XML file. You can capture the log output and see the DDL statements for yourself. I had to tweak them a little bit, but it gives you a basic blue print to start with.
Just so it be noted: If the requirement to preserve the elements order is relaxed it is much more efficient to replace the element being removed with the last element.
In the upper right corner of the dialog, mouse over where the button should be, and see rather or not you get some effect (the button hover). Try clicking it and seeing if it closes. If it does close, then you're just missing your image sprites that came with your package download.
Update 2018, SDK >= 23.
Now you should also check if the user has granted permission to external storage by using:
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
public void saveImageBitmap(Bitmap image_bitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) { // check or ask permission
File myDir = new File(root, "/saved_images");
if (!myDir.exists()) {
myDir.mkdirs();
}
String fname = "Image-" + image_name + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
image_bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
}
}
and of course, add in the AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
There should be
$('.send_upload')
but not $('.upload')
Moral of the story:
Inherit only if you want to override some behavior.
Or rather it should be read as:
Inherit less, interface more.
This is not a reply (I cant post comments), just few random ideas might be helpful. Unfortunately I've never dealt with citrix, only with regular windows servers.
_0. Ensure you're not a victim of Windows Firewall, or any other personal firewall that selectively blocks processes.
Add 10 minutes Sleep() to the first line of your .NET app, then run both VBScript file and your stand-alone application, run sysinternals process explorer, and compare 2 processes.
_1. Same tab, "command line" and "current directory". Make sure they are the same.
_2. "Environment" tab. Make sure they are the same. Normally child processes inherit the environment, but this behaviour can be easily altered.
The following check is required if by "run my script" you mean anything else then double-clicking the .VBS file:
_3. Image tab, "User". If they differ - it may mean user has no access to the network (like localsystem), or user token restricted to delegation and thus can only access local resources (like in the case of IIS NTLM auth), or user has no access to some local files it wants.
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
join this "literal table",
select
t.c.value('@c', 'varchar(30)') code,
t.c.value('@v', 'varchar(30)') val
from (select convert(xml, '<x c="CODE001" v="Value One" /><x c="CODE002" v="Value Two" />') aXmlCol) z
cross apply aXmlCol.nodes('/x') t(c)
This is an online/offline solution and very easy to convert. SCSS to CSS converter
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
There are multiple ways to add the basic HTTP authentication to the RestTemplate
.
try {
// request url
String url = "https://jsonplaceholder.typicode.com/posts";
// create auth credentials
String authStr = "username:password";
String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());
// create headers
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
// create request
HttpEntity request = new HttpEntity(headers);
// make a request
ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);
// get JSON response
String json = response.getBody();
} catch (Exception ex) {
ex.printStackTrace();
}
If you are using Spring 5.1
or higher, it is no longer required to manually set the authorization header. Use headers.setBasicAuth()
method instead:
// create headers
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");
@Service
public class RestService {
private final RestTemplate restTemplate;
public RestService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthentication("username", "password")
.build();
}
// use `restTemplate` instance here
}
@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.basicAuthentication("username", "password").build();
}
I hope it helps!
Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.
So what you do is register the driver so that the JDBC system can know what to do with the URL:
DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
Then you form the URL:
String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"
And finally, use it to get a connection:
Connection c = DriverManager.getConnection(url);
In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.
In terms of what properties MySQL supports, see here.
EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.
In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]
List<personClass> Getperson(string id);
Go to Project-><Projectname> Properties
. Then click on the Debug
tab, and fill in your arguments in the textbox called Command line arguments
.
I tried several answers here, and none of them worked. Ironically, what did work was about the simplest alternative to a <br/>
one could attempt:
<div style="flex-basis: 100%;"></div>
or you could also do:
<div style="width: 100%;"></div>
Place that wherever you want a new line. It seems to work even with adjacent <span>
's, but I'm using it with adjacent <div>
's.
I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,
then on the actual $_post's I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.
After it does whatever to the data, I run a function to clear all the $_post data for each section. you can hit refresh till your blue in the face it won't do anything but refresh the page and display.
So you just need to think logically and make it idiot proof for your users...
I do believe the easiest way is to first go to instant and then to string like:
String d = new Date().toInstant().toString();
Which will result in:
2017-09-08T12:56:45.331Z
Truncate drops the decimal point.
I just had an issue where I needed to solve this properly.
Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.
the code I ended up with:
$.each(messages, function(idx, el){
window.setTimeout(function(){
doSomething(el);
},Math.floor(idx+1)*10000);
});
Basically, think of the timeouts as a "timeline" of your script.
This is what we WANT to code:
DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();
This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:
At Runtime 0 : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();
Hope this helps.
Instead of
let loginRegisterButton:UIButton = {
//... }()
Try:
lazy var loginRegisterButton:UIButton = {
//... }()
That should fix the compile error!!!
Although the other answers solve the OP's problem, they are all overkill and do not explain why he or she is experiencing this issue.
The key is this line, "I close putty, then I cannot reach the address"
When you are logged into your remote host on Putty you have started an SSH linux process and all commands typed from that SSH session will be executed as children of said process.
Your problem is that when you close Putty you are exiting the SSH session which kills that process and any active child processes. When you close putty you inadvertently kill your server because you ran it in the foreground. To avoid this behavior run the server in the background by appending & to your command:
node /srv/www/MyUserAccount/server/server.js &
The problem here is a lack of linux knowledge and not a question about node. For some more info check out: http://linuxconfig.org/understanding-foreground-and-background-linux-processes
UPDATE:
As others have mentioned, the node server may still die when exiting the terminal. A common gotcha I have come across is that even though the node process is running in bg, it's stdout and stderr is still pointed at the terminal. This means that if the node server writes to console.log or console.error it will receive a broken pipe error and crash. This can be avoided by piping the output of your process:
node /srv/www/MyUserAccount/server/server.js > stdout.txt 2> stderr.txt &
If the problem persists then you should look into things like tmux or nohup, which are still more robust than node specific solutions, because they can be used to run all types of processes (databases, logging services, other languages).
A common mistake that could cause the server to exit is that after running the nohup node your_path/server.js &
you simply close the Putty terminal by a simple click. You should use exit
command instead, then your node server will be up and running.
It's not built into the SDK, but you can use the Zxing library. It's free, open source, and Apache-licensed.
The 2016 recommendation is to use the Barcode API, which also works offline.
Regular expressions are probably the easiest solution to this problem:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]
Either u dont have permission to that schema/table OR table does exist. Mostly this issue occurred if you are using other schema tables in your stored procedures. Eg. If you are running Stored Procedure from user/schema ABC and in the same PL/SQL there are tables which is from user/schema XYZ. In this case ABC should have GRANT i.e. privileges of XYZ tables
Grant All On To ABC;
Select * From Dba_Tab_Privs Where Owner = 'XYZ'and Table_Name = <Table_Name>;
To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0
, then you can be sure the original only contained whitespace. Try this:
var str = " ";_x000D_
if (!str.replace(/\s/g, '').length) {_x000D_
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');_x000D_
}
_x000D_
I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.
Something like this should work as a category for NSDate:
- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];
NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
return [selfDateOnly compare:otherDateOnly];
}
To replace whole line containing a specified string with the content of that line
Text file:
Row: 0 last_time_contacted=0, display_name=Mozart, _id=100, phonebook_bucket_alt=2
Row: 1 last_time_contacted=0, display_name=Bach, _id=101, phonebook_bucket_alt=2
Single string:
$ sed 's/.* display_name=\([[:alpha:]]\+\).*/\1/'
output:
100
101
Multiple strings delimited by white-space:
$ sed 's/.* display_name=\([[:alpha:]]\+\).* _id=\([[:digit:]]\+\).*/\1 \2/'
output:
Mozart 100
Bach 101
Adjust regex to meet your needs
[:alpha] and [:digit:] are Character Classes and Bracket Expressions
You can use JavaScript functions like replace, and you can wrap the jQuery code in brackets:
var value = ($("#text").val()).replace(".", ":");
Make sure your AUTO_INCREMENT
is not out of range. In that case, set a new value for it with:
ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number
AUTO_INCREMENT
can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT
stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.
If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT
to one bigger than the latest row's id. So if your latest row's id is 100 then:
ALTER TABLE table_name AUTO_INCREMENT=101
If you would like to check AUTO_INCREMENT
's current value, use this command:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
This may be helpful.
var myOptions = {
center: new google.maps.LatLng($lat,$lang),
zoom: 7,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
The Zoom level can be customizable according to the requirement.
Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.
To answer your question:
Today NodeJS supports new async/await
syntax. This is an easy syntax and makes the life much easier
async function process(promises) { // must be an async function
let x = await Promise.all(promises); // now x will be an array
x = x.map( tmp => tmp * 10); // proccessing the data.
}
const promises = [
new Promise(resolve => setTimeout(resolve, 0, 1)),
new Promise(resolve => setTimeout(resolve, 0, 2))
];
process(promises)
Learn more:
All depends on the app you're trying to build. Use Window
s if you're building a dialog based app. Use Page
s if you're building a navigation based app. UserControl
s will be useful regardless of the direction you go as you can use them in both Windows and Pages.
A good place to start exploring is here: http://windowsclient.net/learn
you can use CASE
SELECT ...,
CASE WHEN IDParent < 1 THEN ID ELSE IDPArent END AS ColumnName,
...
FROM tableName
I have added slashes before inserting into database so on the time of fetching i removed slashes again stripslashes()
and it works for me. I am sharing the code which works for me.
How i inserted into mysql db (blob type)
$db = mysqli_connect("localhost","root","","dName");
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO student_img (id,image) VALUES('','$image')";
$query = mysqli_query($db, $query);
Now to access the image
$sqlQuery = "SELECT * FROM student_img WHERE id = $stid";
$rs = $db->query($sqlQuery);
$result=mysqli_fetch_array($rs);
echo '<img src="data:image/jpeg;base64,'.base64_encode( stripslashes($result['image']) ).'"/>';
Hope it will help someone
Thanks.
All you should need to do is:
# if the file in the right place isn't already committed:
git add <path to desired file>
# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai
# commit the merge:
git commit
I get the same error when I specify my HTTPS URL as : https://www.mywebsite.com . However it works fine when I specify it without the three W's as : https://mywebsite.com .
I would suggest that you use Apache's commons logging utility. It is highly scalable and supports separate log files for different loggers. See here.
The simplest way is using the Multiplicative formula. It works for (n,n) and (n,0) as expected.
def coefficient(n,k):
c = 1.0
for i in range(1, k+1):
c *= float((n+1-i))/float(i)
return c
Just start from there that in CSS, if you repeat 2 values or more, always last one gets applied, unless using !important
tag, but at the same time avoid using !important
as much as you can, so in your case that's the problem, so the second transform override the first one in this case...
So how you can do what you want then?...
Don't worry, transform accepts multiple values at the same time... So this code below will work:
li:nth-child(2) {
transform: rotate(15deg) translate(-20px, 0px); //multiple
}
If you like to play around with transform run the iframe from MDN below:
<iframe src="https://interactive-examples.mdn.mozilla.net/pages/css/transform.html" class="interactive " width="100%" frameborder="0" height="250"></iframe>
_x000D_
Look at the link below for more info:
Grep has an option called Context Line Control
, you can use the --context
in that, simply,
| grep -C 5
or
| grep -5
Should do the trick
If an InterruptedException
is thrown it means that something wants to interrupt (usually terminate) that thread. This is triggered by a call to the threads interrupt()
method. The wait method detects that and throws an InterruptedException
so the catch code can handle the request for termination immediately and does not have to wait till the specified time is up.
If you use it in a single-threaded app (and also in some multi-threaded apps), that exception will never be triggered. Ignoring it by having an empty catch clause I would not recommend. The throwing of the InterruptedException
clears the interrupted state of the thread, so if not handled properly that info gets lost. Therefore I would propose to run:
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// code for stopping current task so thread stops
}
Which sets that state again. After that, finish execution. This would be correct behaviour, even tough never used.
What might be better is to add this:
} catch (InterruptedException e) {
throw new RuntimeException("Unexpected interrupt", e);
}
...statement to the catch block. That basically means that it must never happen. So if the code is re-used in an environment where it might happen it will complain about it.
$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
You could use the Date.getDay()
method, which returns 0 for sunday, up to 6 for saturday. So, you could simply create an array with the name for the day names:
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(dateString);
var dayName = days[d.getDay()];
Here dateString
is the string you received from the third party API.
Alternatively, if you want the first 3 letters of the day name, you could use the Date
object's built-in toString
method:
var d = new Date(dateString);
var dayName = d.toString().split(' ')[0];
That will take the first word in the d.toString()
output, which will be the 3-letter day name.
Crossframe-Scripting is not possible when the two frames have different domains -> Security.
See this: http://javascript.about.com/od/reference/a/frame3.htm
Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.
Make sure this is included in your Info.plist:
<key>CFBundlePackageType</key>
<string>APPL</string>
I had APPL misspelled as AAPL. Once I fixed that and signed into Application Loader and Xcode with the same Apple ID, everything worked.
I hope this will help you.
Goto to your BIOS settings. Enable your Virtualization technology in your settings..
It solved my problem...
For those who need to use the output in subsequent shell commands, rather than groovy, something like this example could be done:
stage('Show Files') {
environment {
MY_FILES = sh(script: 'cd mydir && ls -l', returnStdout: true)
}
steps {
sh '''
echo "$MY_FILES"
'''
}
}
I found the examples on code maven to be quite useful.
I've written this, but have to check the existing methods mentioned to see if they are better.
module PrettyDate
def to_pretty
a = (Time.now-self).to_i
case a
when 0 then 'just now'
when 1 then 'a second ago'
when 2..59 then a.to_s+' seconds ago'
when 60..119 then 'a minute ago' #120 = 2 minutes
when 120..3540 then (a/60).to_i.to_s+' minutes ago'
when 3541..7100 then 'an hour ago' # 3600 = 1 hour
when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago'
when 82801..172000 then 'a day ago' # 86400 = 1 day
when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
when 518400..1036800 then 'a week ago'
else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
end
end
end
Time.send :include, PrettyDate
I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.
You could use LINQ, but I would go with RemoveAll
method. I think that is the one that better expresses your intent.
var integers = new List<int> { 1, 2, 3, 4, 5 };
var remove = new List<int> { 1, 3, 5 };
integers.RemoveAll(i => remove.Contains(i));
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
It's possible using the \A
escape sequence in the psuedo-element generated content. Read more in the CSS2 spec.
#restart:before { content: '\A'; }
You may also need to add white-space:pre;
to #restart
.
note: \A
denotes the end of a line.
p.s. Another treatment to be
:before { content: ' '; display: block; }
There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member
is correctly defined as
package pageNumber;
since, that's the only application package you're importing in your JSP.
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
You can use RelativeSource
to find the parent element, like this -
Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified,
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"
See this SO question for more details about RelativeSource
.
You could use formaction attribute (for type=submit/image, overriding form's action) and pass the non-sensitive value through URL (GET-request).
The posted question is not a problem on older browsers (for example on Chrome 49+).
As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
If Multiset
extends from the Array
class
x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]
x.union(y) # => [1, 2, 4, 7] (ONLY IN RUBY 2.6)
x.union(y, z) # => [1, 2, 4, 7, 3] (ONLY IN RUBY 2.6)
x | y # => [1, 2, 4, 7]
x.difference(y) # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z) # => [4] (ONLY IN RUBY 2.6)
x - y # => [4, 7]
x & y # => [1, 2]
For more info about the new methods in Ruby 2.6, you can check this blog post about its new features
try unpacking in one variable,
python will handle it as a list,
then unpack from the list
def returnATupleWithThreeValues():
return (1,2,3)
a = returnATupleWithThreeValues() # a is a list (1,2,3)
print a[0] # list[0] = 1
print a[1] # list[1] = 2
print a[2] # list[2] = 3
If you are using ASP.NET, the server-side code tags in these examples below will provide the exact control ID, even if you are using Master pages.
Javascript:
document.getElementById("<%=MyControlName.ClientID%>").value;
JQuery:
$("#<%= MyControlName.ClientID %>").val();
basically set.seed() function will help to reuse the same set of random variables , which we may need in future to again evaluate particular task again with same random varibales
we just need to declare it before using any random numbers generating function.
function uniqueid(){
// always start with a letter (for DOM friendlyness)
var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
do {
// between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
var ascicode=Math.floor((Math.random()*42)+48);
if (ascicode<58 || ascicode>64){
// exclude all chars between : (58) and @ (64)
idstr+=String.fromCharCode(ascicode);
}
} while (idstr.length<32);
return (idstr);
}
When I experienced this issue, what fixed it for me was making sure that the AndroidManifest.xml package name was the same as the build.grade applicationId.
You can put the condition after the WHEN
clause, like so:
SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...
HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed
document.getElementById('here').innerHTML = data.name;
This needed to be changed to
document.getElementById('here').innerHTML = data.n;
I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .
function solution($A) {
// code in PHP5.5
$n=count($A);
for($i=1;$i<=$n;$i++) {
if(!in_array($i,$A)) {
return (int)$i;
}
}
}
getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without http:
var optionsget = {
host : 'localhost',
port : 3010,
path : '/quote/random', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
Regarding learning resources, you won't go wrong if you start with http://www.nodebeginner.org/ and then go through some good book to get more in-depth knowledge - I recommend Professional Node.js , but there's many out there.
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
I think your problem is that the margin should be specified in the border tag and not in the grid.
I was able to get SSL working with the following boilerplate code:
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express');
var port = 8000;
var options = {
key: fs.readFileSync('./ssl/privatekey.pem'),
cert: fs.readFileSync('./ssl/certificate.pem'),
};
var app = express();
var server = https.createServer(options, app).listen(port, function(){
console.log("Express server listening on port " + port);
});
app.get('/', function (req, res) {
res.writeHead(200);
res.end("hello world\n");
});
For uploading large files through PHPMyAdmin, follow these steps:
Step 1: Open your php.ini file.
Step 2: Upgrading Memory Limit:
memory_limit = 750M
Step 3: Upgrading Maximum size to post:
post_max_size = 750M
Step 4: Upgrading Maximum file-size to upload:
upload_max_filesize = 1000M
Step 5: Upgrading Maximum Execution Time:
max_execution_time = 5000
Step 6: Upgrading Maximum Input Time:
max_input_time = 3000
Step 7: Restart your xampp control panel.
@funroll is absolutely right. Here you can see what you will need Make sure function runs on main thread only. If you do not want deal with threads you can do like this for example: create NSUserDefaults and in ViewDidLoad cheking condition was pressed button in another View or not (in another View set in NSUserDefaults needed information) and depending on the conditions set needed title for your UIButton, so [yourButton setTitle: @"Title" forState: UIControlStateNormal];
You can use concatenation operator and instead of declaring two variables only use one variable
String finalString = cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));
input[readonly]
{
background-color:blue;
}
https://curtistimson.co.uk/post/css/style-readonly-attribute-css/
Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.
This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.
Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.
In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.
font/woff2
For nginx add the following to the mime.types
file:
font/woff2 woff2;
Old Answer
The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2
.
Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2
is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/*
(font/ttf
, font/woff2
etc)...
N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.
So I have a load of release folders, where those folders may be checked out from one of a few different repos, and may be dev, qa or master branches or may be production releases, checked out from a tag, and the tag may be annotated or not. I have a script that will look at the target folder and get be back an answer in the form -. The problem is different versions of git return different status' for a tag checkout.
So I found git show-ref --tags
worked initially, except for the annotated tags. However adding -d added a separate entry to the list of tags, one for the tag, the other for the annotation (the annotation commit was identified as ^{} which I stripped out with sed).
So this is the core of my script, for anyone that wants it:-
REPO=`git --git-dir=${TARGET} remote show origin -n | \
grep "Fetch URL:" | \
sed -E "s/^.*\/(.*)$/\1/" | \
sed "s/.git$//"`
TAG=`git --git-dir=${TARGET} show-ref -d --tags | \
grep \`git --git-dir=${TARGET} show --quiet --format=format:%H HEAD\` | \
cut -d\ -f2 | \
cut -d/ -f3 | \
sed "s/\^{}$//"`
if [ "${TAG}" == "" ] ; then
BRANCH=`git --git-dir=${TARGET} show-ref --heads | \
grep \`git --git-dir=${TARGET} show --quiet --format=format:%H HEAD\` | \
cut -d\ -f2 | \
cut -d/ -f3`
TAG=${BRANCH}
fi
If you need to have a good and updated database, for having more performance and not requesting external services from your website, here there is a good place to download updated and accurate databases.
I'm recommending this because in my experience it was working excellent even including city and country location for my IP which most of other databases/apis failed to include/report my location except this service which directed me to this database.
(My ip location was from "Rasht" City in "Iran" when I was testing and the ip was: 2.187.21.235
equal to 45815275
)
Therefore I recommend to use these services if you're unsure about which service is more accurate:
Database:
http://lite.ip2location.com/databases
API Service:
http://ipinfodb.com/ip_location_api.php
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
You mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration