Swift 5+:
let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)
try this
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
For my purposes, in the context of a container view controller, I've found that
- (BOOL)isVisible {
return (self.isViewLoaded && self.view.window && self.parentViewController != nil);
}
works well.
You can configure an inputType
for your EditText
:
<EditText android:inputType="number" ... />
In pymongo you can use:
db.mycollection.find({"IMAGE URL":{"$ne":None}});
Because pymongo represents mongo "null" as python "None".
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.
Added the following to the config and it resolved the issue:
<system.net>
<defaultProxy enabled="true">
</defaultProxy>
</system.net>
We are using Akka in a large scale Telco project (unfortunately I can't disclose a lot of details). Akka actors are deployed and accessed remotely by a web application. In this way, we have a simplified RPC model based on Google protobuffer and we achieve parallelism using Akka Futures. So far, this model has worked brilliantly. One note: we are using the Java API.
Using some of the info in here I ended up creating my own function to use.
Could be used as...
custom_alert();
custom_alert( 'Display Message' );
custom_alert( 'Display Message', 'Set Title' );
jQuery UI Alert Replacement
function custom_alert( message, title ) {
if ( !title )
title = 'Alert';
if ( !message )
message = 'No Message to Display.';
$('<div></div>').html( message ).dialog({
title: title,
resizable: false,
modal: true,
buttons: {
'Ok': function() {
$( this ).dialog( 'close' );
}
}
});
}
If you want to delete all duplicates, but one out of each set of duplicates, this is one solution:
DELETE posts
FROM posts
LEFT JOIN (
SELECT id
FROM posts
GROUP BY id
HAVING COUNT(id) = 1
UNION
SELECT id
FROM posts
GROUP BY id
HAVING COUNT(id) != 1
) AS duplicate USING (id)
WHERE duplicate.id IS NULL;
Using [name=elementName]{}
without tag before will work too.
It will affect all elements with this name.
For example:
[name=test] {_x000D_
width: 100px;_x000D_
}
_x000D_
<input type=text name=test>_x000D_
<div name=test></div>
_x000D_
You are looking for the break statement.
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
From MSDN
string value = "9quali52ty3";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
You now have an array of the ASCII value of the bytes. I got the following:
57 113 117 97 108 105 53 50 116 121 51
Yes there is such a built-in function: os.path.join
.
>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'
<form name="myForm">_x000D_
<input name="myText" type="text" ng-model="mytext" required/>_x000D_
<button ng-disabled="myForm.$pristine|| myForm.$invalid">Save</button>_x000D_
</form>
_x000D_
If you want to be a bit more strict
To convert a string to lower case in Python, use something like this.
list.append(sentence.lower())
I found this in the first result after searching for "python upper to lower case".
Facebook has added test versions feature.
First, add a test version of your application: Create Test App
Then, change the Site URL to "http://localhost" under Website, and press Save Changes
That's all, but be careful: App ID and App Secret keys are different for the application and its test versions!
How do I set up the basic authorization?
All you need to do is use -u, --user USER[:PASSWORD]
. Behind the scenes curl
builds the Authorization
header with base64 encoded credentials for you.
Example:
curl -u username:password -i -H 'Accept:application/json' http://example.com
Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/
<script>
$(document).ready(function(){
$('#ex1').zoom();
});
</script>
$("#myTextBox").on("change paste keyup select", function() {
alert($(this).val());
});
select for browser suggestion
For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.
You can't predefine a size of an array in php. A good way to acheive your goal is the following:
// Create a new array.
$array = array();
// Add an item while $i < yourWantedItemQuantity
for ($i = 0; $i < $number_of_items; $i++)
{
array_push($array, $some_data);
//or $array[] = $some_data; for single items.
}
Note that it is way faster to use array_fill() to fill an Array :
$array = array_fill(0,$number_of_items, $some_data);
If you want to verify if a value has been set at an index, you should use the following: array_key_exists("key", $array) or isset($array["key"])
See array_key_exists , isset and array_fill
The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.
When running publicly rather than in development, you should not use the built-in development server (
flask run
). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:
$ pip install waitress
You need to tell Waitress about your application, but it doesn’t use
FLASK_APP
like flask run does. You need to tell it to import and call the application factory to get an application object.$ waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080
Or you can use waitress.serve()
in the code instead of using the CLI command.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
$ python hello.py
str="aaabbbbjjja";
int count = 0;
int size = str.Length;
string[] strarray = new string[size];
for (int i = 0; i < str.Length; i++)
{
strarray[i] = str.Substring(i, 1);
}
Array.Sort(strarray);
str = "";
for (int i = 0; i < strarray.Length - 1; i++)
{
if (strarray[i] == strarray[i + 1])
{
count++;
}
else
{
count++;
str = str + strarray[i] + count;
count = 0;
}
}
count++;
str = str + strarray[strarray.Length - 1] + count;
This is for counting the character occurance. For this example output will be "a4b4j3"
remove the http
or https
from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip
. this worked fine for me.
Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.
A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your gwt.xml
:
<define-property name="user.agent" values="ie6,gecko,gecko1_8"></define-property>
or in gwt 2.x syntax, and for one browser only:
<set-property name="user.agent" value="gecko1_8"/>
This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.
Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.
Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.
What about creating an additional wrapper class?
package com.naveen.research.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class PreparedStatementWrapper implements AutoCloseable {
protected PreparedStatement stat;
public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
this.stat = con.prepareStatement(query);
this.prepareStatement(params);
}
protected abstract void prepareStatement(Object ... params) throws SQLException;
public ResultSet executeQuery() throws SQLException {
return this.stat.executeQuery();
}
public int executeUpdate() throws SQLException {
return this.stat.executeUpdate();
}
@Override
public void close() {
try {
this.stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Then in the calling class you can implement prepareStatement method as:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
new Object[] { 123L, "TEST" }) {
@Override
protected void prepareStatement(Object... params) throws SQLException {
stat.setLong(1, Long.class.cast(params[0]));
stat.setString(2, String.valueOf(params[1]));
}
};
ResultSet rs = stat.executeQuery();) {
while (rs.next())
System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
Fragment Listener
If a fragment
needs to communicate events
to the activity
, the fragment
should define an interface
as an inner type and require that the activity
must implement
this interface
:
import android.support.v4.app.Fragment;
public class MyListFragment extends Fragment {
// ...
// Define the listener of the interface type
// listener is the activity itself
private OnItemSelectedListener listener;
// Define the events that the fragment will use to communicate
public interface OnItemSelectedListener {
public void onRssItemSelected(String link);
}
// Store the listener (activity) that will have events fired once the fragment is attached
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
}
// Now we can fire the event when the user selects something in the fragment
public void onSomeClick(View v) {
listener.onRssItemSelected("some link");
}
}
and then in the activity
:
import android.support.v4.app.FragmentActivity;
public class RssfeedActivity extends FragmentActivity implements
MyListFragment.OnItemSelectedListener {
DetailFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssfeed);
fragment = (DetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.detailFragment);
}
// Now we can define the action to take in the activity when the fragment event fires
@Override
public void onRssItemSelected(String link) {
if (fragment != null && fragment.isInLayout()) {
fragment.setText(link);
}
}
}
just do this
try
{
//some code
try
{
int idNumber = function2();
}
finally
{
do stuff here....
}
}
catch(Exception e)
{//... perhaps something here}
For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.
I think the problem is that you are using type="text" instead of textarea. What you want is:
<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>
To clarify, a type="text" will always be one row, where-as a textarea can be multiple.
I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.
Basically, when you have something like:
<form onsubmit="return callSomeFunction();"></form>
or
<a href="#" onclick="return callSomeFunction();"></a>`
and callSomeFunction()
returns true, then the form
or a
will submit, otherwise it won't.
Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.
I found that if you have comments in your build.gradle it may break when you try to add a new support library. So make sure you check your build.gradle and see if it looks alright manually.
When using the MVVM Command pattern for Button function (recommended practice), a simple way to trigger the effect of the Button is as follows:
someButton.Command.Execute(someButton.CommandParameter);
This will use the Command object which the button triggers and pass the CommandParameter defined by the XAML.
Dan, it's just you're accessing the protected field instead of properties.
See for example this line in your Main(...)
:
myClub.distance = Console.ReadLine();
myClub.distance
is the protected field, while you wanted to set the property mydistance.
I'm just giving you some hint, I'm not going to correct your code, since this is homework! ;)
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.
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
Right click on project >> Click on properties >> Java Build Path >> Source >> Add Folder
Hello There is an example:
import numpy as np
import matplotlib.pyplot as ptl
def grafica_seno_coseno():
x = np.arange(-4,2*np.pi, 0.3)
y = 2*np.sin(x)
y2 = 3*np.cos(x)
ptl.plot(x, y, '-gD')
ptl.plot(x, y2, '-rD')
for xitem,yitem in np.nditer([x,y]):
etiqueta = "{:.1f}".format(xitem)
ptl.annotate(etiqueta, (xitem,yitem), textcoords="offset points",xytext=(0,10),ha="center")
for xitem,y2item in np.nditer([x,y2]):
etiqueta2 = "{:.1f}".format(xitem)
ptl.annotate(etiqueta2, (xitem,y2item), textcoords="offset points",xytext=(0,10),ha="center")
ptl.grid(True)
return ptl.show()
The Application class is a singleton that you can access from any activity or anywhere else you have a Context object.
You also get a little bit of lifecycle.
You could use the Application's onCreate method to instantiate expensive, but frequently used objects like an analytics helper. Then you can access and use those objects everywhere.
SELECT CONVERT(INT, 11.4)
RESULT: 11
SELECT CONVERT(INT, 11.6)
RESULT: 11
to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.
delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);
If you need to create a user_id
then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:
rails generate migration AddUserRefToProducts user:references
This command will generate the following migration:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :user, :product, index: true
end
end
After running rake db:migrate
both a user_id
column and an index will be added to the products
table.
In case you just need to add an index to an existing column, e.g. name
of a user
table, the following technique may be helpful:
rails generate migration AddIndexToUsers name:string:index
will generate the following migration:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_index :users, :name
end
end
Delete add_column
line and run the migration.
In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index
command and then delete add_column
line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:
rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references
why has no answer I've seen mentioned anything about the unwrap
method? Or, even easier, the get_text
method
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unwrap http://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text
Do you mean like this?
>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'
I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)
<meta name="304workaround" content="2013-10-24 21:17:23">
Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...
wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install
f
doesn't actually alter the value of x
(which is always the same reference to an instance of a list). Rather, it alters the contents of this list.
In both cases, a copy of a reference is passed to the function. Inside the function,
n
gets assigned a new value. Only the reference inside the function is modified, not the one outside it.x
does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x
’s value is modified.Since both the x
inside the function and outside it refer to the same value, both see the modification. By contrast, the n
inside the function and outside it refer to different values after n
was reassigned inside the function.
We have improved our answer with detail explanation.Now it's more easy to understand about extension method
Extension method: It is a mechanism through which we can extend the behavior of existing class without using the sub classing or modifying or recompiling the original class or struct.
We can extend our custom classes ,.net framework classes etc.
Extension method is actually a special kind of static method that is defined in the static class.
As DateTime
class is already taken above and hence we have not taken this class for the explanation.
Below is the example
//This is a existing Calculator class which have only one method(Add)
public class Calculator
{
public double Add(double num1, double num2)
{
return num1 + num2;
}
}
// Below is the extension class which have one extension method.
public static class Extension
{
// It is extension method and it's first parameter is a calculator class.It's behavior is going to extend.
public static double Division(this Calculator cal, double num1,double num2){
return num1 / num2;
}
}
// We have tested the extension method below.
class Program
{
static void Main(string[] args)
{
Calculator cal = new Calculator();
double add=cal.Add(10, 10);
// It is a extension method in Calculator class.
double add=cal.Division(100, 10)
}
}
If you are going to be changing a String many times, then it is usually more efficient to use a StringBuilder (but measure your performance to find out):
String str = "The rain in Spain falls mainly on the plain";
StringBuilder sb = new StringBuilder(str);
// do your replacing in sb - although you'll find this trickier than simply using String
String newStr = sb.toString();
Every time you do a replace on a String, a new String object is created, because Strings are immutable. StringBuilder is mutable, that is, it can be changed as much as you want.
In Anon's answer:
"If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__
, you must call it yourself, since that will not happen automatically"
It's incredible: he is wording exactly the contrary of the principle of inheritance.
It is not that "something from super's __init__
(...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__
is overriden by the definition of the derived-clas __init__
So then, WHY defining a derived_class' __init__
, since it overrides what is aimed at when someone resorts to inheritance ??
It's because one needs to define something that is NOT done in the base-class' __init__
, and the only possibility to obtain that is to put its execution in a derived-class' __init__
function.
In other words, one needs something in base-class' __init__
in addition to what would be automatically done in the base-classe' __init__
if this latter wasn't overriden.
NOT the contrary.
Then, the problem is that the desired instructions present in the base-class' __init__
are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__
, in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__
.
That's exactly what is said in the official doc:
An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance
That's all the story:
when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__
function in the derived class
when the aim is to REPLACE the initialization performed by the base-class, __init__
must be defined in the derived-class
when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__
must be defined , comprising an explicit call to the base-class __init__
What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.
As long as the script is after the img
, then:
var youtubeimgsrc = document.getElementById("youtubeimg").src;
See getElementById
in the DOM specification.
If the script is before the img
, then of course the img
doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body
element.
Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:
<img id="foo" src="/images/example.png">
...the src
reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com
, document.getElementById("foo").src
would give you "http://www.example.com/images/example.png"
.
If you wanted the src
attribute's content as is, without being resolved, you'd use getAttribute
instead: document.getElementById("foo").getAttribute("src")
. That would give you "/images/example.png"
with my example above.
If you have an absolute URL, like the one in your question, it doesn't matter.
As paxdiablo said make -f pax.mk
would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.
Also you can just type make
if your file name is makefile/Makefile
.
Suppose you have two files named makefile
and Makefile
in the same directory then makefile
is executed if make
alone is given. You can even pass arguments to makefile.
Check out more about makefile at this Tutorial : Basic understanding of Makefile
Note: Since someone claimed that the external link is dead in Sushant Butta's answer I've posted the content here as a separate answer.
Beware of NULLS.
Today I came across a very strange behaviour of query while using IN and NOT IN
operators. Actually I wanted to compare two tables and find out whether a value from table b
existed in table a
or not and find out its behavior if the column containsnull
values. So I just created an environment to test this behavior.
We will create table table_a
.
SQL> create table table_a ( a number);
Table created.
We will create table table_b
.
SQL> create table table_b ( b number);
Table created.
Insert some values into table_a
.
SQL> insert into table_a values (1);
1 row created.
SQL> insert into table_a values (2);
1 row created.
SQL> insert into table_a values (3);
1 row created.
Insert some values into table_b
.
SQL> insert into table_b values(4);
1 row created.
SQL> insert into table_b values(3);
1 row created.
Now we will execute a query to check the existence of a value in table_a
by checking its value from table_b
using IN
operator.
SQL> select * from table_a where a in (select * from table_b);
A
----------
3
Execute below query to check the non existence.
SQL> select * from table_a where a not in (select * from table_b);
A
----------
1
2
The output came as expected. Now we will insert a null
value in the table table_b
and see how the above two queries behave.
SQL> insert into table_b values(null);
1 row created.
SQL> select * from table_a where a in (select * from table_b);
A
----------
3
SQL> select * from table_a where a not in (select * from table_b);
no rows selected
The first query behaved as expected but what happened to the second query? Why didn't we get any output, what should have happened? Is there any difference in the query? No.
The change is in the data of table table_b
. We have introduced a null
value in the table. But how come it's behaving like this? Let's split the two queries into "AND"
and "OR"
operator.
The first query will be handled internally something like this. So a null
will not create a problem here as my first two operands will either evaluate to true
or false
. But my third operand a = null
will neither evaluate to true
nor false
. It will evaluate to null
only.
select * from table_a whara a = 3 or a = 4 or a = null;
a = 3 is either true or false
a = 4 is either true or false
a = null is null
The second query will be handled as below. Since we are using an "AND"
operator and anything other than true
in any of the operand will not give me any output.
select * from table_a whara a <> 3 and a <> 4 and a <> null;
a <> 3 is either true or false
a <> 4 is either true or false
a <> null is null
So how do we handle this? We will pick all the not null
values from table table_b
while using NOT IN
operator.
SQL> select * from table_a where a not in (select * from table_b where b is not null);
A
----------
1
2
So always be careful about NULL
values in the column while using NOT IN
operator.
Beware of NULL!!
That is a simple alert dialog, Federico gave you a site where you can look things up.
Here is a short example of how an alert dialog can be built.
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton(android.R.string.no, null).show();
To create icon you can use Glyphicon in Bootstrap:
<a href="#" class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</a>
And then control size of icon in css:
.glyphicon-menu-hamburger {
font-size: npx;
}
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
ES6 allows a construct where a function argument is specified with a "..." notation such as
function testArgs (...args) {
// Where you can test picking the first element
console.log(args[0]);
}
You can use sys.argv
to get the arguments as a list.
If you need to access individual elements, you can use
sys.argv[i]
where i
is index, 0
will give you the python filename being executed. Any index after that are the arguments passed.
The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:
date_1m_fwd <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1
Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.
Still you can perform the add month using basic R codes as follows:
library(data.table)
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]
Hope it helps.
A simpler but equally effective option would be:
+ theme_bw(base_size=X)
Edit: I had first said:
What's inelegant about the dictionary solution. It seems perfectly elegant to me, esp since you only need to set the comparator in creation of the dictionary.
Of course though, it is inelegant to use something as a key when it's also the value.
Therefore I would use a HashSet. If later operations required indexing, I'd create a list from it when the Adding was done, otherwise, just use the hashset.
A complementary note about CREATE TABLE .. TYPE=""
syntax in SQL dump files
TLDR: If you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
Long story
As it was said by others, the TYPE
argument to CREATE TABLE
has been deprecated for a long time in MySQL. mysqldump
correctly uses the ENGINE
argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40
in versions of mysqldump
up to 5.7).
However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ...
command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE
will actually produce outdated syntax, including the TYPE
argument, if the sqlmode
variable is set to MYSQL40
or MYSQL323
.
Therefore, if you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
These sqlmode
s basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40
, MYSQL323
and several other similar sqlmode
s have themselves been deprecated and are not supported in MySQL 8.0 and higher.
If your server is still configured with these sqlmode
s and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode
locally for that program, by executing SET SESSION sql_mode = 'MYSQL40';
immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.
A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode
(that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode
(as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.
Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement
In Objective C
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(tableView == firstTableView)
{
//code for first table view
[cell.contentView addSubview: someView];
}
if(tableview == secondTableView)
{
//code for secondTableView
[cell.contentView addSubview: someView];
}
return cell;
}
In Swift 3.0
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
if(tableView == firstTableView) {
//code for first table view
}
if(tableview == secondTableView) {
//code for secondTableView
}
return cell
}
I feel you should be using the Consumer interface instead of Function<T, R>
.
A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)
In your case, you can create a consumer elsewhere in your code like this:
Consumer<Integer> myFunction = x -> {
System.out.println("processing value: " + x);
.... do some more things with "x" which returns nothing...
}
Then you can replace your myForEach
code with below snippet:
public static void myForEach(List<Integer> list, Consumer<Integer> myFunction)
{
list.forEach(x->myFunction.accept(x));
}
You treat myFunction as a first-class object.
This will work for the MacOS for Firefox and Chrome:
// opens the default browser tab with the first webpage
driver.get("the url 1");
thread.sleep(2000);
// opens the second tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND + "t");
driver.get("the url 2");
Thread.sleep(2000);
// comes back to the first tab
driver.findElement(By.cssSelector("Body")).sendKeys(Keys.COMMAND, Keys.SHIFT, "{");
REST stands for Representational state transfer.
It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.
REST is often used in mobile applications, social networking Web sites, mashup tools and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations (verbs). Flexibility is provided by assigning resources (nouns) their own unique universal resource indicators (URIs).
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
zip update.zip $(git diff --name-only commit commit)
changing style with jquery
Try This
$('#selector_id').css('display','none');
You can also change multiple attribute in a single query
Try This
$('#replace-div').css({'padding-top': '5px' , 'margin' : '10px'});
This worked for me:
dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();
Shortcut for static import: CTRL + SHIFT + M
Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.
For example, Using @Timeout rule we can set the timeout for all the tests.
public class TestApp {
@Rule
public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);
......
......
}
@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.
public class TempFolderTest {
@Rule
public TemporaryFolder tempFolder= new TemporaryFolder();
@Test
public void testTempFolder() throws IOException {
File folder = tempFolder.newFolder("demos");
File file = tempFolder.newFile("Hello.txt");
assertEquals(folder.getName(), "demos");
assertEquals(file.getName(), "Hello.txt");
}
}
You can see examples of some in-built rules provided by junit at this link.
I have only tested with EditText but you can use the method
public void setBackgroundResource (int resid)
to apply a style defined in an XML file.
Sine this method belongs to View I believe it will work with any UI element.
regards.
Using npm test
doesn't mean Jest is installed globally. It just means "test" is mapped to using Jest in your package.json file.
The following is what worked for me, at the root level of the project:
node_modules/.bin/jest [args]
args
can be the test file you want to run or the directory containing multiple files.
Same as John's answer, but a slightly less verbose extension method.
public static string GetDirectoryPath(this Assembly assembly)
{
string filePath = new Uri(assembly.CodeBase).LocalPath;
return Path.GetDirectoryName(filePath);
}
Now you can do:
var localDir = Assembly.GetExecutingAssembly().GetDirectoryPath();
or if you prefer:
var localDir = typeof(DaoTests).Assembly.GetDirectoryPath();
For me, this was resolved by running this from the dev console: "POST /_cluster/reroute?retry_failed"
.....
I started by looking at the index list to see which indices were red and then ran
"get /_cat/shards?h=[INDEXNAME],shard,prirep,state,unassigned.reason"
and saw that it had shards stuck in ALLOCATION_FAILED state, so running the retry above caused them to re-try the allocation.
You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h
resides, the other issue could be that GameEngine.h
is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA
and ProjectB
, if you are including GameEngine.h
in some source/header file in ProjectA
then to include it properly, assuming that ProjectB
is in the same parent folder do this:
include "../ProjectB/GameEngine.h"
This is if you have a structure like this:
Root\ProjectA
Root\ProjectB <- GameEngine.h actually lives here
do it using jQuery put inside code on the <head></head>
tag
<script type="text/javascript">
$(document).ready(function() {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
}
});
</script>
I found a workaround a week ago. You can use direct commands with "ExecuteCommand
":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand
statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.
You can check Observable represented by Rxjs, lets you return more than one value.
Check this: https://github.com/angular/material2/issues/5808
Since material2 is using flex layout, you can just set fxFlex="40"
(or the value you want for fxFlex) to md-cell
and md-header-cell
.
I just ran the command with sudo:
sudo pip install numpy
Bear in mind that you will be asked for the user's password. This was tested on macOS High Sierra (10.13)
You wouldn't have to put it in the button click hander. If you were, then you'd assign your text box a name (x:Name
) in your view and then use the generated member of the same name in the code behind to set the Text
property.
If you were avoiding code behind, then you would investigate the MVVM design pattern and data binding, and bind a property on your view model to the text box's Text
property.
You could just create an array of the correct size up-front and fill it:
frames = np.empty((480, 640, 3, 100))
for k in xrange(nframes):
frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))
if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).
Just a note, you might consider using a (nframes, 480,640,3)
shaped array, instead.
AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))
You can use system-dependant commands like
Runtime rt = Runtime.getRuntime();
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1)
rt.exec("taskkill " +....);
else
rt.exec("kill -9 " +....);
Dummy data (you should supply this for us)
visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
combine:
visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour
Now do:
ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) +
geom_point() + geom_smooth()
and adjust colours etc to taste.
What you have can be written easier. Instead of:
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
write
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
system("PAUSE");
return 0;
}
The system function executes anything you give it as if it was written in the command prompt. It suspends execution of your program while the command is executing so you can do anything with it, you can even compile programs from your cpp program.
pkill is the easiest command line utility
pkill -f node
or
pkill -f nodejs
whatever name the process runs as for your os
I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
Using requests
import requests
import shutil,os
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder
def ImageDl(url):
attempts = 0
while attempts < 5:#retry 5 times
try:
filename = url.split('/')[-1]
r = requests.get(url,headers=headers,stream=True,timeout=5)
if r.status_code == 200:
with open(os.path.join(path,filename),'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw,f)
print(filename)
break
except Exception as e:
attempts+=1
print(e)
if __name__ == '__main__':
ImageDl(url)
You can use
string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
When $(document).ready(function (){...})
not work after page post back then use JavaScript function pageLoad in Asp.page as follow:
<script type="text/javascript" language="javascript">
function pageLoad() {
// Initialization code here, meant to run once.
}
</script>
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
controller name:
<%= controller.controller_name %>
return => 'users'
action name:
<%= controller.action_name %>
return => 'show'
id:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
return => '23'
Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):
select * from tab
where DateCol between adddate(now(),-7) and now()
If you're searching by an unique index, then using UserModel.count may actually be better for you than UserModel.findOne due to it returning the whole document (ie doing a read) instead of returning just an int.
Modifying Adam Rosenfield's code:
import sys
def send_msg(sock, msg):
size_of_package = sys.getsizeof(msg)
package = str(size_of_package)+":"+ msg #Create our package size,":",message
sock.sendall(package)
def recv_msg(sock):
try:
header = sock.recv(2)#Magic, small number to begin with.
while ":" not in header:
header += sock.recv(2) #Keep looping, picking up two bytes each time
size_of_package, separator, message_fragment = header.partition(":")
message = sock.recv(int(size_of_package))
full_message = message_fragment + message
return full_message
except OverflowError:
return "OverflowError."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
I would, however, heavily encourage using the original approach.
Make the code say if (msg.content === ('trigger') msg.author.send('text')}
You can use this chrome plugin called "Allow-Control-Allow-Origin: *" ... It make it a dead simple and work very well. check it here: *
Based on the most-approved answer, here is yet another way:
var result = !/[\d\D]/.test(string); //[\d\D] will match any character
To remove all files in folder
import os
import glob
files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
os.remove(file)
To remove all folders in a directory
from shutil import rmtree
import os
// os.path.join() # current working directory.
for dirct in os.listdir(os.path.join('path/to/folder')):
rmtree(os.path.join('path/to/folder',dirct))
This is how I did it with Kotlin to show progress with percentage.
My fragment layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/progressBar"/>
</FrameLayout>
My kotlin fragment in onViewCreated
progressBar.max = 100;
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress;
}
}
webView!!.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
progressBar.visibility = View.VISIBLE
progressBar.progress = 0;
super.onPageStarted(view, url, favicon)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view?.loadUrl(request?.url.toString())
}
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
progressBar.visibility = View.GONE
}
}
webView.loadUrl(url)
Response.Redirect()
throws an exception to abort the current request.
This KB article describes this behavior (also for the Request.End()
and Server.Transfer()
methods).
For Response.Redirect()
there exists an overload:
Response.Redirect(String url, bool endResponse)
If you pass endResponse=false, then the exception is not thrown (but the runtime will continue processing the current request).
If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated.
I had the opposite problem (worked in Internet Explorer, but not in Firefox). For Internet Explorer, you need to add left padding, and for Firefox, you need to add transparent color. So here is our combined solution for a 16px x 16px icon button:
input.iconButton
{
font-size: 1em;
color: transparent; /* Fix for Firefox */
border-style: none;
border-width: 0;
padding: 0 0 0 16px !important; /* Fix for Internet Explorer */
text-align: left;
width: 16px;
height: 16px;
line-height: 1 !important;
background: transparent url(../images/button.gif) no-repeat scroll 0 0;
overflow: hidden;
cursor: pointer;
}
open the command prompt Go to project directory
type git remote add origin your git hub repository location with.git
You can get the current path:
string AssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();
Good luck!
I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:
(1 - (oldNumber / newNumber)) * 100
So, the percentage difference from 30 to 40 is:
(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)
The percentage difference from 40 to 30 is:
(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)
In php, I use a function like this:
function calculatePercentage($oldFigure, $newFigure) {
if (($oldFigure != 0) && ($newFigure != 0)) {
$percentChange = (1 - $oldFigure / $newFigure) * 100;
}
else {
$percentChange = null;
}
return $percentChange;
}
Another option is to use a simple hack to get the underlying container std::queue::c
and call clear
on it. This member must be present in std::queue
as per the standard, but is unfortunately protected
. The hack here was taken from this answer.
#include <queue>
template<class ADAPTER>
typename ADAPTER::container_type& get_container(ADAPTER& a)
{
struct hack : ADAPTER
{
static typename ADAPTER::container_type& get(ADAPTER& a)
{
return a .* &hack::c;
}
};
return hack::get(a);
}
template<typename T, typename C>
void clear(std::queue<T,C>& q)
{
get_container(q).clear();
}
#include <iostream>
int main()
{
std::queue<int> q;
q.push(3);
q.push(5);
std::cout << q.size() << '\n';
clear(q);
std::cout << q.size() << '\n';
}
BigInteger.toString(radix)
will do what you want. Just pass in a radix of 2.
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}
QLineEdit::setValidator()
, for example:
myLineEdit->setValidator( new QIntValidator(0, 100, this) );
or
myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );
See: QIntValidator, QDoubleValidator, QLineEdit::setValidator
Just use <c:url>
-tag with an application context relative path.
When the value
parameter starts with an /
, then the tag will treat it as an application relative url, and will add the application-name to the url.
Example:
jsp:
<c:url value="/templates/style/main.css" var="mainCssUrl" />`
<link rel="stylesheet" href="${mainCssUrl}" />
...
<c:url value="/home" var="homeUrl" />`
<a href="${homeUrl}">home link</a>
will become this html, with an domain relative url:
<link rel="stylesheet" href="/AppName/templates/style/main.css" />
...
<a href="/AppName/home">home link</a>
If you want to play with the thread stack size, you'll want to look at the -Xss option on the Hotspot JVM. It may be something different on non Hotspot VM's since the -X parameters to the JVM are distribution specific, IIRC.
On Hotspot, this looks like java -Xss16M
if you want to make the size 16 megs.
Type java -X -help
if you want to see all of the distribution specific JVM parameters you can pass in. I am not sure if this works the same on other JVMs, but it prints all of Hotspot specific parameters.
For what it's worth - I would recommend limiting your use of recursive methods in Java. It's not too great at optimizing them - for one the JVM doesn't support tail recursion (see Does the JVM prevent tail call optimizations?). Try refactoring your factorial code above to use a while loop instead of recursive method calls.
Even i faced the same in CentOS 6.8.
yum reinstall xorg*
End your current session and open another session in tool like mobiXterm. Make sure session has X11 forwarding enabled in the tool.
There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.
If you insist (or really need it), though, you could make a git repository with just mytheme
and myplugins
directories and symlink those from within the WordPress install.
MDCore wrote:
making a commit to, e.g., mytheme will increment the revision number for myplugin
Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.
The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.
Git really really wants you to use separate repositories for separate entities.
Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.
This also happens (and is particularly confounding) if you forgot that you created a Windows symlink to a different directory, and that other directory doesn't have appropriate permissions.
You can use:
element = driver.find_element_by_class_name("class_name").text
This will return the text within the element and will allow you to verify it after that.
For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
.Select(m => new {
ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
CatId = m.c.CatId
// other assignments
});
If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.
Also, you could throw the Select
into the last lambda of the second Join
(again, provided there are no other operations that depend on the join results) which would give:
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
ProdId = ppc.p.Id, // or ppc.pc.ProdId
CatId = c.CatId
// other assignments
});
...and making a last attempt to sell you on query syntax, this would look like this:
var categorizedProducts =
from p in product
join pc in productcategory on p.Id equals pc.ProdId
join c in category on pc.CatId equals c.Id
select new {
ProdId = p.Id, // or pc.ProdId
CatId = c.CatId
// other assignments
};
Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)
A form submission causes the page to navigate away to the action
of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit()
on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
Brian's answer (a custom function) is the correct and simplest thing to do in general.
But if you really wanted to define a numeric type with a (non-standard) '%' operator, like desk calculators do, so that 'X % Y' means X * Y / 100.0, then from Python 2.6 onwards you can redefine the mod() operator:
import numbers
class MyNumberClasswithPct(numbers.Real):
def __mod__(self,other):
"""Override the builtin % to give X * Y / 100.0 """
return (self * other)/ 100.0
# Gotta define the other 21 numeric methods...
def __mul__(self,other):
return self * other # ... which should invoke other.__rmul__(self)
#...
This could be dangerous if you ever use the '%' operator across a mixture of MyNumberClasswithPct with ordinary integers or floats.
What's also tedious about this code is you also have to define all the 21 other methods of an Integral or Real, to avoid the following annoying and obscure TypeError when you instantiate it
("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__, __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__, __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__, __rpow__, __rtruediv__, __truediv__, __trunc__")
If you only want to return a few characters of your long string, you can use:
select
left(col, 15) + '...' col
from yourtable
See SQL Fiddle with Demo.
This will return the first 15 characters of the string and then concatenates the ...
to the end of it.
If you want to to make sure than strings less than 15 do not get the ...
then you can use:
select
case
when len(col)>=15
then left(col, 15) + '...'
else col end col
from yourtable
One of the (optional) arguments to the JVM is the stack size. It's -Xss. I don't know what the default value is, but if the total amount of stuff on the stack exceeds that value, you'll get that error.
Generally, infinite recursion is the cause of this, but if you were seeing that, your stack trace would have more than 5 frames.
Try adding a -Xss argument (or increasing the value of one) to see if this goes away.
First, some similarities that have not been mentioned yet. Ruby supports open classes, but modules as open too. After all, Class inherits from Module in the Class inheritance chain and so Class and Module do have some similar behavior.
But you need to ask yourself what is the purpose of having both a Class and a Module in a programming language? A class is intended to be a blueprint for creating instances, and each instance is a realized variation of the blueprint. An instance is just a realized variation of a blueprint (the Class). Naturally then, Classes function as object creation. Furthermore, since we sometimes want one blueprint to derive from another blueprint, Classes are designed to support inheritance.
Modules cannot be instantiated, do not create objects, and do not support inheritance. So remember one module does NOT inherit from another!
So then what is the point of having Modules in a language? One obvious usage of Modules is to create a namespace, and you will notice this with other languages too. Again, what's cool about Ruby is that Modules can be reopened (just as Classes). And this is a big usage when you want to reuse a namespace in different Ruby files:
module Apple
def a
puts 'a'
end
end
module Apple
def b
puts 'b'
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c527c98>
> f.a
=> a
> f.b
=> b
But there is no inheritance between modules:
module Apple
module Green
def green
puts 'green'
end
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c462420>
> f.green
NoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>
The Apple module did not inherit any methods from the Green module and when we included Apple in the Fruit class, the methods of the Apple module are added to the ancestor chain of Apple instances, but not methods of the Green module, even though the Green module was defined in the Apple module.
So how do we gain access to the green method? You have to explicitly include it in your class:
class Fruit
include Apple::Green
end
=> Fruit
> f.green
=> green
But Ruby has another important usage for Modules. This is the Mixin facility, which I describe in another answer on SO. But to summarize, mixins allow you to define methods into the inheritance chain of objects. Through mixins, you can add methods to the inheritance chain of object instances (include) or the singleton_class of self (extend).
You could do this with partial application, although using named variables definitely leads to more readable code. John Resig wrote a blog article in 2008 about how to do it in JavaScript: http://ejohn.org/blog/partial-functions-in-javascript/
Function.prototype.partial = function(){
var fn = this, args = Array.prototype.slice.call(arguments);
return function(){
var arg = 0;
for ( var i = 0; i < args.length && arg < arguments.length; i++ )
if ( args[i] === undefined )
args[i] = arguments[arg++];
return fn.apply(this, args);
};
};
It would probably be possible to apply the same principle in Ruby (except for the prototypal inheritance).
When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:
http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake
If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:
http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx
In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:
In the Powershell, cd to the .exe file location. For example:
cd C:\Users\Administrators\Downloads
PS C:\Users\Administrators\Downloads> & '.\aaa.exe'
The installer pops up and follow the instruction on the screen.
Response BASED on @Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,
ACTIONS:
only use openSession()
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);
// and so on, ...
}
}
function phpVersionAtLeast($strVersion = '0.0.0')
{
$version = explode('.', $strVersion);
$questionVer = $version[0] * 10000 + $version[1] * 100 + $version[2];
if(PHP_VERSION_ID >= $questionVer)
return true;
else
return false;
}
function openSession()
{
if(phpVersionAtLeast('5.4.0'))
{
if(session_status()==PHP_SESSION_NONE)
session_start();
}
else // under 5.4.0
{
if(session_id() == '')
session_start();
}
}
I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn't have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys.
There's the %
sign. It's not just for the remainder, it is the modulo operation.
I got a similar error (Incorrect string value: '\xD0\xBE\xDO\xB2. ...' for 'content' at row 1
). I have tried to change character set of column to utf8mb4
and after that the error has changed to 'Data too long for column 'content' at row 1'
.
It turned out that mysql shows me wrong error. I turned back character set of column to utf8
and changed type of the column to MEDIUMTEXT
. After that the error disappeared.
I hope it helps someone.
By the way MariaDB in same case (I have tested the same INSERT there) just cut a text without error.
If your iframe's URL does not change, you can just recreate it.
If your iframe is not from the same origin (protocol scheme, hostname and port), you will not be able to know the current URL in the iframe, so you will need a script in the iframe document to exchange messages with its parent window (the page's window).
In the iframe document:
window.addEventListener('change', function(e) {
if (e.data === 'Please reload yourself') {
var skipCache = true; // true === Shift+F5
window.location.reload(skipCache);
}
}
In your page:
var iframe = document.getElementById('my-iframe');
var targetOrigin = iframe.src; // Use '*' if you don't care
iframe.postMessage('Please reload yourself', targetOrigin);
CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)
RETURNS VARCHAR(24)
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END
You can do this via local storage API. Note that this works only between 2 tabs. you can't put both sender and receiver on the same page:
On sender page:
localStorage.setItem("someKey", "someValue");
On the receiver page
$(document).ready(function () {
window.addEventListener('storage', storageEventHandler, false);
function storageEventHandler(evt) {
alert("storage event called key: " + evt.key);
}
});
It turns out the issue is due to the wrong path of node in system variable. The path is currently pointing to
(I really don't know when I modified it)
C:\Program Files\nodejs\node_modules\npm\bin
so I change to
C:\Program Files\nodejs
and it works like a charm.
$query = "SELECT col1,col2,col3 FROM table WHERE id > 100"
$result = mysql_query($query);
if(mysql_num_rows($result)>0)
{
while($row = mysql_fetch_array()) //here you can use many functions such as mysql_fetch_assoc() and other
{
//It returns 1 row to your variable that becomes array and automatically go to the next result string
Echo $row['col1']."|".Echo $row['col2']."|".Echo $row['col2'];
}
}
One-line solution:
df.join(
df.groupby('state').agg(state_total=('sales', 'sum')),
on='state'
).eval('sales / state_total')
This returns a Series of per-office ratios -- can be used on it's own or assigned to the original Dataframe.
Just follow the requirements listed on the project's page: https://pypi.org/project/pgmagick/
Below is my solution - taking into account that the diffed tables can have duplicate rows. The accepted answer does not take this into account which would give you wrong results in case of duplicates. I am taking care of duplicate rows by numbering them using row_number() and then comparing the numbered rows:
-- TEST TABLES
create table t1 (col_num number,col_date date,col_varchar varchar2(400));
create table t2 (col_num number,col_date date,col_varchar varchar2(400));
-- TEST DATA
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am in both');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am in both');
insert into t1 values (null,null,'I am in both with nulls');
insert into t2 values (null,null,'I am in both with nulls');
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am in T1 only');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am in T2 only');
insert into t1 values (null,null,'I am in T1 only with nulls');
insert into t2 values (null,null,'I am in T2 only with nulls');
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T1 but not in T2');
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T1 but not in T2');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T2 but not in T1');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T2 but not in T1');
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T1 and once in T2');
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T1 and once in T2');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T1 and once in T2');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T2 and once in T1');
insert into t2 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T2 and once in T1');
insert into t1 values (1,TO_DATE ('01.JAN.3000 00:00:00', 'DD.MON.YYYY HH24:MI:SS'),'I am twice in T2 and once in T1');
-- THE DIFF
-- All columns need to be named in the partition by clause, it is not possible to just say 'partition by *'
-- The column used in the order by clause does not matter in terms of functionality
(
select 'In T1 but not in T2' diff,s.* from (
select row_number() over (partition by col_num,col_date,col_varchar order by col_num) rn,t.* from t1 t
minus
select row_number() over (partition by col_num,col_date,col_varchar order by col_num) rn,t.* from t2 t
) s
) union all (
select 'In T2 but not in T1' diff,s.* from (
select row_number() over (partition by col_num,col_date,col_varchar order by col_num) rn,t.* from t2 t
minus
select row_number() over (partition by col_num,col_date,col_varchar order by col_num) rn,t.* from t1 t
) s
);
The best way is to use simple math
>>> a = 8
>>> a**(1./3.)
2.0
EDIT
For Negative numbers
>>> a = -8
>>> -(-a)**(1./3.)
-2.0
Complete Program for all the requirements as specified
x = int(input("Enter an integer: "))
if x>0:
ans = x**(1./3.)
if ans ** 3 != abs(x):
print x, 'is not a perfect cube!'
else:
ans = -((-x)**(1./3.))
if ans ** 3 != -abs(x):
print x, 'is not a perfect cube!'
print 'Cube root of ' + str(x) + ' is ' + str(ans)
You can try installing one of the following localhost softwares:
There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com
)
Got similar issue while trying Azure Sample first-serverless-app.
Here is the info of how i resolved by removing \ at front of $web.
Note: $web container was created automatically while enable static website. Never seen $root container anywhere.
//getting Invalid URI error while following tutorial as-is
az storage blob upload-batch -s . -d \$web --account-name firststgaccount01
//Remove "\" @destination param
az storage blob upload-batch -s . -d $web --account-name firststgaccount01
Your .eslintrc.json should contain the text below.
This way ESLint knows about your global variables.
{
"env": {
"browser": true,
"node": true
}
}
For me, installing development version of libyaml did it.
yum install libyaml-devel #centos
apt-get install libyaml-dev # ubuntu
in web app java spring what worked for me
cron="0 0/30 * * * ?"
This will trigger on for example 10:00AM then 10:30AM etc...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<beans profile="cron">
<bean id="executorService" class="java.util.concurrent.Executors" factory-method="newFixedThreadPool">
<beans:constructor-arg value="5" />
</bean>
<task:executor id="threadPoolTaskExecutor" pool-size="5" />
<task:annotation-driven executor="executorService" />
<beans:bean id="expireCronJob" class="com.cron.ExpireCron"/>
<task:scheduler id="serverScheduler" pool-size="5"/>
<task:scheduled-tasks scheduler="serverScheduler">
<task:scheduled ref="expireCronJob" method="runTask" cron="0 0/30 * * * ?"/> <!-- every thirty minute -->
</task:scheduled-tasks>
</beans>
</beans>
I dont know why but this is working on my local develop and production, but other changes if i made i have to be careful because it may work local and on develop but not on production
Just to add completness to the above selected answer, one can also go the 'Project Setting' windows (if not on the Welcome screen) in IntelliJ IDEA by clicking:
File > Project Structure (Ctrl + Alt + Shift + S)
And can define Project SDK there!
What about this:
function recursiveDelete($dirPath, $deleteParent = true){
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
$path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
}
if($deleteParent) rmdir($dirPath);
}
In C# 8 the new Ranges feature can be used...
value = value[..Math.Min(30, value.Length)];
Instead of using the full plugin name (with groupId) like described in Bartosz's answer, you could add
<pluginGroups>
<pluginGroup>org.springframework.boot</pluginGroup>
</pluginGroups>
to your .m2/settings.xml.
Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:
version: '2'
services:
mysql:
container_name: mysql
image: mysql:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
ports:
- "3306:3306"
networks:
vpcbr:
ipv4_address: 10.5.0.5
apigw-tomcat:
container_name: apigw-tomcat
build: tomcat/.
ports:
- "8080:8080"
- "8009:8009"
networks:
vpcbr:
ipv4_address: 10.5.0.6
depends_on:
- mysql
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 10.5.0.0/16
gateway: 10.5.0.1
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}
Try this:
par(adj = 0)
plot(1, 1, main = "Title")
or equivalent:
plot(1, 1, main = "Title", adj = 0)
adj = 0
produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1]
is allowed.
However, the issue is that this will also change the position of the label of the x-axis and y-axis.
for i,j in dictionary .items():
if i=='C1':
c=[]
for k in j:
j=k+10
c.append(j)
dictionary .update({i:c})
To get the value:
$query = $this->db->query("YOUR QUERY");
Then, for single row from(in controller):
$query1 = $query->row();
$data['product'] = $query1;
In view, you can use your own code (above code)
HTTP and redirects
Let's first recap how ASP.NET MVC works:
Let's also remind ourselves what a redirect is:
An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location
header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult
from an action.
Passing data
If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location
header. This is what would happen if you used something like
return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });
as others have suggested
The reason that this will not work is that the XDocument
is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument
action parameter.
In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.
Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.
Storing data for retrieval on the next request
So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session
(or TempData
, which is more or less the same as the Session
in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:
int documentId = _myDocumentRepository.Save(updatedResultsDocument);
and then you return that key to the client:
return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });
When you want to retrieve the document, you simply fetch it based on the key:
public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);
ConfirmationModel model = new ConfirmationModel(doc);
return View(model);
}
It doesn't - the C# compiler does :)
So this code:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
actually gets compiled as:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
(Gah - intervening edit removed other bits accidentally.)
The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y
which then needs to be copied again as part of the concatenation of (x + y)
and z
. Instead, we get it all done in one go.
EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:
string x = "";
foreach (string y in strings)
{
x += y;
}
just ends up as equivalent to:
string x = "";
foreach (string y in strings)
{
x = string.Concat(x, y);
}
... so this does generate a lot of garbage, and it's why you should use a StringBuilder
for such cases. I have an article going into more details about the two which will hopefully answer further questions.
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
For me, view.window
is null on iOS 14.
extension UIViewController {
var topBarHeight: CGFloat {
var top = self.navigationController?.navigationBar.frame.height ?? 0.0
if #available(iOS 13.0, *) {
top += UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
} else {
top += UIApplication.shared.statusBarFrame.height
}
return top
}
}
Also you can take a look into StringUtils library. It has a bunch of cool stuff.
In most cases you want simple ArrayList
- an implementation of List
Before JDK version 7
List<String> list = new ArrayList<String>();
JDK 7 and later you can use the diamond operator
List<String> list = new ArrayList<>();
Further informations are written here Oracle documentation - Collections
Move import sys
outside of the try
-except
block:
import sys
try:
# ...
except ImportError:
# ...
If any of the imports before the import sys
line fails, the rest of the block is not executed, and sys
is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.
sys
is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys
fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).
There is a way to do it using reflection. It works with .NET 4.0. It accesses a private field and may not work in other versions of .NET without modifications.
I have no idea why Microsoft did not expose this field with a property.
private static int GetStatusCode(WebClient client, out string statusDescription)
{
FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic);
if (responseField != null)
{
HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse;
if (response != null)
{
statusDescription = response.StatusDescription;
return (int)response.StatusCode;
}
}
statusDescription = null;
return 0;
}
I tweaked your code a bit and made it more robust. In terms of progressive enhancement it's probaly better to have all the fade-in-out logic in JavaScript. In the example of myfunksyde any user without JavaScript sees nothing because of the opacity: 0;
.
$(window).on("load",function() {
function fade() {
var animation_height = $(window).innerHeight() * 0.25;
var ratio = Math.round( (1 / animation_height) * 10000 ) / 10000;
$('.fade').each(function() {
var objectTop = $(this).offset().top;
var windowBottom = $(window).scrollTop() + $(window).innerHeight();
if ( objectTop < windowBottom ) {
if ( objectTop < windowBottom - animation_height ) {
$(this).html( 'fully visible' );
$(this).css( {
transition: 'opacity 0.1s linear',
opacity: 1
} );
} else {
$(this).html( 'fading in/out' );
$(this).css( {
transition: 'opacity 0.25s linear',
opacity: (windowBottom - objectTop) * ratio
} );
}
} else {
$(this).html( 'not visible' );
$(this).css( 'opacity', 0 );
}
});
}
$('.fade').css( 'opacity', 0 );
fade();
$(window).scroll(function() {fade();});
});
See it here: http://jsfiddle.net/78xjLnu1/16/
Cheers, Martin
Yes, it is a non-type parameter. You can have several kinds of template parameters
What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:
Template type parameter:
template<typename T>
struct Container {
T t;
};
// pass type "long" as argument.
Container<long> test;
Template integer parameter:
template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};
// pass 3 as argument.
Vector<3> test;
Template pointer parameter (passing a pointer to a function)
template<void (*F)()>
struct FunctionWrapper {
static void call_it() { F(); }
};
// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;
Template reference parameter (passing an integer)
template<int &A>
struct SillyExample {
static void do_it() { A = 10; }
};
// pass flag as argument
int flag;
SillyExample<flag> test;
Template template parameter.
template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};
// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;
A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:
template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};
Vector<> test;
Syntactically, template<>
is reserved to mark an explicit template specialization, instead of a template without parameters:
template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};
For everyone struggling with this issue, you simply need to upgrade your openssl installation. I'm running windows 10, installed the latest anaconda 64-bit and am getting this error when I try to install/upgrade anything with 'conda' or 'pip'. If I uninstall the 64-bit anaconda and install the 32-bit, it works fine. I had a 64-bit version of openssl for windows installed, version 1.1.0 something. I uninstalled that and installed the latest I could find from here: https://slproweb.com/products/Win32OpenSSL.html -- there is a 64-bit version of 1.1.1 on there that worked. Now I can install packages via pip and conda successfully. Hope this helps.
You will find this wrapper usefull :)
var pool = mysql.createPool(config.db);
exports.connection = {
query: function () {
var queryArgs = Array.prototype.slice.call(arguments),
events = [],
eventNameIndex = {};
pool.getConnection(function (err, conn) {
if (err) {
if (eventNameIndex.error) {
eventNameIndex.error();
}
}
if (conn) {
var q = conn.query.apply(conn, queryArgs);
q.on('end', function () {
conn.release();
});
events.forEach(function (args) {
q.on.apply(q, args);
});
}
});
return {
on: function (eventName, callback) {
events.push(Array.prototype.slice.call(arguments));
eventNameIndex[eventName] = callback;
return this;
}
};
}
};
Require it, use it like this:
db.connection.query("SELECT * FROM `table` WHERE `id` = ? ", row_id)
.on('result', function (row) {
setData(row);
})
.on('error', function (err) {
callback({error: true, err: err});
});
The file:
URL scheme refers to a file on the client machine. There is no hostname in the file:
scheme; you just provide the path of the file. So, the file on your local machine would be file:///~User/2ndFile.html
. Notice the three slashes; the hostname part of the URL is empty, so the slash at the beginning of the path immediately follows the double slash at the beginning of the URL. You will also need to expand the user's path; ~
does no expand in a file:
URL. So you would need file:///home/User/2ndFile.html
(on most Unixes), file:///Users/User/2ndFile.html
(on Mac OS X), or file:///C:/Users/User/2ndFile.html
(on Windows).
Many browsers, for security reasons, do not allow linking from a file that is loaded from a server to a local file. So, you may not be able to do this from a page loaded via HTTP; you may only be able to link to file:
URLs from other local pages.
Objective - C
NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding];
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);
Swift
//This your data containing the string
let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)
//Use this method to convert the data into String
let myStringFromData = String(data:myStringData!, encoding: NSUTF8StringEncoding)
print("My string value:" + myStringFromData!)
http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html
It's just a different syntax. Instead of
foreach ($a as $v) {
# ...
}
You could write this:
foreach ($a as $v):
# ...
endforeach;
They will function exactly the same; it's just a matter of style. (Personally I have never seen anyone use the second form.)
The page.github.com does mention:
Github Pages are hosted free and easily published through our site,
Without ever mentioning access control.
The GitHub page help doesn't mention any ACL either.
They are best managed in a gh-pages branch, and can be managed in their own submodule.
But again, without any restriction in term of visibility once published by GitHub.
From version 1.7 and later it should be:
git diff --staged
Your array is quite strange : why not just use the key
as index, and the value
as... the value ?
Wouldn't it be a lot easier if your array was declared like this :
$array = array(
1 => 'Awaiting for Confirmation',
2 => 'Asssigned',
3 => 'In Progress',
4 => 'Completed',
5 => 'Mark As Spam',
);
That would allow you to use your values of key
as indexes to access the array...
And you'd be able to use functions to search on the values, such as array_search()
:
$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);
$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);
var_dump($array);
Easier than with your array, no ?
Instead, with your array that looks like this :
$array = array(
array('key' => 1, 'value' => 'Awaiting for Confirmation'),
array('key' => 2, 'value' => 'Asssigned'),
array('key' => 3, 'value' => 'In Progress'),
array('key' => 4, 'value' => 'Completed'),
array('key' => 5, 'value' => 'Mark As Spam'),
);
You'll have to loop over all items, to analyse the value
, and unset the right items :
foreach ($array as $index => $data) {
if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
unset($array[$index]);
}
}
var_dump($array);
Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?
Percent encoding. Replace the hash with %23
.
Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (.matplotlib/matplotlibrc
) in you home directory.
To set the backend in code you can do
import matplotlib
matplotlib.use('Agg')
where 'Agg' is the name of the backend. Which backends are present depend on your installation and OS.
http://matplotlib.sourceforge.net/faq/installing_faq.html#backends
For .Net 4.5+
It is not always desired to write the uncompressed file to disk. As an ASP.Net developer, I would have to fiddle with permissions to grant rights for my application to write to the filesystem. By working with streams in memory, I can sidestep all that and read the files directly:
using (ZipArchive archive = new ZipArchive(postedZipStream))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var stream = entry.Open();
//Do awesome stream stuff!!
}
}
Alternatively, you can still write the decompressed file out to disk by calling ExtractToFile()
:
using (ZipArchive archive = ZipFile.OpenRead(pathToZip))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
entry.ExtractToFile(Path.Combine(destination, entry.FullName));
}
}
To use the ZipArchive
class, you will need to add a reference to the System.IO.Compression
namespace and to System.IO.Compression.FileSystem
.
simple enough; just run (at the vs command prompt)
xsd your.xsd /classes
(which will create your.cs
). Note, however, that most of the intrinsic options here haven't changed much since 2.0
For the options, use xsd /?
or see MSDN; for example /enableDataBinding
can be useful.
Looks like divs will not go outside of their body's width. Even within another div.
I threw this up to test (without a doctype though) and it does not work as thought.
.slideContainer {_x000D_
overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
<div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
<div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
<div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.
or you can
SELECT
String_to_array(CASE
WHEN <condition 1> THEN a1||','||b1
WHEN <condition 2> THEN a2||','||b2
ELSE a3||','||b3
END, ',') K
FROM <table>
Came here in search of how to build json strings ad-hoc (without serializing a class/object) in C#. In other words, how to escape braces and quotes while using Interpolated Strings in C# and "verbatim string literals" (double quoted strings with '@' prefix), like...
var json = $@"{{""name"":""{name}""}}";
Run:
go mod init yellow
Then create a file yellow.go
:
package yellow
func Mix(s string) string {
return s + "Yellow"
}
Then create a file orange/orange.go
:
package main
import "yellow"
func main() {
s := yellow.Mix("Red")
println(s)
}
Then build:
go build
LEFT OUTER JOIN just like INNER JOIN (normal join) will return as many results for each row in left table as many matches it finds in the right table. Hence you can have a lot of results - up to N x M, where N is number of rows in left table and M is number of rows in right table.
It's the minimum number of results is always guaranteed in LEFT OUTER JOIN to be at least N.
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
See following snippet :
$(document).on("click", "a.deleteText", function() {_x000D_
if (confirm('Are you sure ?')) {_x000D_
$(this).prev('span.text').remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<span class="text">some text</span>_x000D_
<a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
Most of the time, these type of issues happen due to incorrect java version. Make sure your PATH and JAVA_HOME variables are pointing to the correct version.
Remember when you used to sum, for example 2 & 3, in your old calculator and every time you hit the =
you see 3 added to the total, the +=
does similar job. Example:
>>> orange = 2
>>> orange += 3
>>> print(orange)
5
>>> orange +=3
>>> print(orange)
8
Solution using the destructuring assignment syntax of ES6:
var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };_x000D_
var { [Object.keys(temp).pop()]: lastItem } = temp;_x000D_
console.info(lastItem); //"carrot"
_x000D_
Remove constraint not null
to null
ALTER TABLE 'test' CHANGE COLUMN 'testColumn' 'testColumn' datatype NULL;
In JSF I used:
<h:head>
<f:facet name="first">
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
</f:facet>
<!-- ... other meta tags ... -->
</h:head>
For laravel 5
{!!html_entity_decode($text)!!}
Figured out through this link, see RachidLaasri answer
Serialization:
// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);
Response.Write(jsonData);
Deserialization::
To deserialize a dynamic object
string json = @"{
'Name': 'name',
'Description': 'des'
}";
var res = JsonConvert.DeserializeObject< dynamic>(json);
Response.Write(res.Name);
Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.
Following the greenhoorn's answer, you can use "Extensions" like this:
public static class HttpClientExtensions
{
public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
{
//int timeoutSec = 90;
//cl.Timeout = new TimeSpan(0, 0, timeoutSec);
string contentType = "application/json";
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
var userAgent = "d-fens HttpClient";
cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
return cl;
}
}
And use:
string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
GROUP BY grade.gradeId
ORDER BY exam.date
Use the setAttribute
method:
document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");
But you really should be using data followed with a dash and with its property, like:
<li ... data-icon="base.gif" ...>
And to do it in JS use the dataset
property:
document.getElementById('item1').dataset.icon = "base.gif";
echo "Hi All" | tr "[:upper:]" "[:lower:]"
This should work. You can get body using response.json() if its a json response.
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res: Response.json()) => {
console.log(res);
})
In visual studio 2015
, goto->view->formatting marks
, unselect show
If you check Dockerfile from containers, for example fballiano/magento2-apache-php
you'll see that at the end of his file he adds the following command: while true; do sleep 1; done
Now, what I recommend, is that you do this
docker container ls --all | grep 127
Then, you will see if your docker image had an error, if it exits with 0, then it probably needs one of these commands that will sleep forever.
Try this
ALTER TABLE `table_name` CHANGE `column_name` `column_name` data_type NULL DEFAULT '';
like this
ALTER TABLE `drivers_meta` CHANGE `driving_license` `driving_license` VARCHAR(30) NULL DEFAULT '';