In my case it was a proxy issue (requests proxied from nginx to a varnish cache) that caused the issue. I needed to add the following to my proxy definition
proxy_set_header Connection keep-alive;
I found the answer here: https://stackoverflow.com/a/55341260/1062129
A previous answer using LPAD()
is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.
UPDATE
mytable
SET
mycolumn = CONCAT(
REPEAT(
"0",
8 - LENGTH(mycolumn)
),
mycolumn
)
WHERE
LENGTH(mycolumn) < 8;
From grep --help
, but also see man grep:
Exit status is 0 if any line was selected, 1 otherwise; if any error occurs and -q was not given, the exit status is 2.
if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
echo exists
else
echo not found
fi
You may want to use a more specific regex, such as ^MYSQL_ROLE=master$
, to avoid that string in comments, names that merely start with "master", etc.
This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.
Step 1: Start button -> Computer menu item -> Properties on right click menu item -> Advanced System Settings button on left panel -> Advanced tab in System Properties dialog -> Environment Variables button -> System variables table
Step 2: Add MAVEN_HOME variable
Step 3: Update PATH variable
Step 4: Make sure you have JAVA_HOME variable correctly
step 5: open console and check below command
mvn -v
Here is the Angular version of LightBox. Just Awesome :)
Note : I have put this answer hence No Js library has been mentioned under the Tags.
<ul ng-controller="GalleryCtrl">
<li ng-repeat="image in images">
<a ng-click="openLightboxModal($index)">
<img ng-src="{{image.thumbUrl}}" class="img-thumbnail">
</a>
</li>
</ul>
When you create your Sequelize object, pass false
to the logging
parameter:
var sequelize = new Sequelize('database', 'username', 'password', {
// disable logging; default: console.log
logging: false
});
For more options, check the docs.
Could you try this out?
=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0)
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)
Note: Setting Hidden to False will make the row visible
The ffmpeg wiki links back to this page in reference to "How to split video efficiently". I'm not convinced this page answers that question, so I did as @AlcubierreDrive suggested…
echo "Two commands"
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 -sn test1.mkv
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test2.mkv
echo "One command"
time ffmpeg -v quiet -y -i input.ts -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 \
-sn test3.mkv -vcodec copy -acodec copy -ss 00:30:00 -t 01:00:00 -sn test4.mkv
Which outputs...
Two commands
real 0m16.201s
user 0m1.830s
sys 0m1.301s
real 0m43.621s
user 0m4.943s
sys 0m2.908s
One command
real 0m59.410s
user 0m5.577s
sys 0m3.939s
I tested a SD & HD file, after a few runs & a little maths.
Two commands SD 0m53.94 #2 wins
One command SD 0m49.63
Two commands SD 0m55.00
One command SD 0m52.26 #1 wins
Two commands SD 0m58.60 #2 wins
One command SD 0m58.61
Two commands SD 0m54.60
One command SD 0m50.51 #1 wins
Two commands SD 0m53.94
One command SD 0m49.63 #1 wins
Two commands SD 0m55.00
One command SD 0m52.26 #1 wins
Two commands SD 0m58.71
One command SD 0m58.61 #1 wins
Two commands SD 0m54.63
One command SD 0m50.51 #1 wins
Two commands SD 1m6.67s #2 wins
One command SD 1m20.18
Two commands SD 1m7.67
One command SD 1m6.72 #1 wins
Two commands SD 1m4.92
One command SD 1m2.24 #1 wins
Two commands SD 1m1.73
One command SD 0m59.72 #1 wins
Two commands HD 4m23.20
One command HD 3m40.02 #1 wins
Two commands SD 1m1.30
One command SD 0m59.59 #1 wins
Two commands HD 3m47.89
One command HD 3m29.59 #1 wins
Two commands SD 0m59.82
One command SD 0m59.41 #1 wins
Two commands HD 3m51.18
One command HD 3m30.79 #1 wins
SD file = 1.35GB DVB transport stream
HD file = 3.14GB DVB transport stream
The single command is better if you are handling HD, it agrees with the manuals comments on using -ss after the input file to do a 'slow seek'. SD files have a negligible difference.
The two command version should be quicker by adding another -ss before the input file for the a 'fast seek' followed by the more accurate slow seek.
It may be the case that you have some ambiguity in your ViewData:
Take a look Here
If you want a fixed size website this should be fairly simple:
// Override container sizes_x000D_
@container-sm: 700px;_x000D_
@container-md: 700px;_x000D_
@container-lg: 700px;_x000D_
_x000D_
// Fixate media queries to tablet view only (lower viewports set to 0px, desired one to 1px, and the higher to ~9999px)_x000D_
_x000D_
@screen-xs-min: 0px;_x000D_
@screen-sm-min: 1px;_x000D_
@screen-md-min: 9999px;_x000D_
@screen-lg-min: 9999px;_x000D_
_x000D_
// Disable responsive features such as navbar-collapse_x000D_
@grid-float-breakpoint: 9999px;
_x000D_
Unless you are using .container-fluid, then also add:
.container-fluid {
width: 700px;
}
body {
width: 700px + @general-min-width;
}
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace OTL
{
/// <summary>
/// Before usage: Define your class, sample:
/// [DataContract]
///public class MusicInfo
///{
/// [DataMember(Name="music_name")]
/// public string Name { get; set; }
/// [DataMember]
/// public string Artist{get; set;}
///}
/// </summary>
/// <typeparam name="T"></typeparam>
public class OTLJSON<T> where T : class
{
/// <summary>
/// Serializes an object to JSON
/// Usage: string serialized = OTLJSON<MusicInfo>.Serialize(musicInfo);
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public static string Serialize(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// Usage: MusicInfo deserialized = OTLJSON<MusicInfo>.Deserialize(json);
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static T Deserialize(string json)
{
if (string.IsNullOrEmpty(json))
throw new Exception("Json can't empty");
else
try
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(T));
return serializer.ReadObject(stream) as T;
}
}
catch (Exception e)
{
throw new Exception("Json can't convert to Object because it isn't correct format.");
}
}
}
}
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
Try this Toggle Buttons
test_activity.xml
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="100px"
android:layout_height="50px"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>
Test.java
public class Test extends Activity {
private ToggleButton togglebutton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}
public void toggleclick(View v){
if(togglebutton.isChecked())
Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
else
Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
}
}
If you happen to be using Windows 8 and up, here's how to get to it:
The newer Microsoft SQL Server Configuration Manager is a snap-in for the Microsoft Management Console program.
It is not a stand-alone program as used in the previous versions of Microsoft Windows operating systems.
SQL Server Configuration Manager doesn’t appear as an application when running Windows 8.
To open SQL Server Configuration Manager, in the Search charm, under Apps, type:
SQLServerManager15.msc
for [SQL Server 2019] or
SQLServerManager14.msc
for [SQL Server 2017] or
SQLServerManager13.msc
for [SQL Server 2016] or
SQLServerManager12.msc
for [SQL Server 2014] or
SQLServerManager11.msc
for [SQL Server 2012] or
SQLServerManager10.msc
for [SQL Server 2008], and then press Enter.
Text kindly reproduced from SQL Server Configuration Manager changes in Windows 8
Detailed info from MSDN: SQL Server Configuration Manager
Did a quick google. Seems that to find the file size you do this,
long size = f.length();
The differences between the three methods you posted can be found here
getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.
Using tidyverse
df %>% tidyr::gather("id", "value", 1:4) %>%
ggplot(., aes(Xax, value))+
geom_point()+
geom_smooth(method = "lm", se=FALSE, color="black")+
facet_wrap(~id)
DATA
df<- read.table(text =c("
A B C G Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0.425 0.819 0.077 0.281 0.34
0.457 0.429 0.053 0.386 0.53
0.436 0.524 0.049 0.249 0.12
0.423 0.270 0.093 0.279 0.61
0.463 0.315 0.019 0.204 0.23"), header = T)
You can always check the output of path_helpers
in console. Just use the helper with app
app.post_path(3)
#=> "/posts/3"
app.posts_path
#=> "/posts"
app.posts_url
#=> "http://www.example.com/posts"
This happened to me because strangely GIT thought that the local branch was different from the remote branch. This was visible in the branch graph: it displayed two different branches: remotes/origin/branch_name and branch_name.
The solution was simply to remove the local repo and re-clone it from remote. This way GIT would understand that remotes/origin/branch_name>and branch_name are indeed the same, and I could issue the git merge branch_name
.
rm <my_repo>
git clone <my_repo>
cd <my_repo>
git checkout <branch_name>
git pull
git checkout master
git merge <branch_name>
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
this is an old post but...
just surprised that nobody talk about pg_hba file as it can be a good reason to get this error code.
Check here for those who forgot to configure it: http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html
Using 'async': false to prevent asynchronous code is a bad practice,
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/
On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).
Try this instead,
var return_first;
function callback(response) {
return_first = response;
//use return_first variable here
}
$.ajax({
'type': "POST",
'global': false,
'dataType': 'html',
'url': "ajax.php?first",
'data': { 'request': "", 'target': arrange_url, 'method': method_target },
'success': function(data){
callback(data);
},
});
There are already some very great answers but I'm posting a new one to emphasize my observation on case III below about what happens when you have an explicit return statement in a function which you are new
ing up. Have a look at below cases:
Case I:
var Foo = function(){
this.A = 1;
this.B = 2;
};
console.log(Foo()); //prints undefined
console.log(window.A); //prints 1
Above is a plain case of calling the anonymous function pointed by Foo
. When you call this function it returns undefined
. Since there is no explicit return statement so JavaScript interpreter forcefully inserts a return undefined;
statement in the end of the function. Here window is the invocation object (contextual this
) which gets new A
and B
properties.
Case II:
var Foo = function(){
this.A = 1;
this.B = 2;
};
var bar = new Foo();
console.log(bar()); //illegal isn't pointing to a function but an object
console.log(bar.A); //prints 1
Here JavaScript interpreter seeing the new
keyword creates a new object which acts as the invocation object (contextual this
) of anonymous function pointed by Foo
. In this case A
and B
become properties on the newly created object (in place of window object). Since you don't have any explicit return statement so JavaScript interpreter forcefully inserts a return statement to return the new object created due to usage of new
keyword.
Case III:
var Foo = function(){
this.A = 1;
this.B = 2;
return {C:20,D:30};
};
var bar = new Foo();
console.log(bar.C);//prints 20
console.log(bar.A); //prints undefined. bar is not pointing to the object which got created due to new keyword.
Here again JavaScript interpreter seeing the new
keyword creates a new object which acts as the invocation object (contextual this
) of anonymous function pointed by Foo
. Again, A
and B
become properties on the newly created object. But this time you have an explicit return statement so JavaScript interpreter will not do anything of its own.
The thing to note in case III is that the object being created due to new
keyword got lost from your radar. bar
is actually pointing to a completely different object which is not the one which JavaScript interpreter created due to new
keyword.
Quoting David Flanagan from JavaScripit: The Definitive Guide (6th Edition),Ch. 4, Page # 62:
When an object creation expression is evaluated, JavaScript first creates a new empty object, just like the one created by the object initializer {}. Next, it invokes the specified function with the specified arguments, passing the new object as the value of the this keyword. The function can then use this to initialize the properties of the newly created object. Functions written for use as constructors do not return a value, and the value of the object creation expression is the newly created and initialized object. If a constructor does return an object value, that value becomes the value of the object creation expression and the newly created object is discarded.
---Additional Info---
The functions used in code snippet of above cases have special names in JS world as below:
Case I and II - Constructor function
Case III - Factory function. Factory functions shouldn't be used with new
keyword which I've done to explain the concept in current thread.
You can read about difference between them in this thread.
Replacing one string with another can be done in the below methods
Method 1: Using String replaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
Method 2: Using Pattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
Method 3: Using Apache Commons
as defined in the link below:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.
That would lead to the reduced table definition:
CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);
To solve this, add the JAVA_HOME variable in Users variables instead of System variables.
Install 64 bit JDK and JRE if you have a 64-bit computer and set the JAVA_HOME variable like in the picture
This same Facebook error happened to me in the Production environment. The reason was I had 2 apps registered with Facebook (Local, Production) but I hardcoded the Local app ID into the source code and forgot to switch it out for the Production app ID before deployment.
Best practice dictates you shouldn't have the app ID hardcoded into the source code but if you do, do not mismatch your various Facebook app IDs like I mistakenly did.
By using the SqlCommand
and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.
Here is an example, taken from one of the articles above:
private static void UpdateDemographics(Int32 customerID,
string demoXml, string connectionString)
{
// Update the demographics for a store, which is stored
// in an xml column.
string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
+ "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("@demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.
For example create a helper method (or class JsonUtils
with static methods) in json_utils.py
:
def get_attribute(data, attribute, default_value):
return data.get(attribute) or default_value
and then use it in your project:
from json_utils import get_attribute
def my_cool_iteration_func(data):
data_to = get_attribute(data, 'to', None)
if not data_to:
return
data_to_data = get_attribute(data_to, 'data', [])
for item in data_to_data:
print('The id is: %s' % get_attribute(item, 'id', 'null'))
IMPORTANT NOTE:
There is a reason I am using data.get(attribute) or default_value
instead of simply data.get(attribute, default_value)
:
{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'
In my applications getting attribute with value 'null' is the same as not getting the attribute at all. If your usage is different, you need to change this.
The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.
The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER
after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName
, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier
This is a simiple example:
use example
go
create table Test1 (
id int primary key,
item uniqueidentifier,
inserted_at datetime
)
go
create table Test2 (
id int primary key,
inserted_at datetime
)
go
alter table Test2 add item uniqueidentifier;
go
--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());
insert into Test2 select * from Test1;
select * from Test1;
select * from Test2;
The error message is:
Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime
.......... ^ <= pointer to "print head"
/* part1 */
printf("hello worl");
hello worl ^ <= pointer to "print head"
/* part2 */
printf("\b");
hello worl ^ <= pointer to "print head"
/* part3 */
printf("\b");
hello worl ^ <= pointer to "print head"
/* part4 */
printf("d\n");
hello wodl ^ <= pointer to "print head" on the next line
Hmya, the enduring mystique of DoEvents(). There's been an enormous amount of backlash against it, but nobody ever really explains why it is "bad". The same kind of wisdom as "don't mutate a struct". Erm, why does the runtime and the language supports mutating a struct if that's so bad? Same reason: you shoot yourself in the foot if you don't do it right. Easily. And doing it right requires knowing exactly what it does, which in the case of DoEvents() is definitely not easy to grok.
Right off the bat: almost any Windows Forms program actually contains a call to DoEvents(). It is cleverly disguised, however with a different name: ShowDialog(). It is DoEvents() that allows a dialog to be modal without it freezing the rest of the windows in the application.
Most programmers want to use DoEvents to stop their user interface from freezing when they write their own modal loop. It certainly does that; it dispatches Windows messages and gets any paint requests delivered. The problem however is that it isn't selective. It not only dispatches paint messages, it delivers everything else as well.
And there's a set of notifications that cause trouble. They come from about 3 feet in front of the monitor. The user could for example close the main window while the loop that calls DoEvents() is running. That works, user interface is gone. But your code didn't stop, it is still executing the loop. That's bad. Very, very bad.
There's more: The user could click the same menu item or button that causes the same loop to get started. Now you have two nested loops executing DoEvents(), the previous loop is suspended and the new loop is starting from scratch. That could work, but boy the odds are slim. Especially when the nested loop ends and the suspended one resumes, trying to finish a job that was already completed. If that doesn't bomb with an exception then surely the data is scrambled all to hell.
Back to ShowDialog(). It executes DoEvents(), but do note that it does something else. It disables all the windows in the application, other than the dialog. Now that 3-feet problem is solved, the user cannot do anything to mess up the logic. Both the close-the-window and start-the-job-again failure modes are solved. Or to put it another way, there is no way for the user to make your program run code in a different order. It will execute predictably, just like it did when you tested your code. It makes dialogs extremely annoying; who doesn't hate having a dialog active and not being able to copy and paste something from another window? But that's the price.
Which is what it takes to use DoEvents safely in your code. Setting the Enabled property of all your forms to false is a quick and efficient way to avoid problems. Of course, no programmer ever actually likes doing this. And doesn't. Which is why you shouldn't use DoEvents(). You should use threads. Even though they hand you a complete arsenal of ways to shoot your foot in colorful and inscrutable ways. But with the advantage that you only shoot your own foot; it won't (typically) let the user shoot hers.
The next versions of C# and VB.NET will provide a different gun with the new await and async keywords. Inspired in small part by the trouble caused by DoEvents and threads but in large part by WinRT's API design that requires you to keep your UI updated while an asynchronous operation is taking place. Like reading from a file.
Use the following commands.
$ openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013 (or similar output)
For RHEL/CentOS/Fedora:
$ httpd -t -D DUMP_MODULES | grep ssl
ssl_module (shared)
For Ubuntu/Debian
$ apache2 -t -D DUMP_MODULES | grep ssl
ssl_module (shared)
For SUSE
$ httpd2 -t -D DUMP_MODULES | grep ssl
ssl_module (shared)
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
Try using below:
SELECT
(RTRIM(LTRIM(col_1))) + (RTRIM(LTRIM(col_2))) AS Col_newname,
col_1,
col_2
FROM
s_cols
WHERE
col_any_condition = ''
;
a solution i developed and much more stable than any other:
public class URLParamEncoder {
public static String encode(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else {
resultStr.append(ch);
}
}
return resultStr.toString();
}
private static char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
}
select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual
I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.
In your HTML pages, you can request data from the PHP scripts like this:
$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
alert('Result from PHP: ' + e.result);
});
In bar.php you can do this:
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));
This is what's usually called AJAX, and it is useful to give web pages a more dynamic and desktop-like feel (you don't have to refresh the entire page to communicate with PHP).
Other techniques are simpler. As others have suggested, you can simply generate the variable data from your PHP script:
$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";
Most web pages nowadays use a combination of the two.
I liked qiao's first answer very much!
The only thing missing here is to mark the vertexes as visited.
Why we need to do it?
Lets imagine that there is another node number 13 connected from node 11. Now our goal is to find node 13.
After a little bit of a run the queue will look like this:
[[1, 2, 6], [1, 3, 10], [1, 4, 7], [1, 4, 8], [1, 2, 5, 9], [1, 2, 5, 10]]
Note that there are TWO paths with node number 10 at the end.
Which means that the paths from node number 10 will be checked twice. In this case it doesn't look so bad because node number 10 doesn't have any children.. But it could be really bad (even here we will check that node twice for no reason..)
Node number 13 isn't in those paths so the program won't return before reaching to the second path with node number 10 at the end..And we will recheck it..
All we are missing is a set to mark the visited nodes and not to check them again..
This is qiao's code after the modification:
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output of the program will be:
[1, 4, 7, 11, 13]
Without the unneccecery rechecks..
This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.
$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;
var_dump('reset1', reset($array1));
var_dump('reset2', reset($array2));
var_dump('reset3', reset($array3));
var_dump('reset4', reset($array4)); // Warning
var_dump('array_shift1', array_shift($array1));
var_dump('array_shift2', array_shift($array2));
var_dump('array_shift3', array_shift($array3));
var_dump('array_shift4', array_shift($array4)); // Warning
var_dump('each1', each($array1));
var_dump('each2', each($array2));
var_dump('each3', each($array3));
var_dump('each4', each($array4)); // Warning
var_dump('array_values1', array_values($array1)[0]); // Notice
var_dump('array_values2', array_values($array2)[0]);
var_dump('array_values3', array_values($array3)[0]);
var_dump('array_values4', array_values($array4)[0]); // Warning
var_dump('array_slice1', array_slice($array1, 0, 1));
var_dump('array_slice2', array_slice($array2, 0, 1));
var_dump('array_slice3', array_slice($array3, 0, 1));
var_dump('array_slice4', array_slice($array4, 0, 1)); // Warning
list($elm) = $array1; // Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);
Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.
In my opinion, you have should that handler only with arrays.
Now talking about performance, assuming that we have always array, like this:
$elm = empty($array) ? null : ...($array);
...you would use without errors:
$array[count($array)-1];
array_shift
reset
array_values
array_slice
array_shift
is faster than reset
, that is more fast than [count()-1], and these three are faster than array_values
and array_slice
.
The Python docs for hash()
state:
Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup.
Python dictionaries are implemented as hash tables. So any time you use a dictionary, hash()
is called on the keys that you pass in for assignment, or look-up.
Additionally, the docs for the dict
type state:
Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
Easy to use following (no need use CONCAT or ||):
@Query("from Service s where s.category.typeAsString like :parent%")
List<Service> findAll(@Param("parent") String parent);
Documented in: http://docs.spring.io/spring-data/jpa/docs/current/reference/html.
Ramana's answer worked the best for me, of those here, but I had to add a few catches:
import pip
for dist in pip.get_installed_distributions():
if 'site-packages' in dist.location:
try:
pip.call_subprocess(['pip', 'install', '-U', dist.key])
except Exception, exc:
print exc
The site-packages
check excludes my development packages, because they are not located in the system site-packages directory. The try-except simply skips packages that have been removed from PyPI.
To endolith: I was hoping for an easy pip.install(dist.key, upgrade=True)
, too, but it doesn't look like pip was meant to be used by anything but the command line (the docs don't mention the internal API, and the pip developers didn't use docstrings).
They are slightly different - the ETag does not have any information that the client can use to determine whether or not to make a request for that file again in the future. If ETag is all it has, it will always have to make a request. However, when the server reads the ETag from the client request, the server can then determine whether to send the file (HTTP 200) or tell the client to just use their local copy (HTTP 304). An ETag is basically just a checksum for a file that semantically changes when the content of the file changes.
The Expires header is used by the client (and proxies/caches) to determine whether or not it even needs to make a request to the server at all. The closer you are to the Expires date, the more likely it is the client (or proxy) will make an HTTP request for that file from the server.
So really what you want to do is use BOTH headers - set the Expires header to a reasonable value based on how often the content changes. Then configure ETags to be sent so that when clients DO send a request to the server, it can more easily determine whether or not to send the file back.
One last note about ETag - if you are using a load-balanced server setup with multiple machines running Apache you will probably want to turn off ETag generation. This is because inodes are used as part of the ETag hash algorithm which will be different between the servers. You can configure Apache to not use inodes as part of the calculation but then you'd want to make sure the timestamps on the files are exactly the same, to ensure the same ETag gets generated for all servers.
Download the json jar from here. This will solve your problem.
i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution
create custom_spinner.xml in layout folder and paste this code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray">
<TextView
android:id="@+id/tv_spinnervalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorWhite"
android:gravity="center"
android:layout_alignParentLeft="true"
android:textSize="@dimen/_18dp"
android:layout_marginTop="@dimen/_3dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/men_icon"/>
</RelativeLayout>
in your activity
Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
String[] years = {"1996","1997","1998","1998"};
spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
create a new class of adapter
public class SpinnerAdapter extends ArrayAdapter<String> {
private String[] objects;
public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.objects=objects;
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
private View getCustomView(final int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
label.setText(objects[position]);
return row;
}
}
$('input, select').attr('disabled', 'disabled');
Instead of what you have written, you can write it directly in the SelectedIndexChanged event of the dropdownlist control, e.g.
protected void ddlleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
//code goes here
}
No, "message" is not forbidden. It's just deprecated. You application will work fine with using message. But you may want to get rid of the deprecation error, of course.
When you create custom Exception classes for your application, many of them do not subclass just from Exception, but from others, like ValueError or similar. Then you have to adapt to their usage of variables.
And if you have many exceptions in your application it's usually a good idea to have a common custom base class for all of them, so that users of your modules can do
try:
...
except NelsonsExceptions:
...
And in that case you can do the __init__ and __str__
needed there, so you don't have to repeat it for every exception. But simply calling the message variable something else than message does the trick.
In any case, you only need the __init__ or __str__
if you do something different from what Exception itself does. And because if the deprecation, you then need both, or you get an error. That's not a whole lot of extra code you need per class. ;)
From the Python language reference, under Function definitions:
Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.
Fortunately, Django has a way to do what you want, if you use the auto_now
argument for the DateTimeField
:
date = models.DateTimeField(auto_now=True)
See the Django docs for DateTimeField.
Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2017.
Please refer the below link
I spent 8 hours to do that. It is simple...
You shoud have a code like that:
private const int GENERIC_WRITE = 0x40000000;
//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;
Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.
Using setOnItemClickListener is the correct answer, but if you have a keyboard you can change selection even with arrows (no click is performed), so, you need to implement also setOnItemSelectedListener :
myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
MyObject tmp=(MyObject) adapterView.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
// your stuff
}
});
With a small change, it worked fine for me
$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
->update()
->field('status')->set($status)
->field('id')->equals($instrumentId)
->getQuery()
->execute();
The problem is with the TAB. From the tab's title I assume you first made a right click > "Select Rows - Limit 1000". But when you enter a different query in the opening tab, it won't show anything any more... Don't know why. Open a new tab for manual queries, then it will work.
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Your struct is called struct xyx
but a
is of type struct xyz
. Once you fix that, the output is 100
.
#include <stdio.h>
struct xyx {
int x;
int y;
char c;
char str[20];
int arr[2];
};
int main(void)
{
struct xyx a;
a.x = 100;
printf("%d\n", a.x);
return 0;
}
nodeA : pod1 => clusterIP1, pod2 => clusterIP2
nodeB : pod3 => clusterIP3.
pod3 can talk to pod1 via their clusterIP network.
nodeA => nodeIPA : nodeportX
nodeB => nodeIPB : nodeportX
you might access service on pod1 either via nodeIPA:nodeportX OR nodeIPB:nodeportX. Either way will work because kube-proxy (which is installed in each node) will receive your request and distribute it [redirect it(iptables term)] across nodes using clusterIP network.
basically just putting LB in front, so that inbound traffic is distributed to nodeIPA:nodeportX and nodeIPB:nodeportX then continue with the process flow number 2 above.
Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain
to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.
The spec can be read as "ISO-8859-1" or "undefined". Your choice. It's known that many servers use ISO-8859-1 (like it or not) and will fail when you send something else.
For more information and a proposal to fix the situation, see http://greenbytes.de/tech/webdav/draft-reschke-basicauth-enc-latest.html
I think this should help:
Also documentations also prove that you can use require() for json files: https://www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files-in-node-js.htm
var jsonfile = require("./path/to/jsonfile.json");
node = jsonfile.adjacencies.nodeTo;
node2 = jsonfile.adjacencies.nodeFrom;
node3 = jsonfile.adjacencies.data.$color;
//other things.
Unfortunately you cannot do it in one command. There is an open issue for the very feature.
Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.
EDIT
The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.
Shorter and dealing with a column (entire, not just a section of a column):
=COUNTA(A:A)
Beware, a cell containing just a space would be included in the count.
On windows python
3.5, I managed to install scipy
by using conda
not pip
:
conda install scipy
What SSL private key should be sent along with the client certificate?
None of them :)
One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth
). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.
Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.
Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
Use TLS 1.0 and above; and use Server Name Indication.
You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:
openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
-cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem
You can also use -CAfile
to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.
I had this same problem and I was able to solve it by implementing the IValidatableObject interface in my view model.
public class RegisterViewModel : IValidatableObject
{
/// <summary>
/// Error message for Minimum password
/// </summary>
public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters";
/// <summary>
/// Minimum acceptable password length
/// </summary>
public const int PasswordMinimumLength = 8;
/// <summary>
/// Gets or sets the password provided by the user.
/// </summary>
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
/// <summary>
/// Only need to validate the minimum length
/// </summary>
/// <param name="validationContext">ValidationContext, ignored</param>
/// <returns>List of validation errors</returns>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errorList = new List<ValidationResult>();
if ((Password?.Length ?? 0 ) < PasswordMinimumLength)
{
errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"}));
}
return errorList;
}
}
The markup in the Razor is then...
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" }
<div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case
</div>
@Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" })
</div>
This works really well. If I attempt to use [StringLength] instead then the rendered HTML is just not correct. The validation should render as:
<span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span>
With the StringLengthAttribute the rendered HTML shows as a ValidationSummary which is not correct. The funny thing is that when the validator fails the submit is still blocked!
Here's a code snippet showing how to insert a GUID using a parameterised query:
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using(SqlTransaction trans = conn.BeginTransaction())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
cmd.ExecuteNonQuery();
trans.Commit();
}
}
You don't need the executable for setuptools.
You can download the source code, unpack it, traverse to the downloaded directory and run python setup.py install
in the command prompt
As @WarFox stated - there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf
. Here is benchmark that proves that:
@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
public class CharToStringConversion {
private char c = 'c';
@Benchmark
public String stringValueOf() {
return String.valueOf(c);
}
@Benchmark
public String stringValueOfCharArray() {
return String.valueOf(new char[]{c});
}
@Benchmark
public String characterToString() {
return Character.toString(c);
}
@Benchmark
public String characterObjectToString() {
return new Character(c).toString();
}
@Benchmark
public String concatBlankStringPre() {
return c + "";
}
@Benchmark
public String concatBlankStringPost() {
return "" + c;
}
@Benchmark
public String fromCharArray() {
return new String(new char[]{c});
}
}
And result:
Benchmark Mode Cnt Score Error Units
CharToStringConversion.characterObjectToString thrpt 10 82132.021 ± 6841.497 ops/s
CharToStringConversion.characterToString thrpt 10 118232.069 ± 8242.847 ops/s
CharToStringConversion.concatBlankStringPost thrpt 10 136960.733 ± 9779.938 ops/s
CharToStringConversion.concatBlankStringPre thrpt 10 137244.446 ± 9113.373 ops/s
CharToStringConversion.fromCharArray thrpt 10 85464.842 ± 3127.211 ops/s
CharToStringConversion.stringValueOf thrpt 10 119281.976 ± 7053.832 ops/s
CharToStringConversion.stringValueOfCharArray thrpt 10 86563.837 ± 6436.527 ops/s
As you can see, the fastest one would be c + ""
or "" + c
;
VM version: JDK 1.8.0_131, VM 25.131-b11
This performance difference is due to -XX:+OptimizeStringConcat
optimization. You can read about it here.
[ -t <&0 ] || exec >> test.log
This can be used in v5.3.2 to goto a date after initialization
calendar.gotoDate( '2020-09-12' );
eg on datepicker change
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
...
initialDate: '2020-09-02',
...
});
$(".date-picker").change(function(){
var date = $(this).val();
calendar.gotoDate( date );
});
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
You appear to be able to construct reasonably large sets with:
select 9 union all select 10 union all select 11 union all select 12 union all select 13 ...
I got a parser stack overflow in the 5300's, on 5.0.51a.
Try the Command this way:
PS C:\Users\XXX>python.exe
instead of:
C:\Users\XXX>python
First copy your jar file and paste into you Android project's libs folder.
Now right click on newly added (Pasted) jar file and select option
Build Path -> Add to build path
Now you added jar file will get displayed under Referenced Libraries. Again right click on it and select option
Build Path -> Configure Build path
A new window will get appeared. Select Java Build Path from left menu panel and then select Order and export Enable check on added jar file.
Now run your project.
More details @ Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
I realize this is a very old post, but I encountered a similar issue in which my displayed image always had a border around it. I was trying to fill the browser window with a single image. Adding styles like border:none; did not remove the border and neither did margin:0; or padding:0; or any combination of the three.
However, adding position:absolute;top:0;left:0; fixed the problem.
The original post above has position:absolute; but does not have top:0;left:0; and this was adding a default border on my page.
To illustrate the solution, this has a white border (to be precise, it has a top and left offset):
<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;">
This does not have a border:
<img src="filename.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;">
Hopefully this helps someone finding this post looking to resolve a similar problem.
This might be obvious, but it might help someone who has never seen it before. This also happens for regular functions if you mistakenly assign a parameter by position and explicitly by name.
>>> def foodo(thing=None, thong='not underwear'):
... print thing if thing else "nothing"
... print 'a thong is',thong
...
>>> foodo('something', thing='everything')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foodo() got multiple values for keyword argument 'thing'
Another solution for this old post (for those that it might help) :
public class Version implements Comparable<Version> {
private String version;
public final String get() {
return this.version;
}
public Version(String version) {
if(version == null)
throw new IllegalArgumentException("Version can not be null");
if(!version.matches("[0-9]+(\\.[0-9]+)*"))
throw new IllegalArgumentException("Invalid version format");
this.version = version;
}
@Override public int compareTo(Version that) {
if(that == null)
return 1;
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for(int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ?
Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ?
Integer.parseInt(thatParts[i]) : 0;
if(thisPart < thatPart)
return -1;
if(thisPart > thatPart)
return 1;
}
return 0;
}
@Override public boolean equals(Object that) {
if(this == that)
return true;
if(that == null)
return false;
if(this.getClass() != that.getClass())
return false;
return this.compareTo((Version) that) == 0;
}
}
Version a = new Version("1.1");
Version b = new Version("1.1.1");
a.compareTo(b) // return -1 (a<b)
a.equals(b) // return false
Version a = new Version("2.0");
Version b = new Version("1.9.9");
a.compareTo(b) // return 1 (a>b)
a.equals(b) // return false
Version a = new Version("1.0");
Version b = new Version("1");
a.compareTo(b) // return 0 (a=b)
a.equals(b) // return true
Version a = new Version("1");
Version b = null;
a.compareTo(b) // return 1 (a>b)
a.equals(b) // return false
List<Version> versions = new ArrayList<Version>();
versions.add(new Version("2"));
versions.add(new Version("1.0.5"));
versions.add(new Version("1.01.0"));
versions.add(new Version("1.00.1"));
Collections.min(versions).get() // return min version
Collections.max(versions).get() // return max version
// WARNING
Version a = new Version("2.06");
Version b = new Version("2.060");
a.equals(b) // return false
Edit:
@daiscog: Thank you for your remark, this piece of code has been developed for the Android platform and as recommended by Google, the method "matches" check the entire string unlike Java that uses a regulatory pattern. (Android documentation - JAVA documentation)
I think for your situation, the easy and simple for your html input , you can probably add the attribute title
<input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">
/^[0-9\+]{1,}[0-9\-]{3,15}$/
so first is a digit or a +, then some digits or -
Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait,
and wait short time in every loop.
This will result in something like
max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
if [ -f /tmp/st_new.tmp ]; then
break # call results.sh outside loop
else
(( retry = retry + 1 ))
sleep 1
fi
done
if [ -f /tmp/st_new.tmp ]; then
source ../../results.sh
rm -f /tmp/st_new.tmp
else
echo Something wrong with st_new.sh
fi
The difference lies in the fact that ./gradlew
indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle
and then invoke gradle using the gradle
command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.
Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.
Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable
Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html
Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk
In PhoneGap 3.4.0 you can call:
cordova build android --release
If you have set up the 'ant.properties' file in 'platforms/android' directory like the following:
key.store=/Path/to/KeyStore/myapp-release-key.keystore
key.alias=myapp
Then you will be prompted for your keystore password and the output file (myapp-release.apk) ends up in the 'platforms/android/ant-build' directory already signed and aligned and ready to deploy.
Please note that PrimeFaces supports the standard JSF 2.0+ keywords:
@this
Current component.@all
Whole view.@form
Closest ancestor form of current component.@none
No component.and the standard JSF 2.3+ keywords:
@child(n)
nth child.@composite
Closest composite component ancestor.@id(id)
Used to search components by their id ignoring the component tree structure and naming containers.@namingcontainer
Closest ancestor naming container of current component.@parent
Parent of the current component.@previous
Previous sibling.@next
Next sibling.@root
UIViewRoot instance of the view, can be used to start searching from the root instead the current component.But, it also comes with some PrimeFaces specific keywords:
@row(n)
nth row.@widgetVar(name)
Component with given widgetVar.And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass
:
process="@(.myClass :input)"
See:
Since I just went though a drag, I'll try to write the answer I'd have wished for two hours ago. This is for people who don't just want the copy&paste solution
First: Do you wonder why copying and pasting paths works for some people while it doesn't work for others?** The main reason, solutions differ are different python versions, 2.x or 3.x. There are actually distinct versions of virtualenv and virtualenvwrapper that work with either python 2 or 3. If you are on python 2 install like so:
sudo pip install virutalenv
sudo pip install virtualenvwrapper
If you are planning to use python 3 install the related python 3 versions
sudo pip3 install virtualenv
sudo pip3 install virtualenvwrapper
You've successfully installed the packages for your python version and are all set, right? Well, try it. Type workon
into your terminal. Your terminal will not be able to find the command (workon
is a command of virtualenvwrapper). Of course it won't. Workon
is an executable that will only be available to you once you load/source the file virtualenvwrapper.sh
. But the official installation guide has you covered on this one, right?. Just open your .bash_profile and insert the following, it says in the documentation:
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
Especially the command source /usr/local/bin/virtualenvwrapper.sh
seems helpful since the command seems to load/source the desired file virtualenvwrapper.sh
that contains all the commands you want to work with like workon
and mkvirtualenv
. But yeah, no. When following the official installation guide, you are very likely to receive the error from the initial post: mkvirtualenv: command not found
. Still no command is being found and you are still frustrated. So whats the problem here? The problem is that virtualenvwrapper.sh is not were you are looking for it right now. Short reminder ... you are looking here:
source /usr/local/bin/virtualenvwrapper.sh
But there is a pretty straight forward way to finding the desired file. Just type
which virtualenvwrapper
to your terminal. This will search your PATH for the file, since it is very likely to be in some folder that is included in the PATH of your system.
If your system is very exotic, the desired file will hide outside of a PATH folder. In that case you can find the path to virtalenvwrapper.sh
with the shell command find / -name virtualenvwrapper.sh
Your result may look something like this: /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
Congratulations. You have found your missing file!
. Now all you have to do is changing one command in your .bash_profile. Just change:
source "/usr/local/bin/virtualenvwrapper.sh"
to:
"/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh"
Congratulations. Virtualenvwrapper does now work on your system. But you can do one more thing to enhance your solution. If you've found the file virtualenvwrapper.sh
with the command which virtualenvwrapper.sh
you know that it is inside of a folder of the PATH. So if you just write the filename, your file system will assume the file is inside of a PATH folder. So you you don't have to write out the full path. Just type:
source "virtualenvwrapper.sh"
Thats it. You are no longer frustrated. You have solved your problem. Hopefully.
As bmargulies mentioned:
Preferences>Java>Editor>Templates>New...
Now, type psvm then Ctrl + Space
on Mac or Windows.
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
var $table = $('#myTable2');
$table.bootstrapTable('destroy');
Worked for me
Append script to body:
$(document).ready(function() {
$("<script>", { src : "bootstrap.min.js", type : "text/javascript" }).appendTo("body");
});
Try this
DateTime startTime = varValue
DateTime endTime = varTime
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );
Edit: If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.
UPDATE some_table
SET this_column=x, that_column=y
WHERE something LIKE 'them'
If you can select it, you can manipulate it.
Try this:
$(".head h3").html("your new header");
But as others mentioned, you probably want head
div to have an id.
It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.
Above, Abhishek mentions the command line differences specified in two URLS:
PhoneGap: http://docs.phonegap.com/en/edge/guide_cli_index.md.html
Cordova: http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface
One thing to point out is that, as of this post, the phonegap one looks to be almost the same as the cordova one, and is probably not an accurate image of the command line option differences. As such, I installed both on my system so I could look at the differences.
These are just a few of them. Hopefully they are brought more in sync sometime. If anyone has better information, please tell me.
I guess my point is that the phonegap CLI documention mentioned quite often is not really for the phonegap CLI, but for the cordova CLI, at this time. Please tell me if I am missing something. Thanks.
A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.
Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.
On the contrary, I do think working with list
makes it easy to automate such things.
Here is one solution (I stored your four dataframes in folder temp/
).
filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)
It is important to store the full path for your files (as I did with full.names
), otherwise you have to paste the working directory, e.g.
filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")
will work too. Note that I used substr
to extract file names while discarding full path.
You can access your summary tables as follows:
> res$`df4.csv`
A B
Min. :0.00 Min. : 1.00
1st Qu.:1.25 1st Qu.: 2.25
Median :3.00 Median : 6.00
Mean :3.50 Mean : 7.00
3rd Qu.:5.50 3rd Qu.:10.50
Max. :8.00 Max. :16.00
If you really want to get individual summary tables, you can extract them afterwards. E.g.,
for (i in 1:length(res))
assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
You can use a List-Comprehension to make it a one-liner:
[fl.readline() for i in xrange(17)]
More about list comprehension in PEP 202 and in the Python documentation.
This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):
var seconds = System.Math.Abs((date1 - date2).TotalSeconds);
Adding another answer to the bunch (no pun intended)...
You do need to call the doAnswer method if you can't\don't want to use spy's. However, you don't necessarily need to roll your own Answer. There are several default implementations. Notably, CallsRealMethods.
In practice, it looks something like this:
doAnswer(new CallsRealMethods()).when(mock)
.voidMethod(any(SomeParamClass.class));
Or:
doAnswer(Answers.CALLS_REAL_METHODS.get()).when(mock)
.voidMethod(any(SomeParamClass.class));
Actually I got this to work. Consider the following snippet:
Method m;
Type[] genericParameterTypes = m.getGenericParameterTypes();
for (int i = 0; i < genericParameterTypes.length; i++) {
if( genericParameterTypes[i] instanceof ParameterizedType ) {
Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
//parameters[0] contains java.lang.String for method like "method(List<String> value)"
}
}
I'm using jdk 1.6
If you don't care about legacy browsers:
if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )
if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:
if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )
As, @Shaswat Rungta said: "I think the question is more about how to add it after the installation is over."
On my PC(Windows 7) I think that the command "Git Bash here" disappeard after I installed Visual Studio 2017.
I fixt this by downloading and installing Git again.
This is not the solution to you, but if you want to restrict the function calls to some specific parameter types then you must use the PROATOR { The Python Function prototype validator }. you can refer the following link. https://github.com/mohit-thakur-721/proator
If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.
Refer to the ".Source" of the image in the binding statement.
XAML
<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>
View Model Field
private Image _imageOpenClose;
public Image ImageOpenClose
{
get
{
return _imageOpenClose;
}
set
{
_imageOpenClose = value;
OnPropertyChanged();
}
}
pde is extesion for:
Processing: Java derived language
Wiring: C/C++ derived language (Wiring is derived from Processing)
Early versions of Arduino: C/C++ derived (Arduino IDE is derived from Wiring)
For Arduino for example the IDE preprocessor is adding some #defines and some C/C++ files before giving all to gcc.
You can use RTRIM
or cast your value to VARCHAR
:
SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)
Or
SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)
For me it worked a simple sudo pip -I install <package>
.
As man pip
states, -I
ignores installed packages, forcing reinstall instead.
p {_x000D_
width:100%;_x000D_
overflow: hidden;_x000D_
display: -webkit-box;_x000D_
-webkit-line-clamp: 2;_x000D_
-webkit-box-orient: vertical;_x000D_
background:#fff;_x000D_
position:absolute;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p>
_x000D_
This is what i have been used for hashing:
String pass = "password";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte hashBytes[] = messageDigest.digest(pass.getBytes(StandardCharsets.UTF_8));
BigInteger noHash = new BigInteger(1, hashBytes);
String hashStr = noHash.toString(16);
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
Have a look at Yahoo! tips: https://developer.yahoo.com/performance/rules.html#expires.
There are also tips by Google: https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
The solution in the selected answer does not work in case of using Autolayout. If you are using Autolayout for views take a look at this answer.
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
For simple IE detection I tend to use:
(/msie|trident/i).test(navigator.userAgent)
Visit the Microsoft Developer Network to learn about the IE useragent: http://msdn.microsoft.com/library/ms537503.aspx
I used https://stackoverflow.com/a/3431104/2022534 but replaced Django's model_to_dict() with this to be able to handle ForeignKey:
def model_to_dict(instance):
data = {}
for field in instance._meta.fields:
data[field.name] = field.value_from_object(instance)
if isinstance(field, ForeignKey):
data[field.name] = field.rel.to.objects.get(pk=data[field.name])
return data
Please note that I have simplified it quite a bit by removing the parts of the original I didn't need. You might want to put those back.
Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.
I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
this works too, ...if you have multiple column joins
from p in context.Periods
join f in context.Facts
on new {
id = p.periodid,
p.otherid
} equals new {
f.id,
f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value
Unless your app is using some special encryption you can simply add Boolean a key to your Info.plist
with name ITSAppUsesNonExemptEncryption
and value NO
.
If your app is using custom encryption then you will need to provide extra legal documents and go through a review of your encryption before being able to select builds.
If you continue with selecting that version for testing, it will ask for the compliance information manually. Choosing "No" presents you with the plist recommendation above.
This is change has been announced in the 2015 WWDC, but I guess it has been enforced only very recently. See this and this for a transcript of the WWDC session related to the export compliance, just to a text search for "export".
There are other similar questions on SO, see:
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_CLASS_NUMBER);
simply use:
@JsonFormat(pattern="10/04/2019")
or you can use pattern as you like for e.g: ('-' in place of '/')
Just create a button element with jQuery, and add the event handler when you create it :
var div = $('<div />', {'data-role' : 'fieldcontain'}),
btn = $('<input />', {
type : 'button',
value : 'Dynamic Button',
id : 'btn_a',
on : {
click: function() {
alert ( this.value );
}
}
});
div.append(btn).appendTo( $('#pg_menu_content').empty() );
Make sure you that your target in System.IO.Delete(string file)
is a file which is existed.
Maybe there is a mistake in your code ;Like you don't pass the correct file name to the method , or your target is a folder. In these cases you'll see the : "access to the path is denied error".
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
Regarding some points mentioned in previous answers, and to improve readability:
No need for data.loc or query, but I do think it is a bit long.
The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.
I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.
q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time
df.loc[q_product & q_start & q_end, c('Time,Product')]
# c is just a convenience
c = lambda v: v.split(',')
There is no config file unless you create one yourself. However, the port is a parameter of the listen()
function. For example, to listen on port 8124:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
If you're having problems finding a port that's open, you can go to the command line and type:
netstat -ano
To see a list of all ports in use per adapter.
Just copy and paste this Objective-C code.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
[btnAddContact addTarget:self action:@selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
self.navigationItem.rightBarButtonItem = barButton;
}
#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}
This is what i just used, i like how clean it is :-)
$('select').val(function(){
var nextOption = $(this).children(':selected').next();
return $(nextOption).val();
}).change();
php.js ( http://www.phpjs.org/ ) has a isset()
function: http://phpjs.org/functions/isset:454
First, put your file *.class
(e.g Hello.class
) into 1 folder (e.g C:\java
). Then you try command and type cd /d C:\java
. Now you can type "java Hello" !
There is an ipython nbextension that constructs a table of contents for a notebook. It seems to only provide navigation, not section folding.
This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:
if (substr($string, -1, 1) == ',')
{
$string = substr($string, 0, -1);
}
If you want to remove all commas from the end of a line use the simpler:
$string = rtrim($string, ',');
The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:
$string = rtrim($string, ", \t\n");
No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.
That means that
If you add absolute positioning to an element with display: inline-flex
, it will become block-level (like display: flex
), but will still generate a flex formatting context.
If you add absolute positioning to an element with display: flex
, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.
That said, absolutely positioning conflicts with flex children.
As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.
You Can Use Below Code To Make Status Bar Transparent. See Images With red highlight which helps you to identify use of Below code
Kotlin code snippet for your android app
Step:1 Write down code in On create Method
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}
if (Build.VERSION.SDK_INT >= 19) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
window.statusBarColor = Color.TRANSPARENT
}
Step2: You Need SetWindowFlag method which describe in Below code.
private fun setWindowFlag(bits: Int, on: Boolean) {
val win = window
val winParams = win.attributes
if (on) {
winParams.flags = winParams.flags or bits
} else {
winParams.flags = winParams.flags and bits.inv()
}
win.attributes = winParams
}
Java code snippet for your android app:
Step1: Main Activity Code
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
Step2: SetWindowFlag Method
public static void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}
. This can also include null
values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)
I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:
@Cacheable(value="bookCache",
key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse)
...
@Cacheable(value="bookCache",
key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...
Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:
<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />
...with:
public class CacheKeyGenerator
implements org.springframework.cache.interceptor.KeyGenerator {
@Override
public Object generate(final Object target, final Method method,
final Object... params) {
final List<Object> key = new ArrayList<>();
key.add(method.getDeclaringClass().getName());
key.add(method.getName());
for (final Object o : params) {
key.add(o);
}
return key;
}
}
Use "&
" instead of "&".
the general answer can be for example:
df <- data.frame(rbind(c(2,9,6),c(4,6,7),c(4,6,7),c(4,6,7),c(2,9,6))))
new_df <- df[-which(duplicated(df)), ]
X1 X2 X3
1 2 9 6
2 4 6 7
If you are working with API, then you can use it as:
import moment from 'moment'
...
this.state = {
List: []
};
}
componentDidMount() {
this.getData();
}
// Show List
getData() {
fetch('url')
.then((response) => {
response.json()
.then((result) => {
this.setState({ List: result })
})
})
}
this.state.List =
this.state.List.map(row => ({...row, dob: moment(row.dob).format("YYYY/MM/DD")}))
...
As an extension to the answer, I found this post but was looking to fill a 4 dimensional array. The original example is only a two dimensional array, but the question says "multidimensional". I didn't want to post a new question for this...
You can use the same method, but you have to nest them so that you eventually get to a single dimensional array.
fourDArray = new float[10][10][10][1];
// Fill each row with null
for (float[][][] row: fourDArray)
{
for (float[][] innerRow: row)
{
for (float[] innerInnerRow: innerRow)
{
Arrays.fill(innerInnerRow, -1000);
}
}
};
private String convertFrom(String lines, String from, String to) {
ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
CharBuffer cb = Charset.forName(to).decode(bb);
return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};
This seems simple enough and works both in python 2 and 3
try: subprocess.check_output('which executable',shell=True)
except: sys.exit('ERROR: executable not found')
A little late, but if any of you have been going crazy trying to use inline SVG as a background, the escaping suggestions above do not quite work. For one, it does not work in IE, and depending on the content of your SVG the technique will cause trouble in other browsers, like FF.
If you base64 encode the svg (not the entire url, just the svg tag and its contents! ) it works in all browsers. Here is the same jsfiddle example in base64: http://jsfiddle.net/vPA9z/3/
The CSS now looks like this:
body { background-image:
url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPScxMCcgaGVpZ2h0PScxMCc+PGxpbmVhckdyYWRpZW50IGlkPSdncmFkaWVudCc+PHN0b3Agb2Zmc2V0PScxMCUnIHN0b3AtY29sb3I9JyNGMDAnLz48c3RvcCBvZmZzZXQ9JzkwJScgc3RvcC1jb2xvcj0nI2ZjYycvPiA8L2xpbmVhckdyYWRpZW50PjxyZWN0IGZpbGw9J3VybCgjZ3JhZGllbnQpJyB4PScwJyB5PScwJyB3aWR0aD0nMTAwJScgaGVpZ2h0PScxMDAlJy8+PC9zdmc+");
Remember to remove any URL escaping before converting to base64. In other words, the above example showed color='#fcc' converted to color='%23fcc', you should go back to #.
The reason why base64 works better is that it eliminates all the issues with single and double quotes and url escaping
If you are using JS, you can use window.btoa()
to produce your base64 svg; and if it doesn't work (it might complain about invalid characters in the string), you can simply use https://www.base64encode.org/.
Example to set a div background:
var mySVG = "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='#F00'/><stop offset='90%' stop-color='#fcc'/> </linearGradient><rect fill='url(#gradient)' x='0' y='0' width='100%' height='100%'/></svg>";_x000D_
var mySVG64 = window.btoa(mySVG);_x000D_
document.getElementById('myDiv').style.backgroundImage = "url('data:image/svg+xml;base64," + mySVG64 + "')";
_x000D_
html, body, #myDiv {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}
_x000D_
<div id="myDiv"></div>
_x000D_
With JS you can generate SVGs on the fly, even changing its parameters.
One of the better articles on using SVG is here : http://dbushell.com/2013/02/04/a-primer-to-front-end-svg-hacking/
Hope this helps
Mike
This can also happen if your file permissions get changed somehow. Removing the lock file didn't help, and we were getting errors in the log file like:
2016-01-20T09:14:58.210-0800 [initandlisten] warning couldn't write to / rename file /var/lib/mongodb/journal/prealloc.0: couldn't open file /var/lib/mongodb/journal/prealloc.0 for writing errno:13 Permission denied
2016-01-20T09:14:58.288-0800 [initandlisten] couldn't open /var/lib/mongodb/local.ns errno:13 Permission denied
2016-01-20T09:14:58.288-0800 [initandlisten] error couldn't open file /var/lib/mongodb/local.ns terminating
So, went to check permissions:
ls -l /var/lib/mongodb
total 245780
drwxr-xr-x 2 mongodb mongodb 4096 Jan 20 09:14 journal
drwxr-xr-x 2 root root 4096 Jan 20 09:11 local
-rw------- 1 root root 67108864 Jan 20 09:11 local.0
-rw------- 1 root root 16777216 Jan 20 09:11 local.ns
-rwxr-xr-x 1 mongodb nogroup 0 Jan 20 09:14 mongod.lock
To fix:
# chown -R mongodb:mongodb /var/lib/mongodb
Remove the lock file if it's still there:
# rm /var/lib/mongodb/mongod.lock
Start mongodb
# service mongodb start
Tail the log and you should see at the end of it:
tail -f /var/log/mongodb/mongodb.log
2016-01-20T09:16:02.025-0800 [initandlisten] waiting for connections on port 27017
Ok, for me that work with this...
var e2key = function(e) {
if (!e) return '';
var event2key = {
'96':'0', '97':'1', '98':'2', '99':'3', '100':'4', '101':'5', '102':'6', '103':'7', '104':'8', '105':'9', // Chiffres clavier num
'48':'m0', '49':'m1', '50':'m2', '51':'m3', '52':'m4', '53':'m5', '54':'m6', '55':'m7', '56':'m8', '57':'m9', // Chiffres caracteres speciaux
'65':'a', '66':'b', '67':'c', '68':'d', '69':'e', '70':'f', '71':'g', '72':'h', '73':'i', '74':'j', '75':'k', '76':'l', '77':'m', '78':'n', '79':'o', '80':'p', '81':'q', '82':'r', '83':'s', '84':'t', '85':'u', '86':'v', '87':'w', '88':'x', '89':'y', '90':'z', // Alphabet
'37':'left', '39':'right', '38':'up', '40':'down', '13':'enter', '27':'esc', '32':'space', '107':'+', '109':'-', '33':'pageUp', '34':'pageDown' // KEYCODES
};
return event2key[(e.which || e.keyCode)];
};
var page5Key = function(e, customKey) {
if (e) e.preventDefault();
switch(e2key(customKey || e)) {
case 'left': /*...*/ break;
case 'right': /*...*/ break;
}
};
$(document).bind('keyup', page5Key);
$(document).trigger('keyup', [{preventDefault:function(){},keyCode:37}]);
TIMESTAMP is four bytes vs eight bytes for DATETIME.
Timestamps are also lighter on the database and indexed faster.
The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format. The supported range is ’1000-01-01 00:00:00' to ’9999-12-31 23:59:59'.
The TIMESTAMP data type has a range of ’1970-01-01 00:00:01' UTC to ’2038-01-09 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in.
Here is the JSfiddle Demo
I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order
so you can check if it's greater than zero:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.
This might be helpful,
const data = {_x000D_
email: "[email protected]",_x000D_
username: "me"_x000D_
};_x000D_
_x000D_
const options = {_x000D_
headers: {_x000D_
'Content-Type': 'application/json',_x000D_
}_x000D_
};_x000D_
_x000D_
axios.post('http://path', data, options)_x000D_
.then((res) => {_x000D_
console.log("RESPONSE ==== : ", res);_x000D_
})_x000D_
.catch((err) => {_x000D_
console.log("ERROR: ====", err);_x000D_
})
_x000D_
Blockquote
Blockquote
I started coding pretty much the about the time Hungarian notation was invented and the first time I was forced to use it on a project I hated it.
After a while I realised that when it was done properly it did actually help and these days I love it.
But like all things good, it has to be learnt and understood and to do it properly takes time.
all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)
>>> bin(10)
'0b1010'
>>> 0b1010
10
The most efficient selector you can use is an attribute selector.
input[name="btnPage"]:hover {/*your css here*/}
Here's a live demo: http://tinkerbin.com/3G6B93Cb
It is more that the media validates the string encoding, so we want to ensure that the data is acceptable by a handling application (and doesn't contain a binary sequence representing EOL for example)
Imagine you want to send binary data in an email with encoding UTF-8 -- The email may not display correctly if the stream of ones and zeros creates a sequence which isn't valid Unicode in UTF-8 encoding.
The same type of thing happens in URLs when we want to encode characters not valid for a URL in the URL itself:
http://www.foo.com/hello my friend -> http://www.foo.com/hello%20my%20friend
This is because we want to send a space over a system that will think the space is smelly.
All we are doing is ensuring there is a 1-to-1 mapping between a known good, acceptable and non-detrimental sequence of bits to another literal sequence of bits, and that the handling application doesn't distinguish the encoding.
In your example, man
may be valid ASCII in first form; but often you may want to transmit values that are random binary (ie sending an image in an email):
MIME-Version: 1.0
Content-Description: "Base64 encode of a.gif"
Content-Type: image/gif; name="a.gif"
Content-Transfer-Encoding: Base64
Content-Disposition: attachment; filename="a.gif"
Here we see that a GIF image is encoded in base64 as a chunk of an email. The email client reads the headers and decodes it. Because of the encoding, we can be sure the GIF doesn't contain anything that may be interpreted as protocol and we avoid inserting data that SMTP or POP may find significant.
I found that celery purge
doesn't work for my more complex celery config. I use multiple named queues for different purposes:
$ sudo rabbitmqctl list_queues -p celery name messages consumers
Listing queues ... # Output sorted, whitespaced for readability
celery 0 2
[email protected] 0 1
[email protected] 0 1
apns 0 1
[email protected] 0 1
analytics 1 1
[email protected] 0 1
bcast.361093f1-de68-46c5-adff-d49ea8f164c0 0 1
bcast.a53632b0-c8b8-46d9-bd59-364afe9998c1 0 1
celeryev.c27b070d-b07e-4e37-9dca-dbb45d03fd54 0 1
celeryev.c66a9bed-84bd-40b0-8fe7-4e4d0c002866 0 1
celeryev.b490f71a-be1a-4cd8-ae17-06a713cc2a99 0 1
celeryev.9d023165-ab4a-42cb-86f8-90294b80bd1e 0 1
The first column is the queue name, the second is the number of messages waiting in the queue, and the third is the number of listeners for that queue. The queues are:
The analytics task is a brute force tasks that worked great on small data sets, but now takes more than 24 hours to process. Occasionally, something will go wrong and it will get stuck waiting on the database. It needs to be re-written, but until then, when it gets stuck I kill the task, empty the queue, and try again. I detect "stuckness" by looking at the message count for the analytics queue, which should be 0 (finished analytics) or 1 (waiting for last night's analytics to finish). 2 or higher is bad, and I get an email.
celery purge
offers to erase tasks from one of the broadcast queues, and I don't see an option to pick a different named queue.
Here's my process:
$ sudo /etc/init.d/celeryd stop # Wait for analytics task to be last one, Ctrl-C
$ ps -ef | grep analytics # Get the PID of the worker, not the root PID reported by celery
$ sudo kill <PID>
$ sudo /etc/init.d/celeryd stop # Confim dead
$ python manage.py celery amqp queue.purge analytics
$ sudo rabbitmqctl list_queues -p celery name messages consumers # Confirm messages is 0
$ sudo /etc/init.d/celeryd start
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Google Map</title>
<style>
#map{
height: 600px;
width: 100%;
}
</style>
</head>
<body>
<h1>My Google Map`</h1>
<div id="map"></div>
<script>
function initMap(){
//Map options
var options = {
zoom:9,
center:{lat:42.3601, lng:-71.0589}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// customer marker
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png';
//array of Marrkeers
var markers = [
{
coords:{lat: 42.4668, lng: -70.9495},img:iconBase,con:'<h3> This Is your Content <h3>'
},
{
coords:{lat: 42.8584, lng: -70.9300},img:iconBase,con:'<h3> This Is your Content <h3>'
},
{
coords:{lat: 42.7762, lng: -71.0773},img:iconBase,con:'<h3> This Is your Content <h3>'
}
];
//loopthrough markers
for(var i = 0; i <markers.length; i++){
//add markeers
addMarker(markers[i]);
}
//function for the plotting markers on the map
function addMarker (props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
icon:props.img
});
var infoWindow = new google.maps.InfoWindow({
content:props.con,
});
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
}
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=**YourAPIKey**&callback=initMap"
defer
></script>
</body>
</html>
In your code:
while(fscanf(fp,"%s %c",item,&status) == 1)
why 1 and not 2? The scanf functions return the number of objects read.
Visual Studio Resource Editor (free as VS 2013 Community edition) can import PNG (and other formats) and export ICO.
Adding on to Mihalis Bagos answer. I have ended up doing the following:
<style>
.ui-menu{
z-index: 1000;
}
#menubar-layout-container > .ui-menu:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#menubar-layout-container > .ui-menu > .ui-menu-item {
display: inline-block;
float: left;
margin: 0;
padding: 0;
width: auto;
}
.ui-menu .ui-menu-icon{
display: none;
}
</style>
This makes the top level menu horizontal but leaves any sub menus vertical.
I had to remove the icons as this was messing up the layout
There also seems to be a problem with the sub menu positioning.
var statuses = new[] { "A", "B", "C" };
var filteredOrders = from order in orders.Order
where statuses.Contains(order.StatusCode)
select order;
If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.
select IDENT_CURRENT('TableName') as LastIdentity
Using MAX(id)
is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id)
. IDENT_CURRENT
is nearly instantaneous...
This should be quite simple with something like this :
public static String toBinary(int number){
StringBuilder sb = new StringBuilder();
if(number == 0)
return "0";
while(number>=1){
sb.append(number%2);
number = number / 2;
}
return sb.reverse().toString();
}
-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.
-Xmx maximal heap size
By the way, Jsoup has method that takes file: http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parse(java.io.File,%20java.lang.String)
I'm a beginner in Java...
I found another implementation for the infinity in the Java documentation, for the boolean
and double
types.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3
Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.
It looks ugly, but it works.
public class Main {
public static void main(String[] args) {
System.out.println(1.0/0.0);
System.out.println(-1.0/0.0);
}
}
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
I encountered the same error than adding
Task.Delay(2000);
in each request solved the problem
In order to have this result:
{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}
that holds the same data as:
{
"aoColumnDefs": [
{ "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
{ "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
{ "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
]
}
you could use this code:
JSONObject jo = new JSONObject();
Collection<JSONObject> items = new ArrayList<JSONObject>();
JSONObject item1 = new JSONObject();
item1.put("aDataSort", new JSONArray(0, 1));
item1.put("aTargets", new JSONArray(0));
items.add(item1);
JSONObject item2 = new JSONObject();
item2.put("aDataSort", new JSONArray(1, 0));
item2.put("aTargets", new JSONArray(1));
items.add(item2);
JSONObject item3 = new JSONObject();
item3.put("aDataSort", new JSONArray(2, 3, 4));
item3.put("aTargets", new JSONArray(2));
items.add(item3);
jo.put("aoColumnDefs", new JSONArray(items));
System.out.println(jo.toString());
I needed to check an input value if it's integer or float and to do that I've come up with the following:
function isInteger(x) {_x000D_
var integer = parseInt(x, 10);_x000D_
if (!isNaN(integer) && !isFloat(x)) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
function isFloat(x) {_x000D_
var f = parseFloat(x);_x000D_
var floor = Math.floor(f);_x000D_
var fraction = f - floor;_x000D_
if (fraction > 0) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
var cases = [_x000D_
"1",_x000D_
"1.00",_x000D_
"1.01",_x000D_
"0.05",_x000D_
"ab1",_x000D_
"ab1.1",_x000D_
1,_x000D_
1.00,_x000D_
1.01,_x000D_
0.05,_x000D_
1e+5,_x000D_
"",_x000D_
true,_x000D_
false,_x000D_
null,_x000D_
NaN,_x000D_
undefined,_x000D_
];_x000D_
_x000D_
console.log("isInteger()");_x000D_
for (var i = 0; i < cases.length; i++) {_x000D_
console.log(cases[i], isInteger(cases[i]));_x000D_
}_x000D_
_x000D_
console.log("\nisFloat()");_x000D_
for (var i = 0; i < cases.length; i++) {_x000D_
console.log(cases[i], isFloat(cases[i]));_x000D_
}
_x000D_
The -Contains
operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
I think what you want is the -Match
operator:
"12-18" -Match "-"
Which returns True
.
Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match
operator uses regular expressions to perform text matching.
The workaround is, I I save the excel file as excel 97-2003 then it works fine
This may not have been the case at the time the question was asked, but as of Chrome 66, autoplay is blocked.
http://bgr.com/2018/04/18/google-chrome-66-download-auto-playing-videos-block/
You can make an AMI of an existing instance, and then launch other instances using that AMI.
Native JSON support has been included in PHP since 5.2 in the form of methods json_encode()
and json_decode()
. You would use the first to output a PHP variable in JSON.
Postman currently does not support that.
You may use this online tester by Websocket.in: https://www.websocket.in/test-online
I used the CSS in the accepted answer here for my responsive YouTube videos - worked great right up until YouTube updated their system around the start of August 2015. The videos on YouTube are the same dimensions but for whatever reason the CSS in the accepted answer now letterboxes all our videos. Black bands across top and bottom.
I've tickered around with the sizes and settled on getting rid of the top padding and changing the bottom padding to 56.45%
. Seems to look good.
.videowrapper {
position: relative;
padding-bottom: 56.45%;
height: 0;
}
BEGIN
For i in (select id, name, desc from table2)
LOOP
Update table1 set name = i.name, desc = i.desc where id = i.id and (name is null or desc is null);
END LOOP;
END;
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
Instead of a comment, I just want to answer post.
Interface java.sql.PreparedStatement
columnIndexes « You can use prepareStatement function that accepts columnIndexes and SQL statement. Where columnIndexes allowed constant flags are Statement.RETURN_GENERATED_KEYS1 or Statement.NO_GENERATED_KEYS[2], SQL statement that may contain one or more '?' IN parameter placeholders.
SYNTAX «
Connection.prepareStatement(String sql, int autoGeneratedKeys)
Connection.prepareStatement(String sql, int[] columnIndexes)
Example:
PreparedStatement pstmt =
conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
columnNames « List out the columnNames like 'id', 'uniqueID', ...
. in the target table that contain the auto-generated keys that should be returned. The driver will ignore them if the SQL statement is not an INSERT
statement.
SYNTAX «
Connection.prepareStatement(String sql, String[] columnNames)
Example:
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
Full Example:
public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";
String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
//"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
int primkey = 0 ;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
pstmt.setString(1, UserName );
pstmt.setString(2, Language );
pstmt.setString(3, Message );
if (pstmt.executeUpdate() > 0) {
// Retrieves any auto-generated keys created as a result of executing this Statement object
java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
if ( generatedKeys.next() ) {
primkey = generatedKeys.getInt(1);
}
}
System.out.println("Record updated with id = "+primkey);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
I am using Chrome version 75.
add the muted property to video tag
<video id="myvid" muted>
then play it using javascript and set muted to false
var myvideo = document.getElementById("myvid");
myvideo.play();
myvideo.muted = false;
edit: need user interaction (at least click anywhere in the page to work)
I know this is a very old question. Just posting this here as I solved this problem using FlexBox. Here is the solution
#container {
height: 100%;
width: 100%;
display: flex;
}
#leftThing {
width: 25%;
background-color: blue;
}
#content {
width: 50%;
background-color: green;
}
#rightThing {
width: 25%;
background-color: yellow;
}
_x000D_
<div id="container">
<div id="leftThing">
Left Side Menu
</div>
<div id="content">
Random Content
</div>
<div id="rightThing">
Right Side Menu
</div>
</div>
_x000D_
Just had to add display:flex
to the container! No floats required.
bash
4.2 introduces the lastpipe
option, which allows your code to work as written, by executing the last command in a pipeline in the current shell, rather than a subshell.
shopt -s lastpipe
echo "hello world" | read test; echo test=$test
The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from
and Deny from
directives that are preventing access. Read the mod_authz_host documentation for more details.
You should be able to solve this in your VirtualHost by adding something like:
<Location />
Allow from all
Order Deny,Allow
</Location>
Or alternatively with a Directory
directive:
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.
You can use the IsDbNull function:
If IsDbNull(myItem("sID")) = False AndAlso myItem("sID")==sID Then
// Do something
End If
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};
After lots of searching This code work for me:
Check the permission already has: Check WRITE_EXTERNAL_STORAGE permission Allowed or not?
if(isReadStorageAllowed()){
//If permission is already having then showing the toast
//Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
//Existing the method with return
return;
}else{
requestStoragePermission();
}
private boolean isReadStorageAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
//Requesting permission
private void requestStoragePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}
Implement Override onRequestPermissionsResult method for checking is the user allow or denie
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == REQUEST_WRITE_STORAGE){
//If permission is granted
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Displaying a toast
Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
}else{
//Displaying another toast if permission is not granted
Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
}
}
laravel 5 you can easily do this . see below
{{--*/ @$variable_name = 'value' /*--}}
Tags and Elements are not the same.
Elements
They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.
Eg:
<p>This is the <span>Home</span> page</p>
Tags
Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.
The browser sees the letters '
' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '
' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.- Opening tag.
- Closing tagIt depends, if you are referring to unsigned long the formatting character is "%lu"
. If you're referring to signed long the formatting character is "%ld"
.
Obviously this issue has different causes. :)
For my case, my account log in expired... I solved it by simply:
XCode -> Preferences -> Account -> Apple IDs -> Select the related ID and renew the log in...
Hope this helps!
Yes, you can put arrays in sessions, example:
$_SESSION['name_here'] = $your_array;
Now you can use the $_SESSION['name_here']
on any page you want but make sure that you put the session_start()
line before using any session functions, so you code should look something like this:
session_start();
$_SESSION['name_here'] = $your_array;
Possible Example:
session_start();
$_SESSION['name_here'] = $_POST;
Now you can get field values on any page like this:
echo $_SESSION['name_here']['field_name'];
As for the second part of your question, the session variables remain there unless you assign different array data:
$_SESSION['name_here'] = $your_array;
Session life time is set into php.ini file.
Favicons only work when served from a web-server which sets mime-types correctly for served content. Loading from a local file might not work in chromium. Loading from an incorrectly configured web-server will not work.
Web-servers such as lighthttpd must be configured manually to set the mime type correctly.
Because of the likelihood that mimetype assignment will not work in all environments, I would suggest you use an inline base64 encoded ico file instead. This will load faster as well, as it reduces the number of http requests sent to the server.
On POSIX based systems you can base64 encode a file with the base64
command.
To create a base64 encoded ico line use the command:
$ base64 favicon.ico --wrap 0
And insert the output into the line:
<link href="data:image/x-icon;base64,HERE" rel="icon" type="image/x-icon" />
Replacing the word HERE
like so:
<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA////AERpOgA5cCcA7vDtAF6jSABllFcAuuCvAK2trQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFjMzMzMzNxARYzMzMzVBEEERYzMzNhERZxRGMzZxQEA2FER3cRSAgTNxgEEREIQBMzFIARERFEEzNhERARFAATMzYREBEAhBMzMzEYEBFEEzMzNhEQQRQDMzMzcRgEAAMzMzNhERgIEzMzMyERgEQDMzMzMRAEgEMzMzMxERAEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" rel="icon" type="image/x-icon" />
This worked for me on Ubuntu:
Stop MySQL server:
/etc/init.d/mysql stop
Start MySQL from the commandline:
/usr/sbin/mysqld
In another terminal enter mysql and issue:
grant all privileges on *.* to 'root'@'%' with grant option;
You may also want to add
grant all privileges on *.* to 'root'@'localhost' with grant option;
and optionally use a password as well.
flush privileges;
and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with
/etc/init.d/mysql start
On OS X, I like my date to be in the format of YYYY-MM-DD HH:MM
in the output for the file.
So to specify a file I would use:
stat -f "%Sm" -t "%Y-%m-%d %H:%M" [filename]
If I want to run it on a range of files, I can do something like this:
#!/usr/bin/env bash
for i in /var/log/*.out; do
stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
done
This example will print out the last time I ran the sudo periodic daily weekly monthly
command as it references the log files.
To add the filenames under each date, I would run the following instead:
#!/usr/bin/env bash
for i in /var/log/*.out; do
stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
echo "$i"
done
The output would was the following:
2016-40-01 16:40
/var/log/daily.out
2016-40-01 16:40
/var/log/monthly.out
2016-40-01 16:40
/var/log/weekly.out
Unfortunately I'm not sure how to prevent the line break and keep the file name appended to the end of the date without adding more lines to the script.
PS - I use #!/usr/bin/env bash
as I'm a Python user by day, and have different versions of bash
installed on my system instead of #!/bin/bash