Date
has the time as well, just add HH:mm:ss
to the date format:
import java.text.SimpleDateFormat
def date = new Date()
def sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
println sdf.format(date)
In case you are using JRE 8 you can use LoaclDateTime:
import java.time.*
LocalDateTime t = LocalDateTime.now();
return t as String
I recently open sourced Piper (https://github.com/creactiviti/piper) a distributed and very light weight, Spring-based, workflow engine.
I'm blind and from some months I'm using VINUX (a linux distro based on Ubuntu) with SODBEANS (a version of netbeans with a plug-in named SAPPY that add a TTS support). This solution works quite well but sometimes I prefer to launch Win XP and NVDA for launching many pages on FireFox because Vinux doesn't work very well when you try to open more than 3 windows of FireFox...
my rule of thumb is:
rebase
for branches with the same name,merge
otherwise.
examples for same names would be master
, origin/master
and otherRemote/master
.
if develop
exists only in the local repository, and it is always based on a recent origin/master
commit, you should call it master
, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master
branch.
if develop
is shared, it should not be rebased on master
, just merged back into it with --no-ff
. you are developing on develop
. master
and develop
have different names, because we want them to be different things, and stay separate. do not make them same with rebase
.
What the output that you need, select
or print
or .. so on.
so use the following code:
IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2
Via the simulators for respective devices, we can have screenshots with cmd+S command conveniently. And that gives us the exact resolution for the device we simulate. The review team would have mentioned this, but never did. :)
You can try this. Function below sets all values of object's properties to undefined. Works as well with nested objects.
var clearObjectValues = (objToClear) => {
Object.keys(objToClear).forEach((param) => {
if ( (objToClear[param]).toString() === "[object Object]" ) {
clearObjectValues(objToClear[param]);
} else {
objToClear[param] = undefined;
}
})
return objToClear;
};
That worked for me:
$ export LC_ALL=en_US.UTF-8
$ export LANG=en_US.UTF-8
You're not missing anything. RestTemplate#exchange(..)
is the appropriate method to use to set request headers.
Here's an example (with POST, but just change that to GET and use the entity you want).
Note that with a GET, your request entity doesn't have to contain anything (unless your API expects it, but that would go against the HTTP spec). It can be an empty String.
Sometimes you have loops becouse your type class have references to other classes and that classes have references to your type class, thus you have to select the parameters that you need exactly in the json string, like this code.
List<ROficina> oficinas = new List<ROficina>();
oficinas = /*list content*/;
var x = JsonConvert.SerializeObject(oficinas.Select(o => new
{
o.IdOficina,
o.Nombre
}));
You are halfway there. Try:
In [4]: a[a < 0] = 0
In [5]: a
Out[5]: array([1, 2, 3, 0, 5])
You can do that in several ways:
<<
but that is not the usual wayWith string interpolation
source = "#{ROOT_DIR}/#{project}/App.config"
with +
source = "#{ROOT_DIR}/" + project + "/App.config"
The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.
When dealing with pathnames, you may want to use File.join
to avoid messing up with pathname separator.
In the end, it is a matter of taste.
I am too late but let me explain how I solved this problem.
This problem is basically because of improper folders/solution structure.
this issue may occur because 1. If you have copied project from other location and trying to run the project.
so to resolve this go to original location and crosscheck the folders and files again.
this works for me.
A decorator takes the function definition and creates a new function that executes this function and transforms the result.
@deco
def do():
...
is equivalent to:
do = deco(do)
def deco(func):
def inner(letter):
return func(letter).upper() #upper
return inner
This
@deco
def do(number):
return chr(number) # number to letter
is equivalent to this
def do2(number):
return chr(number)
do2 = deco(do2)
65 <=> 'a'
print(do(65))
print(do2(65))
>>> B
>>> B
To understand the decorator, it is important to notice, that decorator created a new function do which is inner that executes function and transforms the result.
I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:
Step 1: Wrap your Iframe in a div wrapper
Step 2: Add a background image to your div wrapper:
.wrapperdiv{
background-image:url(img/loading.gif);
background-repeat:no-repeat;
background-position:center center; /*Can place your loader where ever you like */
}
Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"
The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.
Give it a try.
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
Like others have mentioned, I think of roles as containers for more granular permissions.
Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.
I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.
Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST
These permissions are relatively static, but the relationship of roles to them may be dynamic.
Example -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
You may create APIs to manage the relationship of these permissions to a role.
I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685
To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions
SSH keys are meant to be private so a 644
permission is too open.
Binary references to set Permissions
r(read) = 4
w(write) = 2
x(execute) = 1
So by adding these numbers and by passing the summed digit to chmod command,We set the permission of file/directory. The first digit sets permission for the owner, second digit for group and the third one for all other users on the system who have no right to the file.
A permission of 644 means
(4+2) = read/write permission for the owner
(4) = read permission for the group
(4) = read permission for all other users
By changing the the permission of the file to 400
using
chmod 400 <filename>
solves the issue. As it makes the key read-only accessible to the owner.
Ref: https://www.linux.com/training-tutorials/understanding-linux-file-permissions/
I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:
<configuration>
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/init1.aspx?call=2"/>
<add initializationPage="/init1.aspx?call=2" />
</applicationInitialization>
</system.webServer>
Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.
Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with
while (m.find()) {
//do something???
}
Use regex to find a match maybe?
Or create an array
String[] a = new String[]{
"tom",
"bob",
"harry"
};
if(a.contains(stringtomatch)){
//do something
}
returning true or false indicates that whether execution should continue or stop right there. So just an example
<input type="button" onclick="return func();" />
Now if func() is defined like this
function func()
{
// do something
return false;
}
the click event will never get executed. On the contrary if return true is written then the click event will always be executed.
Yes. With gjson all you have to do now is:
bar := gjson.Get(json, "foo.bar")
bar
could be a struct property if you like. Also, no maps.
In the first regex, each space character is being replaced, character by character, with the empty string.
In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +
.
However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.
If you change the replacement string to '#'
, the difference becomes much clearer:
var str = ' A B C D EF ';
console.log(str.replace(/\s/g, '#')); // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#
This is due to locking of Mongodb
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart
EDIT: While this is currently accepted answer, readers might find this other answer by user John Hart more adapted to their needs. It uses an option which, according to user Ken, was introduced in version 7.21.3 (which was released in December 2010, i.e. after this initial answer).
In your edited question, you're using the URL as the host name, whereas it needs to be the host name only.
Try:
curl -H 'Host: project1.loc' http://127.0.0.1/something
where project1.loc
is just the host name and 127.0.0.1
is the target IP address.
(If you're using curl from a library and not on the command line, make sure you don't put http://
in the Host
header.)
An abstract class is a class that can't be instantiated. It's only purpose is for other classes to extend.
Abstract methods are methods in the abstract class (have to be declared abstract) which means the extending concrete class must override them as they have no body.
The main purpose of an abstract class is if you have common code to use in sub classes but the abstract class should not have instances of its own.
You can read more about it here: Abstract Methods and Classes
you can use convert function :
Select convert(int,[Column1])
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h"
to your main.cpp
file.
In second.h
you just declare like this void yourFunction();
In second.cpp
you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h"
also in the beginning of second.cpp
Hope this helps:)
try regular expression method at this URL: http://www.dotnetperls.com/remove-html-tags
/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
table_ages <- subset(infert, select=c("age"))
summary(table_ages)
# age
# Min. :21.00
# 1st Qu.:28.00
# Median :31.00
# Mean :31.50
# 3rd Qu.:35.25
# Max. :44.00
This is probably what they're looking for. summary(...)
applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.
Note that
summary(infert$age)
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 21.00 28.00 31.00 31.50 35.25 44.00
The numbers are the same but the format is different. This is because table_ages
is a data frame with one column (ages), whereas infert$age
is a numeric vector. Try typing summary(infert)
.
Try the following code.
TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
Get the time of the day and assign it to TimeSpan
variable.
I know it is very late but following approach can also be used:
<select id="type" name="type" >
<option value="Permanent" id="permanent">I am here to stay.</option>
<option value="toremove" id="toremove">Remove me!</option>
<option value="Other" id="other">Other</option>
</select>
and if I have to remove second option (id=toremove), the script would look like
$('#toremove').hide();
To compare two objects you can use:
angular.equals(obj1, obj2)
It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo
var obj1 = {
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return true
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
Old question, and the posted answers work great. I'll chime in with another option though.
git reset ORIG_HEAD
ORIG_HEAD
references the commit that HEAD
previously referenced.
You can try Gson convertor, to get the exact conversion like json.stringify
val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)
In Sequelize version 5 you might also can use this way (full use Operator Sequelize) :
var condition =
{
[Op.or]: [
{
LastName: {
[Op.eq]: "Doe"
},
},
{
FirstName: {
[Op.or]: ["John", "Jane"]
}
},
{
Age:{
[Op.gt]: 18
}
}
]
}
And then, you must include this :
const Op = require('Sequelize').Op
and pass it in :
Student.findAll(condition)
.success(function(students){
//
})
It could beautifully generate SQL like this :
"SELECT * FROM Student WHERE LastName='Doe' OR FirstName in ("John","Jane") OR Age>18"
You can also use defaultdict to address this situation. It goes something like this:
from collections import defaultdict
#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)
for aKey in aSourceDictionary:
aTargetDictionary[aKey].append(aSourceDictionary[aKey])
I tried everything but nothing worked. So I just used : chmod -R 777 to htdocs. At least it's only in my local.
There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
std::vector<double> v;
double* a = &v[0];
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
for Mac,
Click on Android Studio,
then go to Preferences...
Set your Path inside DART SDK PATH here.
After Enable this for your project(like image show),then apply
git reset
if you don't want to commit these changes.
In my opinion, it's better to use the method of startActivity()
just in the your code of the Activity.class
. If you use that in the Adapter
or other class, it will result in that.
Here's what I use:
function strhex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
You could also use the Newtonsoft.Json library for this and call SerializeObject with the Formatting.Indented enum -
var x = JsonConvert.SerializeObject(jsonString, Formatting.Indented);
Documentation: Serialize an Object
Update -
Just tried it again. Pretty sure this used to work - perhaps it changed in a subsequent version or perhaps i'm just imagining things. Anyway, as per the comments below, it doesn't quite work as expected. These do, however (just tested in linqpad). The first one is from the comments, the 2nd one is an example i found elsewhere in SO -
void Main()
{
//Example 1
var t = "{\"x\":57,\"y\":57.0,\"z\":\"Yes\"}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(t);
var f = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(f);
//Example 2
JToken jt = JToken.Parse(t);
string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(formatted);
//Example 2 in one line -
Console.WriteLine(JToken.Parse(t).ToString(Newtonsoft.Json.Formatting.Indented));
}
In Javascript I would use /.*_/
, meaning: match everything until _ (including)
Example:
console.log( 'hello_world'.replace(/.*_/,'') ) // 'world'
Putting #pragma once
at the top of your header file will ensure that it is only included once. Note that #pragma once
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
)
Just use the classic ==
operator:
>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False
Lists are equal if elements at the same index are equal. Ordering is taken into account then.
Make it 100% of the viewport height:
div {
height: 100vh;
}
Works in all modern browsers and IE>=9, see here for more info.
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
display_errors = On
/etc/init.d/apache2 restart
function hasSpaces(str) {
if (str.indexOf(' ') !== -1) {
return true
} else {
return false
}
}
The easiest solution I found was to simply put that in your fragment :
androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(getActivity(),
R.id.nav_host_fragment);
navController.navigate(R.id.action_position_to_destination);
}
});
Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.
I think you have to do mydb.commit()
all the insert into.
Something like this
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='mydb')
cursor = mydb.cursor()
csv_data = csv.reader(file('students.csv'))
for row in csv_data:
cursor.execute('INSERT INTO testcsv(names, \
classes, mark )' \
'VALUES("%s", "%s", "%s")',
row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
I did this combination. its work for me. but facing one issue if click move that div size is too large that scenerio scroll not down to this particular div.
var scrollDownTo =$("#show_question_" + nQueId).position().top;
console.log(scrollDownTo);
$('#slider_light_box_container').animate({
scrollTop: scrollDownTo
}, 1000, function(){
});
}
I solved it upgrading the lxml version with:
pip install --upgrade lxml
math.fabs()
always returns float, while abs()
may return integer.
The best thing I can currently think of (within the list of "simple" tools) is Ghostscript (current version is v.8.71) and the PostScript utility program ps2ascii.ps
. Ghostscript ships it in its lib
subdirectory. Try this (on Windows):
gswin32c.exe ^
-q ^
-sFONTPATH=c:/windows/fonts ^
-dNODISPLAY ^
-dSAFER ^
-dDELAYBIND ^
-dWRITESYSTEMDICT ^
-dCOMPLEX ^
-f ps2ascii.ps ^
-dFirstPage=3 ^
-dLastPage=7 ^
input.pdf ^
-dQUIET ^
-c quit
This command processes pages 3-7 of input.pdf
. Read the comments in the ps2ascii.ps
file itself to see what the "weird" numbers and additional infos mean (they indicate strings, positions, widths, colors, pictures, rectangles, fonts and page breaks...). To get a "simple" text output, replace the -dCOMPLEX
part by -dSIMPLE
.
Following is the code to find email id, name and profile url etc
private CallbackManager callbackManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
//TODO on click of fb custom button call handleFBLogin()
callbackManager = CallbackManager.Factory.create();
}
private void handleFBLogin() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if (isLoggedIn && Store.isUserExists(ActivitySignIn.this)) {
goToHome();
return;
}
LoginManager.getInstance().logInWithReadPermissions(ActivitySignIn.this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
runOnUiThread(new Runnable() {
@Override
public void run() {
setFacebookData(loginResult);
}
});
}
@Override
public void onCancel() {
Toast.makeText(ActivitySignIn.this, "CANCELED", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(ActivitySignIn.this, "ERROR" + exception.toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void setFacebookData(final LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response", response.toString());
String email = response.getJSONObject().getString("email");
String firstName = response.getJSONObject().getString("first_name");
String lastName = response.getJSONObject().getString("last_name");
String profileURL = "";
if (Profile.getCurrentProfile() != null) {
profileURL = ImageRequest.getProfilePictureUri(Profile.getCurrentProfile().getId(), 400, 400).toString();
}
//TODO put your code here
} catch (JSONException e) {
Toast.makeText(ActivitySignIn.this, R.string.error_occurred_try_again, Toast.LENGTH_SHORT).show();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email,first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
If you want to pass two values, you can use this approach
<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
OnClick="RemoveFromRole_Click" />
Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand
event in this case, which I think is more clean code.
One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).
The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:
This is because the .pubxml.user contains required information to publish, and that file isn't (and shouldn't) be included in source control. To fix this VS bug, copy the information from the .pubxml.user file to the .pubxml file. The relevant properties are:
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
Put those in your .pubxml and you should be good to go.
I have seen most of the articles that don't work properly that's why new developers and professional developers get confused about it.
I am explaining to you in a very simple way. In this code, I am generating a google Recaptcha token at the client side at every 3 seconds of time interval because the token is valid for only a few minutes that's why if any user takes time to fill the form then it may be expired.
First I have an index.php file where I am going to write HTML and JavaScript code.
<!DOCTYPE html>
<html>
<head>
<title>Google Recaptcha V3</title>
</head>
<body>
<h1>Google Recaptcha V3</h1>
<form action="recaptcha.php" method="post">
<label>Name</label>
<input type="text" name="name" id="name">
<input type="hidden" name="token" id="token" />
<input type="hidden" name="action" id="action" />
<input type="submit" name="submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
grecaptcha.ready(function() {
grecaptcha.execute('put your site key here', {action: 'application_form'}).then(function(token) {
$('#token').val(token);
$('#action').val('application_form');
});
});
}, 3000);
});
</script>
</body>
</html>
Next, I have created recaptcha.php file to execute it at the server side
<?php
if ($_POST['submit']) {
$name = $_POST['name'];
$token = $_POST['token'];
$action = $_POST['action'];
$curlData = array(
'secret' => 'put your secret key here',
'response' => $token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($curlData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($ch);
$captchaResponse = json_decode($curlResponse, true);
if ($captchaResponse['success'] == '1' && $captchaResponse['action'] == $action && $captchaResponse['score'] >= 0.5 && $captchaResponse['hostname'] == $_SERVER['SERVER_NAME']) {
echo 'Form Submitted Successfully';
} else {
echo 'You are not a human';
}
}
Source of this code. If you would like to know the explanation of this code please visit. Google reCAPTCHA V3 integration in PHP
I had the same problem. I made it work with:
"C:\Program Files (x86)\Android\android-sdk\tools\emulator-arm.exe" @foo
foo
is the name of your virtual device.
You can do easily like bellow,
_employee.Gender = rbtnMale.Checked?rbtnMale.Text:_employee.Gender;
_employee.Gender = rbtnFemale.Checked?rbtnFemale.Text:_employee.Gender;
The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:
<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>
very old question, i know. but with the new f-strings (starting from python 3.6) there are fresh options. so here for completeness:
from datetime import datetime
dt = datetime.now()
# str.format
strg = '{:%B %d, %Y}'.format(dt)
print(strg) # July 22, 2017
# datetime.strftime
strg = dt.strftime('%B %d, %Y')
print(strg) # July 22, 2017
# f-strings in python >= 3.6
strg = f'{dt:%B %d, %Y}'
print(strg) # July 22, 2017
strftime()
and strptime()
Behavior explains what the format specifiers mean.
Open Notepad.
Type the following lines into it (obviously replace the folders with your ones)
@echo off
rem you could also remove the line above, because it might help you to see what happens
rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e
Save the file as backup.bat (not .txt)
Double click on the file to run it. It will backup the folder and all its contents files/subfolders.
Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.
To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.
Just in case your PC is not a "Western" PC and you don't know which code page is used, you can have a look at this page: National Language Support (NLS) API Reference
[Microsoft removed this reference, take it form web-archive National Language Support (NLS) API Reference
Or you can query your registry:
C:\>reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage /f ACP
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
ACP REG_SZ 1252
End of search: 1 match(es) found.
C:\>
I have not used BeuatifulSoup but maybe the following can help in some tiny way.
import re
import urllib2
stuff = urllib2.urlopen(your_url_goes_here).read() # stuff will contain the *entire* page
# Replace the string Python with your desired regex
results = re.findall('(Python)',stuff)
for i in results:
print i
I'm not suggesting this is a replacement but maybe you can glean some value in the concept until a direct answer comes along.
Replace 123 with number of commits your branch has diverged from origin.
git reset HEAD~123 && git reset && git checkout . && git clean -fd && git pull
data.table
and na.omit()
with optional param cols=
.na.omit.data.table
is the fastest on my benchmark (see below), whether for all columns or for select columns (OP question part 2).
data.table
, use complete.cases()
.On a vanilla data.frame
, complete.cases
is faster than na.omit()
or dplyr::drop_na()
. Notice that na.omit.data.frame
does not support cols=
.
Here is a comparison of base (blue), dplyr
(pink), and data.table
(yellow) methods for dropping either all or select missing observations, on notional dataset of 1 million observations of 20 numeric variables with independent 5% likelihood of being missing, and a subset of 4 variables for part 2.
Your results may vary based on length, width, and sparsity of your particular dataset.
Note log scale on y axis.
#------- Adjust these assumptions for your own use case ------------
row_size <- 1e6L
col_size <- 20 # not including ID column
p_missing <- 0.05 # likelihood of missing observation (except ID col)
col_subset <- 18:21 # second part of question: filter on select columns
#------- System info for benchmark ----------------------------------
R.version # R version 3.4.3 (2017-11-30), platform = x86_64-w64-mingw32
library(data.table); packageVersion('data.table') # 1.10.4.3
library(dplyr); packageVersion('dplyr') # 0.7.4
library(tidyr); packageVersion('tidyr') # 0.8.0
library(microbenchmark)
#------- Example dataset using above assumptions --------------------
fakeData <- function(m, n, p){
set.seed(123)
m <- matrix(runif(m*n), nrow=m, ncol=n)
m[m<p] <- NA
return(m)
}
df <- cbind( data.frame(id = paste0('ID',seq(row_size)),
stringsAsFactors = FALSE),
data.frame(fakeData(row_size, col_size, p_missing) )
)
dt <- data.table(df)
par(las=3, mfcol=c(1,2), mar=c(22,4,1,1)+0.1)
boxplot(
microbenchmark(
df[complete.cases(df), ],
na.omit(df),
df %>% drop_na,
dt[complete.cases(dt), ],
na.omit(dt)
), xlab='',
main = 'Performance: Drop any NA observation',
col=c(rep('lightblue',2),'salmon',rep('beige',2))
)
boxplot(
microbenchmark(
df[complete.cases(df[,col_subset]), ],
#na.omit(df), # col subset not supported in na.omit.data.frame
df %>% drop_na(col_subset),
dt[complete.cases(dt[,col_subset,with=FALSE]), ],
na.omit(dt, cols=col_subset) # see ?na.omit.data.table
), xlab='',
main = 'Performance: Drop NA obs. in select cols',
col=c('lightblue','salmon',rep('beige',2))
)
We want code that is robust and simple. This solution works on old devices and newer devices.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getActivity().finishAffinity();
} else{
getActivity().finish();
System.exit( 0 );
}
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
This should work regardless of @@DATEFIRST
ALTER FUNCTION dbo.DEV_VW_WeekSerial
(@YearNum int,
@WeekNum int,
@DayNum int)
RETURNS Date AS
BEGIN
DECLARE @FirstDayYear As Date;
SET @FirstDayYear='01/01/' + CAST(@YearNum As varchar)
RETURN dateadd(d,(@DayNum-datepart(weekday,@FirstDayYear)),dateadd(week, @WeekNum-1,@FirstDayYear))
END
One liner for Python 2.5+ and Python 3 (positive int only):
''.join(reversed([x + (',' if i and not i % 3 else '') for i, x in enumerate(reversed(str(1234567)))]))
You don't need to use **arr, you can either use:
void do_something(int el, std::vector<int> *arr){
arr->push_back(el);
}
or:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
**arr makes no sense but if you insist using it, do it this way:
void do_something(int el, std::vector<int> **arr){
(*arr)->push_back(el);
}
but again there is no reason to do so...
The following works for me:
function decodeHtml(html) {
let areaElement = document.createElement("textarea");
areaElement.innerHTML = html;
return areaElement.value;
}
Joins in update
statements are non-standard and not supported by all vendors. What you're trying to do can be accomplished with a sub-select:
update
file1
set
firstfield = (select 'stuff' concat something from file2 where substr(file1.field1, 10, 20) = substr(file2.xxx,1,10) )
where
file1.foo like 'BLAH%'
'use strict';
angular.module('cloudApp')
.controller('MenuController', function ($scope, $location, CloudAuth) {
$scope.menu = [
{
'title': 'Dashboard',
'iconClass': 'fa fa-dashboard',
'link': '/dashboard',
'active': true
},
{
'title': 'Devices',
'iconClass': 'fa fa-star',
'link': '/devices'
},
{
'title': 'Settings',
'iconClass': 'fa fa-gears',
'link': '/settings'
}
];
$location.path('/dashboard');
$scope.isLoggedIn = CloudAuth.isLoggedIn;
$scope.isAdmin = CloudAuth.isAdmin;
$scope.isActive = function(route) {
return route === $location.path();
};
});
And use the below in the template:
<li role="presentation" ng-class="{active:isActive(menuItem.link)}" ng-repeat="menuItem in menu"><a href="{{menuItem.link}}"><i class="{{menuItem.iconClass}}"></i> {{menuItem.title}}</a></li>
If you have nodejs installed, you can download and install the server using command line:
npm install -g http-server
Change directories to the directory where you want to serve files from:
$ cd ~/projects/angular/current_project
Run the server:
$ http-server
which will produce the message Starting up http-server, serving on:
Available on: http://your_ip:8080 and http://127.0.0.1:8080
That allows you to use urls in your browser like
PYTHONPATH is an environment variable whose value is a list of directories. Once set, it is used by Python to search for imported modules, along with other std. and 3rd-party library directories listed in Python's "sys.path".
As any other environment variables, you can either export it in shell or in ~/.bashrc, see here. You can query os.environ['PYTHONPATH'] for its value in Python as shown below:
$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"
IF defined in shell as
$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite
THEN result =>
/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
ELSE result =>
PYTHONPATH is not defined
To set PYTHONPATH to multiple paths, see here.
Note that one can add or delete a search path via sys.path.insert(), del or remove() at run-time, but NOT through os.environ[]. Example:
>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>>
In summary, PYTHONPATH is one way of specifying the Python search path(s) for imported modules in sys.path. You can also apply list operations directly to sys.path without the aid of PYTHONPATH.
(Updated 2018-03-17)
The problem, as you've spotted, is that String.Contains
does not perform a word-boundary check, so Contains("float")
will return true
for both "foo float bar" (correct) and "unfloating" (which is incorrect).
The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b
. So the regex you want is simply: \bfloat\b
.
A downside to using a Regex
instance is that they can be slow to run if you don't use the .Compiled
option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.
Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split
).
Suppose you just want to look for elements with a single, design-time specified class-name:
class Program {
private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );
private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
}
}
If you need to choose a single class-name at runtime then you can build a regex:
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {
Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}
If you have multiple class-names and you want to match all of them, you could create an array of Regex
objects and ensure they're all matching, or combine them into a single Regex
using lookarounds, but this results in horrendously complicated expressions - so using a Regex[]
is probably better:
using System.Linq;
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {
Regex[] exprs = new Regex[ classNames.Length ];
for( Int32 i = 0; i < exprs.Length; i++ ) {
exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
}
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e =>
e.Name == "div" &&
exprs.All( r =>
r.IsMatch( e.GetAttributeValue("class", "") )
)
);
}
The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex
may be faster in some circumstances - always profile your code first, kids!)
This method below: CheapClassListContains
provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch
:
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e =>
e.Name == "div" &&
CheapClassListContains(
e.GetAttributeValue("class", ""),
className,
StringComparison.Ordinal
)
);
}
/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
if( String.Equals( haystack, needle, comparison ) ) return true;
Int32 idx = 0;
while( idx + needle.Length <= haystack.Length )
{
idx = haystack.IndexOf( needle, idx, comparison );
if( idx == -1 ) return false;
Int32 end = idx + needle.Length;
// Needle must be enclosed in whitespace or be at the start/end of string
Boolean validStart = idx == 0 || Char.IsWhiteSpace( haystack[idx - 1] );
Boolean validEnd = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
if( validStart && validEnd ) return true;
idx++;
}
return false;
}
HtmlAgilityPack is somewhat stagnated doesn't support .querySelector
and .querySelectorAll
, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll
, so you can use it like so:
private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {
return doc.QuerySelectorAll( "div.float" );
}
With runtime-defined classes:
private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {
String selector = "div." + String.Join( ".", classNames );
return doc.QuerySelectorAll( selector );
}
From 2020 You can add hover styles inside media query
@media (hover: hover) and (pointer: fine) {
/* css hover class/style */
}
This media query indicates that styles will work on browsers that not emulate :hover so it will NOT work on touch browsers.
So what you need to do is replace th:field with th:name and add th:value, th:value will have the value of the variable you're passing across.
<div class="col-auto">
<input type="text" th:value="${client.name}" th:name="clientName"
class="form control">
</div>
Store your results in variables, and use them in your HTML and add the necessary styling.
$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];
And in the HTML, you could do:
<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>
Now, you can simply add the styles for country
class in your CSS, like so:
#userdetails {
/* styles go here */
}
Alternatively, you could also use this in your HTML:
<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>
Hope this helps!
I have found that if I save my query(spool_script_file.sql) and call it using this
@c:\client\queries\spool_script_file.sql as script(F5)
My output now is just the results with out the commands at the top.
I found this solution on the oracle forums.
In numpy
, index and dimension numbering starts with 0. So axis 0
means the 1st dimension. Also in numpy
a dimension can have length (size) 0. The simplest case is:
In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0
I also get it if x = np.zeros((0,5), int)
, a 2d array with 0 rows, and 5 columns.
So someplace in your code you are creating an array with a size 0 first axis.
When asking about errors, it is expected that you tell us where the error occurs.
Also when debugging problems like this, the first thing you should do is print the shape
(and maybe the dtype
) of the suspected variables.
pandas
pandas
, when sending a Series
or DataFrame
to a numpy.array
, as with the following:
try-except
blockif x.size != 0:
Update: See the bottom of the answer for a slightly better way of doing it.
Update #2: I've figured out changing legend title fonts too.
Update #3: There is a bug in Matplotlib 2.0.0 that's causing tick labels for logarithmic axes to revert to the default font. Should be fixed in 2.0.1 but I've included the workaround in the 2nd part of the answer.
This answer is for anyone trying to change all the fonts, including for the legend, and for anyone trying to use different fonts and sizes for each thing. It does not use rc (which doesn't seem to work for me). It is rather cumbersome but I could not get to grips with any other method personally. It basically combines ryggyr's answer here with other answers on SO.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
# Set the font dictionaries (for plot title and axis titles)
title_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal',
'verticalalignment':'bottom'} # Bottom vertical alignment for more space
axis_font = {'fontname':'Arial', 'size':'14'}
# Set the font properties (for use in legend)
font_path = 'C:\Windows\Fonts\Arial.ttf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)
ax = plt.subplot() # Defines ax variable by creating an empty plot
# Set the tick labels font
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
label.set_fontname('Arial')
label.set_fontsize(13)
x = np.linspace(0, 10)
y = x + np.random.normal(x) # Just simulates some data
plt.plot(x, y, 'b+', label='Data points')
plt.xlabel("x axis", **axis_font)
plt.ylabel("y axis", **axis_font)
plt.title("Misc graph", **title_font)
plt.legend(loc='lower right', prop=font_prop, numpoints=1)
plt.text(0, 0, "Misc text", **title_font)
plt.show()
The benefit of this method is that, by having several font dictionaries, you can choose different fonts/sizes/weights/colours for the various titles, choose the font for the tick labels, and choose the font for the legend, all independently.
UPDATE:
I have worked out a slightly different, less cluttered approach that does away with font dictionaries, and allows any font on your system, even .otf fonts. To have separate fonts for each thing, just write more font_path
and font_prop
like variables.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.ticker
# Workaround for Matplotlib 2.0.0 log axes bug https://github.com/matplotlib/matplotlib/issues/8017 :
matplotlib.ticker._mathdefault = lambda x: '\\mathdefault{%s}'%x
# Set the font properties (can use more variables for more fonts)
font_path = 'C:\Windows\Fonts\AGaramondPro-Regular.otf'
font_prop = font_manager.FontProperties(fname=font_path, size=14)
ax = plt.subplot() # Defines ax variable by creating an empty plot
# Define the data to be plotted
x = np.linspace(0, 10)
y = x + np.random.normal(x)
plt.plot(x, y, 'b+', label='Data points')
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
label.set_fontproperties(font_prop)
label.set_fontsize(13) # Size here overrides font_prop
plt.title("Exponentially decaying oscillations", fontproperties=font_prop,
size=16, verticalalignment='bottom') # Size here overrides font_prop
plt.xlabel("Time", fontproperties=font_prop)
plt.ylabel("Amplitude", fontproperties=font_prop)
plt.text(0, 0, "Misc text", fontproperties=font_prop)
lgd = plt.legend(loc='lower right', prop=font_prop) # NB different 'prop' argument for legend
lgd.set_title("Legend", prop=font_prop)
plt.show()
Hopefully this is a comprehensive answer
you can also check this link
SELECT * FROM master_question
WHERE 1 ORDER BY question_id
ASC LIMIT 20
Just Follow Simple 1-2-3 Steps :
1) Go to Taskbar
2) Click on WAMP icon (Left Click)
3) Now Go to Apache > Services > Apache Module and check Rewrite_module is enable or not ! if its not then click on it ! WAMP will be automatically restarted and you're done !
For the relative path (i.e. the direct equivalent of Windows' %~dp0
):
MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"
For the absolute, normalized path:
MY_PATH="`dirname \"$0\"`" # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`" # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
# error; for some reason, the path is not accessible
# to the script (e.g. permissions re-evaled after suid)
exit 1 # fail
fi
echo "$MY_PATH"
You can use this my library to do the job: https://github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
You'll need a UITapGestureRecognizer
.
To set up use this:
override func viewDidLoad()
{
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
}
(You could also use a UIButton
and assign an image to it, without text and than simply connect an IBAction
)
The easiest way to calculate number of neurons in one layer is: Param value / (number of units * 4)
For example in Paul Lo's answer , number of neurons in one layer is 264710 / (514 * 4 ) = 130
Very short answer :
Different databases have different uses. I'm not a database expert. Rule of thumb:
Short answer:
Let's consider two example scenarios:
Scenario 1:
You are building an online store/website, and you want to be able to:
You want to be able to find data for a particular user, change its name... basically perform INSERT, UPDATE, DELETE operations on user data. Same with products, etc.
You want to be able to make transactions, possibly involving a user buying a product (that's a relation). Then OLTP is probably a good fit.
Scenario 2:
You have an online store/website, and you want to compute things like
This falls into the analytics/business intelligence domain, and therefore OLAP is probably more suited.
If you think in terms of "It would be nice to know how/what/how much"..., and that involves all "objects" of one or more kind (ex. all the users and most of the products to know the total spent) then OLAP is probably better suited.
Longer answer:
Of course things are not so simple. That's why we have to use short tags like OLTP
and OLAP
in the first place. Each database should be evaluated independently in the end.
So what could be the fundamental difference between OLAP and OLTP?
Well, databases have to store data somewhere. It shouldn't be surprising that the way the data is stored heavily reflects the possible use of said data. Data is usually stored on a hard drive. Let's think of a hard drive as a really wide sheet of paper, where we can read and write things. There are two ways to organize our reads and writes so that they can be efficient and fast.
One way is to make a book that is a bit like a phone book. On each page of the book, we store the information regarding a particular user. Now that's nice, we can find the information for a particular user very easily! Just jump to the page! We can even have a special page at the beginning to tell us on which page the users are if we want. But on the other hand, if we want to find, say, how much money all of our users spent then we would have to read every page, i.e. the whole book! That would be a row-based book/database (OLTP). The optional page at the beginning would be the index.
Another way to use our big sheet of paper is to make an accounting book. I'm no accountant, but let's imagine that we would have a page for "expenditures", "purchases"... That's nice because now we can query things like "give me the total revenue" very quickly (just read the "purchases" page). We can also ask for more involved things like "give me the top ten products sold" and still have acceptable performance. But now consider how painful it would be to find the expenditures for a particular user. You would have to go through the whole list of everyone's expenditures and filter the ones of that particular user, then sum them. Which basically amounts to "read the whole book" again. That would be a column-based database (OLAP).
It follows that:
OLTP
databases are meant to be used to do many small transactions, and usually serve as a "single source of truth".
OLAP
databases on the other hand are more suited for analytics, data mining, fewer queries but they are usually bigger (they operate on more data).
It's a bit more involved than that of course and that's a 20 000 feet overview of how databases differ, but it allows me not to get lost in a sea of acronyms.
Speaking of acronyms:
To read a bit further, here are some relevant links which heavily inspired my answer:
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
Make sure the build variant is set to debug (and not release) in Android Studio (check the build variants panel).
If set to debug, it should automatically sign the app with the auto-generated debug keystore, without editing the build scripts.
However you will need to create and configure a specific keystore for release.
Official documentation, covering debug and release modes: https://developer.android.com/tools/publishing/app-signing.html
I used
System.Data.Linq.SqlClient.SqlMethods.Like(row.Name, "test")
in my query.
This performs a case-insensitive comparison.
I have an S3 and used this guide from Google:
https://developers.google.com/chrome-developer-tools/docs/remote-debugging
Really easy, works flawlessly.
This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:
import pylab
datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]
for data, label in datalist:
pylab.plot( data[:,0], data[:,1], label=label )
pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")
You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.
Applying font-size: 0.1px;
to the button works for me in Firefox, Internet Explorer 6, Internet Explorer 7, and Safari. None of the other solutions I've found worked across all of the browsers.
Is there a step missing?
Yes. You need to create the directory:
mkdir ${HOME}/.ssh
Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:
% chmod 700 ~/.ssh
Should the
.ssh
dir be generated when I use thessh-keygen
command?
No. This command generates an SSH key pair but will fail if it cannot write to the required directory:
% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.
Once you've created your keys, you should also restrict who can read those key files to just yourself:
% chmod -R go-wrx ~/.ssh/*
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
In my case, my Dockerfile contained an installation step, which produced the vendor
directory (the PHP equivalent of node_modules
). I then COPY
this directory over to the final application image. Therefore, I could not put vendor
in my .dockerignore
. My solution was simply to delete the directory before performing composer install
(the PHP equivalent of npm install
).
FROM composer AS composer
WORKDIR /app
COPY . .
RUN rm -rf vendor \
&& composer install
FROM richarvey/nginx-php-fpm
WORKDIR /var/www/html
COPY --from=composer /app .
This solution works and does not bloat the final image, but it is not ideal, because the vendor
directory on the host is copied into the Docker context during the build process, which adds time.
I was tinkering around when moving our applications to HTML5 with RESTful apis in the backend. The solution that I came up with was:
As you can see, this reduces the frequent refresh token requests. If user closes the browser/app before the renew token call is triggered, the previous token will expire in time and user will have to re-login.
A more complicated strategy can be implemented to cater for user inactivity (e.g. neglected an opened browser tab). In that case, the renew token call should include the expected expiring time which should not exceed the defined session time. The application will have to keep track of the last user interaction accordingly.
I don't like the idea of setting long expiration hence this approach may not work well with native applications requiring less frequent authentication.
I just spent sometime debugging the same issue. Note, that issue might not be between different projects, but actually between several references in one project that depend on different versions of the same dll/assembly. In my case, issue was reference FastMember.dll
versions mismatch that comes from two different NuGet packages in a single project. When I was given a project, it would not compile because NuGet packages were missing and VS refused to restore missing packages. Through the NuGet menu, I manually update all the NuGets to the latest version, that is when the warning appeared.
In Visual Studio Tools > Options > Build and Run > MSBuld Project build output verbosity: (set to) Diagnostics.
Look for the line(s) There was a conflict between
in the Output
window. Below is the part of output that I got:
1> There was a conflict between "FastMember, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null" and "FastMember, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null". (TaskId:19)
1> "FastMember, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null" was chosen because it was primary and "FastMember, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null" was not. (TaskId:19)
1> References which depend on "FastMember, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null" [C:\Users\ksd3jvp\Source\Temp\AITool\Misra\AMSAITool\packages\FastMember.1.5.0\lib\net461\FastMember.dll]. (TaskId:19)
1> C:\Users\ksd3jvp\Source\Temp\AITool\Misra\AMSAITool\packages\FastMember.1.5.0\lib\net461\FastMember.dll (TaskId:19)
1> Project file item includes which caused reference "C:\Users\ksd3jvp\Source\Temp\AITool\Misra\AMSAITool\packages\FastMember.1.5.0\lib\net461\FastMember.dll". (TaskId:19)
1> FastMember, Version=1.5.0.0, Culture=neutral, processorArchitecture=MSIL (TaskId:19)
1> References which depend on "FastMember, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null" []. (TaskId:19)
1> C:\Users\ksd3jvp\Source\Temp\AITool\Misra\AMSAITool\packages\ClosedXML.0.94.2\lib\net46\ClosedXML.dll (TaskId:19)
1> Project file item includes which caused reference "C:\Users\ksd3jvp\Source\Temp\AITool\Misra\AMSAITool\packages\ClosedXML.0.94.2\lib\net46\ClosedXML.dll". (TaskId:19)
1> ClosedXML, Version=0.94.2.0, Culture=neutral, processorArchitecture=MSIL (TaskId:19)
Notice, that Project file item includes which caused reference "C:\Users\ksd3jvp\Source\Temp\AITool\Misra\AMSAITool\packages\ClosedXML.0.94.2\lib\net46\ClosedXML.dll"
ClosedXML.dll
comes from ClosedXML
NuGet and it depends on FastMember.dll 1.3.0.0
. On top of it, there is also FastMember
Nuget in the project, and it has FastMember.dll 1.5.0.0
. Mismatch !
I have uninstalled ClosedXML
& FastMember
NuGets, because I had binding redirect and installed just latest version of ClosedXML
That fixed the issue !
This worked for me:
String result = input.replaceAll("string1|string2|string3","replacementString");
Example:
String input = "applemangobananaarefruits";
String result = input.replaceAll("mango|are|ts","-");
System.out.println(result);
Output: apple-banana-frui-
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
If there is no vertical scrolling then you can use position:absolute
and height:100%
declared on html and body elements.
Another option is to use viewport height units, see Make div 100% height of browser window
Absolute position Example:
html, body {_x000D_
height:100%;_x000D_
position: absolute;_x000D_
background-color:red;_x000D_
}_x000D_
.button{_x000D_
height:50%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="button">BUTTON</div>
_x000D_
html, body {min-height:100vh;background:gray;_x000D_
}_x000D_
.col-100vh {_x000D_
height:100vh;_x000D_
}_x000D_
.col-50vh {_x000D_
height:50vh;_x000D_
}_x000D_
#mmenu_screen--information{_x000D_
background:teal;_x000D_
}_x000D_
#mmenu_screen--book{_x000D_
background:blue;_x000D_
}_x000D_
.mmenu_screen--direktaction{_x000D_
background:red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div id="mmenu_screen" class="col-100vh container-fluid main_container">_x000D_
_x000D_
<div class="row col-100vh">_x000D_
<div class="col-xs-6 col-100vh">_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--book">_x000D_
BOOKING BUTTON_x000D_
</div>_x000D_
_x000D_
<div class="col-50vh col-xs-12" id="mmenu_screen--information">_x000D_
INFO BUTTON_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
<div class="col-100vh col-xs-6 mmenu_screen--direktaction">_x000D_
DIRECT ACTION BUTTON_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You should be able to run the command
git config --system core.longpaths true
or add it to one of your Git configuration files manually to turn this functionality on, once you are on a supported version of Git. It looks like maybe 1.9.0 and after.
You should install a editor (or IDE) supporting Python syntax. It can highlight source code and make basic format checking. For example: Eric4, Spyder, Ninjia, or Emacs, Vi.
You can try like this too.
Your HTML
Code
<select id="mySelectionBox">
<option value="hello">Foo</option>
<option value="hello1">Foo1</option>
<option value="hello2">Foo2</option>
<option value="hello3">Foo3</option>
</select>
You JQuery
Code
$("#mySelectionBox option").each(function() {
alert(this.text + ' ' + this.value);
});
OR
var select = $('#mySelectionBox')[0];
for (var i = 0; i < select.length; i++){
var option = select.options[i];
alert (option.text + ' ' + option.value);
}
This tool creates the folders with the images in them automatically for you. All you have to do is supply your image then drag the generated folders to your res folder. http://romannurik.github.io/AndroidAssetStudio/
All the best.
There is a fairly well maintained repo on github that has a CSV (with semicolon delimiters), XML, and JSON source of countries, country codes, and other information.
I had the same problem, but believe it or not is was a case of case sensitivity.
This on localhost: http://localhost/.../getdata.php?id=3
Did not behave the same as this on the server: http://server/.../getdata.php?id=3
Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3
add_action( 'init', 'remove_category_perma' );
function remove_category_perma() {
unset($GLOBALS['wp_rewrite']->extra_permastructs['category']);
}
If you just want to change the size font dynamically then you can:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.tutorial_cross_marginTop))
As @achie's answer, you can get the dp from dimens.xml like this:
val dpValue = (resources.getDimension(R.dimen.tutorial_cross_marginTop)/ resources.displayMetrics.density).toInt()
or get sp like this
val spValue = (resources.getDimension(R.dimen.font_size)/ resources.displayMetrics.scaledDensity).toInt()
About Resources.java #{getDimension}
/**
* Retrieve a dimensional for a particular resource ID. Unit
* conversions are based on the current {@link DisplayMetrics} associated
* with the resources.
*
* @param id The desired resource identifier, as generated by the aapt
* tool. This integer encodes the package, type, and resource
* entry. The value 0 is an invalid identifier.
*
* @return Resource dimension value multiplied by the appropriate
* metric.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @see #getDimensionPixelOffset
* @see #getDimensionPixelSize
*/
Resource dimension value multiplied by the appropriate
If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).
If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).
Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.
O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.
f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))
Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).
In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,
f(x) = T(g(x)) iff g(x) = T(f(x))
Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,
f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))
There are also little-oh and little-omega (?
) notations representing loose upper and loose lower bounds of a function.
To summarize:
f(x) = O(g(x))
(big-oh) means that the growth rate off(x)
is asymptotically less than or equal to to the growth rate ofg(x)
.
f(x) = O(g(x))
(big-omega) means that the growth rate off(x)
is asymptotically greater than or equal to the growth rate ofg(x)
f(x) = o(g(x))
(little-oh) means that the growth rate off(x)
is asymptotically less than the growth rate ofg(x)
.
f(x) = ?(g(x))
(little-omega) means that the growth rate off(x)
is asymptotically greater than the growth rate ofg(x)
f(x) = T(g(x))
(theta) means that the growth rate off(x)
is asymptotically equal to the growth rate ofg(x)
For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.
This was very helpful for me as I was trying to figure out how to match all the characters in an xml tag including attributes. I was running into the "matches everything to the end" problem with:
/<simpleChoice.*>/
but was able to resolve the issue with:
/<simpleChoice[^>]*>/
after reading this post. Thanks all.
try this
INSERT INTO exampleTbl VALUES('he doesn''t work for me')
In your case you can do that without using push
at all:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
var newRows = 8;
var newCols = 7;
var item;
for (var i = 0; i < newRows; i++) {
item = myArray[i] || (myArray[i] = []);
for (var k = item.length; k < newCols; k++)
item[k] = 0;
}
With version 2.0 Firebug introduced an Events panel, which lists all events for the element currently selected within the HTML panel.
It can also display event listeners wrapped into jQuery event bindings in case the option Show Wrapped Listeners is checked, which you can reach via the Events panel's options menu.
With that panel the workflow to debug an event handler is as follows:
=> The script execution will stop at the first line of the event handler function and you can step debug it.
The posted solutions will not link any hidden files. To include them, try this:
cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib
not /mnt/usr/lib
), you could do this:
cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto
server
just visit http://www.hivemq.com/demos/websocket-client/ and enter server connection details.
If you got connected means your server is configured properly.
You can also test publish
and subscribe
of messages using this mqtt web socket
to just look at a tables layout from the cli. you would do
desc mytable
or
show table mytable
if(n==1 || n==0){
return n;
}else{
return fib(n-1) + fib(n-2);
}
However, using recursion to get fibonacci number is bad practice, because function is called about 8.5 times than received number. E.g. to get fibonacci number of 30 (1346269) - function is called 7049122 times!
Using the lambda function to check the character is "_" then only count will be incremented else not a valid character
std::string s = "a_b_c";
size_t count = std::count_if( s.begin(), s.end(), []( char c ){if(c =='_') return true; });
std::cout << "The count of numbers: " << count << std::endl;
In my case, since my Java code is meant to be ported to other languages in the near future (Mainly C++), I at least want to pay lip service to freeing memory properly so it helps the porting process later on.
I personally rely on nulling variables as a placeholder for future proper deletion. For example, I take the time to nullify all elements of an array before actually deleting (making null) the array itself.
But my case is very particular, and I know I'm taking performance hits when doing this.
Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem
Just to understand better how tabindex elements works to complete accepted answer :
The tabindex global attribute is an integer indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation, and if so, at what position. It can take several values:
-a negative value means that the element should be focusable, but should not be reachable via sequential keyboard navigation;
-0 means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention;
-a positive value means should be focusable and reachable via sequential keyboard navigation; its relative order is defined by the value of the attribute: the sequential follow the increasing number of the tabindex. If several elements share the same tabindex, their relative order follows their relative position in the document.
from : Mozilla Devlopper Network
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
I think the confusion is that on my server I had to right click the Task Scheduler Library on left hand side and right click to get the option to enable or disable all tasks history.
Hope this helps
I ran into this problem today and I was pulling my hair out trying to figure it out. Like many people here, it would work if I removed the iCloud options in my entitlement file. When I would go to debug the app with the iCloud options enabled then I would get the 0xe8008016 error. This was right after revoking and regenerating new certificates.
So what solved it for me was to turn on iCloud support for the automatically generated Xcode team profile. Log onto the online provisioning tool, go to App IDs
, click on Xcode iOS Wildcard App ID
, click on edit
, enable iCloud by checking the checkbox, and finally clicking Done
. Refresh your profiles in Xcode and then it will start to work.
This makes some sense - when you're debugging it defaults to the team profile and the team profile needs to have iCloud turned on.
They are technically the same thing, it's actually a different notation of using the provider
function of the $provide
service.
The only difference between the service
and the factory
notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.
// Factory
angular.module('myApp').factory('myFactory', function() {
var _myPrivateValue = 123;
return {
privateValue: function() { return _myPrivateValue; }
};
});
// Service
function MyService() {
this._myPrivateValue = 123;
}
MyService.prototype.privateValue = function() {
return this._myPrivateValue;
};
angular.module('myApp').service('MyService', MyService);
var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');
To loop with each()
$("a.directions-link").each(function() {
var $this = $(this);
var _href = $this.attr("href");
$this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});
(string)((int)"00000234892839")
RIGHT ANSWER HERE: Answers above are correct (for some of them) but let's make this simple -- with one tag.
I prefer to use input tags, but you can use a button tag
Here's what your solution should look like using HTML:
< input type="button" class="btn btn-info" onclick='window.location.href = "@Url.Action("Index", "ReviewPendingApprovals", routeValues: null)"'/> // can omit or modify routeValues to your liking
Following width worked well in HTML5: -
<table >
<tr>
<th style="min-width:120px">Month</th>
<th style="min-width:60px">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Please note that
Try this, you can define title directly in XML:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="some title"
app:popupTheme="@style/AppTheme.PopupOverlay">
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :
var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects); //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
list_Objects.sort(function(a,b){
return a["name"].localeCompare(b["name"]);
});
Console.log(list_Objects); //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]
Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.
DECLARE @t1 TABLE (
ColID int IDENTITY,
Col2 int
)
DECLARE @t2 TABLE (
ColID int IDENTITY,
Col2 int
)
INSERT INTO @t1 (Col2) VALUES (123)
INSERT INTO @t1 (Col2) VALUES (234)
INSERT INTO @t1 (Col2) VALUES (456)
INSERT INTO @t1 (Col2) VALUES (1)
INSERT INTO @t2 (Col2) VALUES (123)
INSERT INTO @t2 (Col2) VALUES (345)
INSERT INTO @t2 (Col2) VALUES (456)
INSERT INTO @t2 (Col2) VALUES (2)
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
t1Col2 t2Col2 MyDesiredResult
----------- ----------- ---------------
123 123 1
234 345 234 <- Not a zero
456 456 1
1 2 1 <- Not a match
The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.
The relevant code is copied below:
#include <stdio.h>
#include <stdlib.h>
__global__ void foo(int *ptr)
{
*ptr = 7;
}
int main(void)
{
foo<<<1,1>>>(0);
// make the host block until the device is finished with foo
cudaDeviceSynchronize();
// check for error
cudaError_t error = cudaGetLastError();
if(error != cudaSuccess)
{
// print the CUDA error message and exit
printf("CUDA error: %s\n", cudaGetErrorString(error));
exit(-1);
}
return 0;
}
in your component assign a variable like,
export class AppComponent {
netImage:any = "../assets/network.jpg";
title = 'app';
}
use this netImage in your src to get the image, as given below,
<figure class="figure">
<img [src]="netImage" class="figure-img img-fluid rounded" alt="A generic square placeholder image with rounded corners in a figure.">
<figcaption class="figure-caption">A caption for the above image.</figcaption>
</figure>
Sometimes, I find if you have stackoverflow exceptions in your unit test code, visual studio will mark that unit test case as not run and will stop running other test cases that follow this case.
In this case, you have to find out which case is causing the stackoverflow exception.
use Extension
import java.text.NumberFormat
val Int.commaString: String
get() = NumberFormat.getInstance().format(this)
val String.commaString: String
get() = NumberFormat.getNumberInstance().format(this.toDouble())
val Long.commaString: String
get() = NumberFormat.getInstance().format(this)
val Double.commaString: String
get() = NumberFormat.getInstance().format(this)
result
1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!
when you perform a test, you ever have the probabilty to reject the null hypothesis when it is true.
See the nextt R code:
p=function(n){
x=rnorm(n,0,1)
s=shapiro.test(x)
s$p.value
}
rep1=replicate(1000,p(5))
rep2=replicate(1000,p(100))
plot(density(rep1))
lines(density(rep2),col="blue")
abline(v=0.05,lty=3)
The graph shows that whether you have a sample size small or big a 5% of the times you have a chance to reject the null hypothesis when it s true (a Type-I error)
If you really need to have ADB
running as root
, the quickest and easiest way is to install Android Custom ROMs and the most popular is CyanogenMod
for it has the Root Access
options in developer options menu where you can choose to give root access to apps and ADB
. I used CM before but since it wasn't developed anymore, I tried looking for some solutions out there. Although CyanogenMod is still a good alternative because it does not have bloatware.
One alternative I found out from a friend is using adbd insecure
app which you could try from here: https://forum.xda-developers.com/showthread.php?t=1687590. In my case, it works perferct with an Android custom kernel, but not with the Android stock ROM (vanilla android only). You may try other alternatives too like modifying boot.img
of the Android ROM.
I could not use localStorage
directly in the Firefox (v27) console. I got the error:
[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]
What worked was:
window.content.localStorage
Using Firebase's Query API, you might be tempted to try this:
// !!! THIS WILL NOT WORK !!!
ref
.orderBy('genre')
.startAt('comedy').endAt('comedy')
.orderBy('lead') // !!! THIS LINE WILL RAISE AN ERROR !!!
.startAt('Jack Nicholson').endAt('Jack Nicholson')
.on('value', function(snapshot) {
console.log(snapshot.val());
});
But as @RobDiMarco from Firebase says in the comments:
multiple
orderBy()
calls will throw an error
So my code above will not work.
I know of three approaches that will work.
What you can do is execute one orderBy().startAt()./endAt()
on the server, pull down the remaining data and filter that in JavaScript code on your client.
ref
.orderBy('genre')
.equalTo('comedy')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
if (movie.lead == 'Jack Nicholson') {
console.log(movie);
}
});
If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_lead": "comedy_Jack Nicholson"
}, //...
You're essentially building your own multi-column index that way and can query it with:
ref
.orderBy('genre_lead')
.equalTo('comedy_Jack Nicholson')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
David East has written a library called QueryBase that helps with generating such properties.
You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_year": "comedy_1997"
}, //...
And then query for comedies of the 90s with:
ref
.orderBy('genre_year')
.startAt('comedy_1990')
.endAt('comedy_2000')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25"
. This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.
This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.
A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.
Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:
"movies"
// the same structure you have today
"by_genre"
"comedy"
"by_lead"
"Jack Nicholson"
"movie1"
"Jim Carrey"
"movie3"
"Horror"
"by_lead"
"Jack Nicholson"
"movie2"
There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063
If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.
Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
with a little help of math
#include <math.h>
int main(){
int a = -1;
unsigned int b;
b = abs(a);
}
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
How about this: (or is it ok to use like this?)
var test = "Hello";
new Thread(new ThreadStart(() =>
{
try
{
//Staff to do
Console.WriteLine(test);
}
catch (Exception ex)
{
throw;
}
})).Start();
And if you are using Command line on Windows, download a program ANSICON that enables console to accept color codes. ANSICON is available at https://github.com/adoxa/ansicon/releases
Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.
Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.
If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:
USING CTE (Row, Name, PicID)
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
U.NAME, P.PIC_ID
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
ORDER BY U.NAME, P.PIC_ID
)
SELECT
CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
ON current.Row = previous.Row + 1
ORDER BY current.Row
The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.
[1-9]\.\d{1,2}|0\.((0?[1-9])|([1-9]0?)){1,2}\b
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RemoveAt = gvr.RowIndex;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["Products"];
dt.Rows.RemoveAt(RemoveAt);
dt.AcceptChanges();
ViewState["Products"] = dt;
}
}
catch (Exception ex)
{
throw;
}
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
gvProductsList.DataSource = ViewState["Products"];
gvProductsList.DataBind();
}
catch (Exception ex)
{
}
}
In my experience, first name/last name fields should be at least 48 characters -- there are names from some countries such as Malaysia or India that are very long in their full form.
Phone numbers and postcodes you should always treat as text, not numbers. The normal reason given is that there are postcodes that begin with 0, and in some countries, phone numbers can also begin with 0. But the real reason is that they aren't numbers -- they're identifiers that happen to be made up of numerical digits (and that's ignoring countries like Canada that have letters in their postcodes). So store them in a text field.
In MySQL you can use VARCHAR fields for this type of information. Whilst it sounds lazy, it means you don't have to be too concerned about the right minimum size.
KISS Answer:
document.getElementById('element').style.background = '#DD00DD';
How about this...?
TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);
This was taken from the MSDN docs for XDocument.Load, found here...
int valueToMatch = 7;
Stream.of(1,2,3,4,5,6,7,8).anyMatch(val->{
boolean isMatch = val == valueToMatch;
if(isMatch) {
/*Do whatever you want...*/
System.out.println(val);
}
return isMatch;
});
It will do only operation where it find match, and after find match it stop it's iteration.
Go to
C:\Program Files\MySQL\MySQL Server 5.2\bin
then Open MySQLInstanceConfig file
then complete the wizard.
Click finish
Solve the problem
I think this is the best way to change the port number also.
It works for me
Another way of accomplishing this is using animation
which provides more control.
#content #nav a {
background-color: #FF0;
/* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
animation-duration: 1s; /* same as transition duration */
animation-timing-function: linear; /* kind of same as transition timing */
animation-delay: 0ms; /* same as transition delay */
animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
animation-play-state: running; /* can be set dynamically to pause mid animation*/
/* declaring the states of the animation to transition through */
/* optionally add other properties that will change here, or new states (50% etc) */
@keyframes onHoverAnimation {
0% {
background-color: #FF0;
}
100% {
background-color: #AD310B;
}
}
}
#content #nav a:hover {
/* animation wont run unless the element is given the name of the animation. This is set on hover */
animation-name: onHoverAnimation;
}
Just add in the '0' in your select.
INSERT INTO table_name (a,b,c,d)
SELECT
other_table.a AS a,
other_table.b AS b,
other_table.c AS c,
'0' AS d
FROM other_table
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
managed to fix this by copying the below folder from another Visual Studio setup (non-express)
from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc
to C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc
Try:
$group = Get-ADGroup -Identity your-group-name -Properties *
$group.members | count
This worked for me for a group with over 17000 members.
in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display e.g 0.02f will print 25.00 0.002f will print 25.000
If you have multiple windows open and only want to close the one that was closed use JFrame.dispose().
If you want to close all windows and terminate the application use System.exit()
In python: help(my_list.append)
for example, will give you the docstring of the function.
>>> my_list = []
>>> help(my_list.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools
"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types
How it works:
To set up Local Overrides:
UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides
Updated ES6 version
const truncateString = (string, maxLength = 50) => {
if (!string) return null;
if (string.length <= maxLength) return string;
return `${string.substring(0, maxLength)}...`;
};
truncateString('what up', 4); // returns 'what...'
Make sure that the node server to provide the bundle is running in the background. To run start the server use npm start
or react-native start
and keep the tab open during development
For all the standard library types the member function empty()
is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".
The clear()
member function is inherited from ios
and is used to clear the error state of the stream, e.g. if a file stream has the error state set to eofbit
(end-of-file), then calling clear()
will set the error state back to goodbit
(no error).
For clearing the contents of a stringstream
, using:
m.str("");
is correct, although using:
m.str(std::string());
is technically more efficient, because you avoid invoking the std::string
constructor that takes const char*
. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.
Javascript will do the trick here.
function load() {
var file = new XMLHttpRequest();
file.open("GET", "http://remote.tld/random.txt", true);
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
document.getElementById("div1").innerHTML = text;
}
}
}
}
window.onLoad = load();
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
Below code is combining two things
shopt -s nocasematch that will take care of case insensitive
and if condition that will accept both the input either you pass yes,Yes,YES,y.
shopt -s nocasematch
if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
then exit 0
fi
<a href="http://the.url.com/page.html">
<span onclick="hide(); return false">Hide me</span>
</a>
This is the easiest solution.
jqueryTitle({
title: 'New Title'
});
for first title:
jqueryTitle('destroy');
String comparison in WHERE phrase is not case sensitive. You could try to compare using
WHERE `colname` = 'keyword'
or
WHERE `colname` = 'KeyWord'
and you will get the same result. That is default behavior of MySQL.
If you want the comparison to be case sensitive, you could add COLLATE
just like this:
WHERE `colname` COLLATE latin1_general_cs = 'KeyWord'
That SQL would give different result with this one:
WHERE colname
COLLATE latin1_general_cs = 'keyword'
latin1_general_cs
is common or default collation in most database.
Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.
I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4
node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.
Try the following code.
File file = new File(path); // path = your file path
lastSlash = file.toString().lastIndexOf('/');
if (lastSlash >= 0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if (fileName.endsWith("pdf"))
{
mimeType = "application/pdf";
}
else
{
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
(MimeTypeMap.getFileExtensionFromUrl(path));
}
Uri uri_path = Uri.fromFile(file);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.putExtra(PATH, path);
intent.putExtra(MIMETYPE, mimeType);
intent.setType(mimeType);
intent.setDataAndType(uri_path, mimeType);
startActivity(intent);
You can use simple trick which is import flask app variable from main inside another file, like:
test-routes.py
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
and in your main files, where you declared flask app, import test-routes, like:
app.py
from flask import Flask, request, abort
app = Flask(__name__)
# import declared routes
import test-routes
It works from my side.
To stop redis server
sudo service redis-server stop
and check the status of it using
sudo service redis-server status
In response to other comments, DISPOSE_ON_CLOSE does not seem to properly exit the application - it only destroys the window, but the application will continue running. If you want to terminate the application use EXIT_ON_CLOSE.
It's complicated.
First of all, in this code
const p = new Promise((resolve) => {
resolve(4);
});
the type of p
is inferred as Promise<{}>
. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p
should be Promise<number>
.
Then, Promise<{}>
is compatible with Promise<number>
, because basically the only property a promise has is then
method, and then
is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1
.
But the purpose of async
is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2
because {}
is obvioulsy not compatible with number
.
So the async
behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:
const whatever2 = async (): Promise<number> => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
See the Warning section of ?factor
:
In particular,
as.numeric
applied to a factor is meaningless, and may happen by implicit coercion. To transform a factorf
to approximately its original numeric values,as.numeric(levels(f))[f]
is recommended and slightly more efficient thanas.numeric(as.character(f))
.
The FAQ on R has similar advice.
Why is as.numeric(levels(f))[f]
more efficent than as.numeric(as.character(f))
?
as.numeric(as.character(f))
is effectively as.numeric(levels(f)[f])
, so you are performing the conversion to numeric on length(x)
values, rather than on nlevels(x)
values. The speed difference will be most apparent for long vectors with few levels. If the values are mostly unique, there won't be much difference in speed. However you do the conversion, this operation is unlikely to be the bottleneck in your code, so don't worry too much about it.
Some timings
library(microbenchmark)
microbenchmark(
as.numeric(levels(f))[f],
as.numeric(levels(f)[f]),
as.numeric(as.character(f)),
paste0(x),
paste(x),
times = 1e5
)
## Unit: microseconds
## expr min lq mean median uq max neval
## as.numeric(levels(f))[f] 3.982 5.120 6.088624 5.405 5.974 1981.418 1e+05
## as.numeric(levels(f)[f]) 5.973 7.111 8.352032 7.396 8.250 4256.380 1e+05
## as.numeric(as.character(f)) 6.827 8.249 9.628264 8.534 9.671 1983.694 1e+05
## paste0(x) 7.964 9.387 11.026351 9.956 10.810 2911.257 1e+05
## paste(x) 7.965 9.387 11.127308 9.956 11.093 2419.458 1e+05
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
In the View, modify the current view or create a new view and make a filter change, select the radio button "Show items only when the following is true", in the below columns type "Created" and in the next dropdown select "is less than" and fill the next column [Today]-7.
The keyword [Today] denotes the current day for the calculation and this view will show as per your requirement
You can also use a nested for
loop like shown below
n = 3
arr = []
for x in range(n):
arr.append([])
for y in range(n):
arr[x].append([])
for z in range(n):
arr[x][y].append(0)
print(arr)
If you want to know if a string is a number, you could always try parsing it:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Note that TryParse
returns a bool
, which you can use to check if your parsing succeeded.
pip
itself is just a normal python package. Thus you can install pip with pip.
Of cource, you don't want to affect the system's pip, install it inside a virtualenv.
pip install pip==1.2.1
/src/com/example/MyClass.java
package com.example
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MyClass extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ImageView iv = (ImageView) findViewById(R.id.imageview1);
iv.setVisibility(View.VISIBLE);
}
});
}
}
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ImageView
android:src="@drawable/image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/imageview1"
android:visibility="invisible"
/>
</LinearLayout>
Corrected a few things and added an alternative select - delete as appropriate.
DELIMITER |
CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN
DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;
-- method 1
SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;
SELECT
b.*,
HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist
FROM
cities b
ORDER BY
dist
LIMIT 10;
-- method 2
SELECT
b.*,
HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM
cities AS a
JOIN cities AS b on a.cityID = p_cityID
ORDER BY
dist
LIMIT 10;
END |
delimiter ;
I Prefer this way ... it was much easier
http://www.pymssql.org/en/stable/pymssql_examples.html
conn = pymssql.connect("192.168.10.198", "odoo", "secret", "EFACTURA")
cursor = conn.cursor()
cursor.execute('SELECT * FROM usuario')
Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .
Copy the file to C:\Python27\Scripts
Run cmd from the above location and type
pip install numpy-1.9.2+mkl-cp27-none-win32.whl
You will hopefully get the below output:
Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2
Hope that works for you.
EDIT 1
Adding @oneleggedmule 's suggestion:
You can also run the following command in the cmd:
pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl
Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.
You may find that using the `group' aes will help you get the result you want. For example:
tu <- expand.grid(Land = gl(2, 1, labels = c("DE", "BB")),
Altersgr = gl(5, 1, labels = letters[1:5]),
Geschlecht = gl(2, 1, labels = c('m', 'w')),
Jahr = 2000:2009)
set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)
ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +
geom_point() + geom_line() +
facet_grid(Geschlecht ~ Land)
Which produces the plot found here:
With versions of cut
I know of, no, this is not possible. cut
is primarily useful for parsing files where the separator is not whitespace (for example /etc/passwd
) and that have a fixed number of fields. Two separators in a row mean an empty field, and that goes for whitespace too.