I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z))
you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z))
instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))
Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:
glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));
You can add glm::radians() if you want to keep using degrees. And add the includes:
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
You should include "bPaginate": false,
into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html
You need to decide whether the array elements will be stored in row order or column order and then be consistent about it. http://en.wikipedia.org/wiki/Row-major_order
The C language uses row order for Multidimensional arrays
To simulate this with a single dimensional array, you multiply the row index by the width, and add the column index thus:
int array[width * height];
int SetElement(int row, int col, int value)
{
array[width * row + col] = value;
}
Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.
If you want to remove the routes cache on your server, remove this file:
bootstrap/cache/routes.php
And if you want to update it just run php artisan route:cache
and upload the bootstrap/cache/routes.php
to your server.
I strongly recommend TurboGears or Bottle:
TurboGears:
Bottle:
To add to all the Awesome work started by Luke I am posting one more that takes a css class value and treats class and alt as optional parameters (valid under ASP.NET 3.5+). This will allow more functionality but reduct the number of overloaded methods needed.
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
if(alt != null)
imgBuilder.MergeAttribute("alt", alt);
if (cssClass != null)
imgBuilder.MergeAttribute("class", cssClass);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
php -f test.php
See the manual for full details of running PHP from the command line
Import lodash
using
$ npm i --save lodash
var _ = require('lodash');
var objArrayList =
[
{ name: "user1"},
{ name: "user2"},
{ name: "user2"}
];
var Obj = _.find(objArrayList, { name: "user2" });
// Obj ==> { name: "user2"}
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
In most cases it could be better to pad the columns only on the right so just the spacing between the columns gets padded, and the first column is still aligned with the table.
CSS:
.padding-table-columns td
{
padding:0 5px 0 0; /* Only right padding*/
}
HTML:
<table className="padding-table-columns">
<tr>
<td>Cell one</td>
<!-- There will be a 5px space here-->
<td>Cell two</td>
<!-- There will be an invisible 5px space here-->
</tr>
</table>
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
If using Visual Studio 2012 and later (which uses .NET regular expressions), you can remove trailing whitespace without removing blank lines by using the following regex
Replace (?([^\r\n])\s)+(\r?\n)
With $1
Some explanation
The reason you need the rather complicated expression is that the character class \s
matches spaces, tabs and newline characters, so \s+
will match a group of lines containing only whitespace. It doesn't help adding a $
termination to this regex, because this will still match a group of lines containing only whitespace and newline characters.
You may also want to know (as I did) exactly what the (?([^\r\n])\s)
expression means. This is an Alternation Construct, which effectively means match to the whitespace character class if it is not a carriage return or linefeed.
Alternation constructs normally have a true and false part,
(?( expression ) yes | no )
but in this case the false part is not specified.
So Why not use powershell to create the list of source files for you. Take a look at this script
param (
[Parameter(Mandatory=$True)]
[string]$root
)
if (-not (Test-Path -Path $root)) {
throw "Error directory does not exist"
}
#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;
$files = Get-ChildItem -Path $root -Recurse -File |
Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} |
Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}
$CMakeExpr = "set(SOURCES "
foreach($file in $files){
$CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;
Suppose you have a folder with this structure
C:\Workspace\A
--a.cpp
C:\Workspace\B
--b.cpp
Now save this file as "generateSourceList.ps1" for example, and run the script as
~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt
out.txt file will contain
set(SOURCE "A/a.cpp" "B/b.cpp")
I've got an example working.
Here's how my doc looks:
<html>
<head>
<link rel="stylesheet" href="css/main.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-resource.min.js"></script>
<script src="js/app.js"></script>
<script src="controllers/ctrls.js"></script>
</head>
<body ng-app="app">
<div id="contnr">
<ng-view></ng-view>
</div>
</body>
</html>
Here's what my partial looks like:
<div id="welcome" ng-controller="Index">
<b>Welcome! Please Login!</b>
<form ng-submit="auth()">
<input class="input login username" type="text" placeholder="username" /><br>
<input class="input login password" type="password" placeholder="password" /><br>
<input class="input login submit" type="submit" placeholder="login!" />
</form>
</div>
Here's what my Ctrl looks like:
app.controller('Index', function($scope, $routeParams, $location){
$scope.auth = function(){
$location.url('/map');
};
});
app is my module:
var app = angular.module('app', ['ngResource']).config(function($routeProvider)...
Hope this is helpful!
Viewgroup inherits properties of views and does more with other views and viewgroup.
See the Android API: http://developer.android.com/reference/android/view/ViewGroup.html
var intArray = [1, 2, 3, 4, 5];
//lets use each function
$.each(intArray, function(index, element) {
if (element === 3) {
return false;
}
console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
});
//lets use map function
$.map(intArray, function(element, index) {
if (element === 3) {
return false;
}
console.log(element); // prints only 1,2,4,5. skip the number 3.
});
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.
<script type="text/javascript">
$(document).ready(function() {
document.title = 'blah';
});
</script>
Swift put this
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: .Any, barMetrics: .Default)
UINavigationBar.appearance().shadowImage = UIImage()
in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()
) in combination with svg's <foreignObject>
element.
You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup)
)
But note that it is mostly a hack and that there are a lot of limitations :
document.styleSheets
. for this part, DOMParser
and XMLSerializer
may help.<img>
tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).Now, a small demo of some html markup in a pseudo element :
/* _x000D_
** original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
* xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
* I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
Here's an example that you could use :
var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
dddd : Full day Name
Do : day of the Month
MMMM : Full Month name
YYYY : 4 digits Year
For more informations :
In OSX, you can set the classpath from scratch like this:
export CLASSPATH=/path/to/some.jar:/path/to/some/other.jar
Or you can add to the existing classpath like this:
export CLASSPATH=$CLASSPATH:/path/to/some.jar:/path/to/some/other.jar
This is answering your exact question, I'm not saying it's the right or wrong thing to do; I'll leave that for others to comment upon.
There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError
will be raised by the .index
method only, because it's the only code you have there!
To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index
will not raise this type of error for any other issues. Not that I can think of any.
There is always apache commons beanutils but of course it uses reflection under the hood
The sane way to do this is to use zip()
and a List Comprehension / Generator Expression:
filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == '[email protected]')
new_emails, new_other_list = zip(*filtered)
Also, if your'e not using array.array()
or numpy.array()
, then most likely you are using []
or list()
, which give you Lists, not Arrays. Not the same thing.
If you are dealing with a web service call using the Axis framework, there is a much simpler answer. If all want is for your client to be able to call the SSL web service and ignore SSL certificate errors, just put this statement before you invoke any web services:
System.setProperty("axis.socketSecureFactory",
"org.apache.axis.components.net.SunFakeTrustSocketFactory");
The usual disclaimers about this being a Very Bad Thing to do in a production environment apply.
I found this at the Axis wiki.
Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:
this.setState({ [`${name}`]: value}, () => {
console.log("State updated: ", JSON.stringify(this.state[name]));
});
PS: Please mind the quote character.
Below I've incorporated suggestion from comments. Thank you al!
import hashlib
def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
h = hash_factory()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(chunk_num_blocks*h.block_size), b''):
h.update(chunk)
return h.digest()
import hashlib
def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
h = hash_factory()
with open(filename,'rb') as f:
while chunk := f.read(chunk_num_blocks*h.block_size):
h.update(chunk)
return h.digest()
if you care about more pythonic (no 'while True') way of reading the file check this code:
import hashlib
def checksum_md5(filename):
md5 = hashlib.md5()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
md5.update(chunk)
return md5.digest()
Note that the iter() func needs an empty byte string for the returned iterator to halt at EOF, since read() returns b'' (not just '').
Oh! just read comments in question, dear I missed it. but just letting the answer be here in case it can be useful to some other person
I tried "Ctrl+C" and "Ctrl+ Break" none worked. I was using SQL Plus that came with Oracle Client 10.2.0.1.0. SQL Plus is used by most as client for connecting with Oracle DB. I used the Cancel, option under File menu and it stopped the execution!
Once you click File wait for few mins then the select command halts and menu appears click on Cancel.
using "10" for representing a year is not good, because it can be 1910, 1810, etc. You probably should use 4 digits for that.
If you can change the date to something like
yyyymmdd
Then you can use:
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
Answers above are correct but didn't exactly help me as there was additional information I required.
I have just setup Spark so the log4j file still had the '.template' suffix and wasn't being read. I believe that logging then defaults to Spark core logging conf.
So if you are like me and find that the answers above didn't help, then maybe you too have to remove the '.template' suffix from your log4j conf file and then the above works perfectly!
http://apache-spark-user-list.1001560.n3.nabble.com/disable-log4j-for-spark-shell-td11278.html
You can try Thread.currentThread().isDaemon()
In xamarin ios suppose your label name is title then do the following
title.TextAlignment = UITextAlignment.Center;
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
This is a very broad question, so I am going to give a broad answer.
That is all that I can tell from the above screenshot. However, if I were to speculate, you probably have an IO subsystem that is too slow to keep up with the demand. This could be caused by missing indexes or an actually too slow disk. Keep in mind, that 15000 reads for a single OLTP query is slightly high but not uncommon.
I needed a function which could format a price (given in cents) in a way preferred by the user, and the tricky part is that the format is specified by the user -- and I do not expect my users to understand printf-like syntax, or regexps, etc. My solution is somewhat similar to that used in Basic, so the user just marks with # places for digits, for example:
simple_format(1234567,"$ ###,###,###.##")
"$ 12,345.67"
simple_format(1234567,"### ### ###,## pln")
"12 345,67 pln"
I believe this is quite easy to understand by user, and quite easy to implement:
function simple_format(integer,format){
var text = "";
for(var i=format.length;i--;){
if(format[i]=='#'){
text = (integer%10) + text;
integer=Math.floor(integer/10);
if(integer==0){
return format.substr(0,i).replace(/#(.*#)?/,"")+text;
}
}else{
text = format[i] + text;
}
}
return text;
}
The problem with the command
sed 'code' file > file
is that file
is truncated by the shell before sed actually gets to process it. As a result, you get an empty file.
The sed way to do this is to use -i
to edit in place, as other answers suggested. However, this is not always what you want. -i
will create a temporary file that will then be used to replace the original file. This is problematic if your original file was a link (the link will be replaced by a regular file). If you need to preserve links, you can use a temporary variable to store the output of sed before writing it back to the file, like this:
tmp=$(sed 'code' file); echo -n "$tmp" > file
Better yet, use printf
instead of echo
since echo
is likely to process \\
as \
in some shells (e.g. dash):
tmp=$(sed 'code' file); printf "%s" "$tmp" > file
You can check the version of your genymotion and virtualbox. The genymotion 2.5.3 would work better with virtualbox 4.3.30.
This works:
$string = 'A B C D';
$arr = preg_split('/[\s]+/', $string);
Here is my solution:
public String HMAC_SHA256(String secret, String message)
{
String hash="";
try{
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
hash = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
}catch (Exception e)
{
}
return hash.trim();
}
best solution TNX to Drew Chapin and all of you too:
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
my script:
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } ` -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
in the office doc: https://developer.android.com/reference/android/support/constraint/ConstraintLayout
When a dimension is set to MATCH_CONSTRAINT, the default behavior is to have the resulting size take all the available space.
Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"
Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent"
mvn clean install -U
-U means force update of dependencies.
If you want to update a single dependency without clean or -U you could just remove it from your local repo and then build.
you can just do
select rownum, l.* from student l where name like %ram%
this assigns the row number as the rows are fetched (so no guaranteed ordering of course).
if you wanted to order first do:
select rownum, l.*
from (select * from student l where name like %ram% order by...) l;
Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.
I recently got the same issue. Below solution is work for me:
let strValue = "123"
let result = (strValue as NSString).integerValue
-if gradle.properties not available then first add that file and
add
android.useDeprecatedNdk=true
-use this code in build.gradle
defaultConfig {
applicationId 'com.example.application'
minSdkVersion 16
targetSdkVersion 21
versionCode 11
versionName "1.1"
ndk {
abiFilters "armeabi"
}
}
`
// TestTree.java
// A simple test to see how we can build a tree and populate it
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class TestTree extends JFrame {
JTree tree;
DefaultTreeModel treeModel;
public TestTree( ) {
super("Tree Test Example");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void init( ) {
// Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the
// DefaultTreeModel can use it to build a complete tree.
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");
// Build our tree model starting at the root node, and then make a JTree out
// of it.
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
// Build the tree up from the nodes we created.
treeModel.insertNodeInto(subroot, root, 0);
// Or, more succinctly:
subroot.add(leaf1);
root.add(leaf2);
// Display it.
getContentPane( ).add(tree, BorderLayout.CENTER);
}
public static void main(String args[]) {
TestTree tt = new TestTree( );
tt.init( );
tt.setVisible(true);
}
}
os.path.commonprefix() and os.path.relpath() are your friends:
>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var']) # No common prefix: the root is the common prefix
'/'
You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:
paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
…
You can then find the relative paths:
relative_paths = [os.path.relpath(path, common_prefix) for path in paths]
You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.
PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().
PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:
>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'
even though /usr/var
is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix()
solves this (specific) problem.
PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?
PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()
), taking the intersection of all these parent sets, and selecting the longest common prefix.
PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath()
, which returns a valid path.
For people just stumbling upon this now, I resolved an error of this type that was thrown with all the references and using statements placed properly. There's evidently some confusion with substituting in a function that returns DataTable instead of calling it on a declared DataTable. For example:
This worked for me:
DataTable dt = SomeObject.ReturnsDataTable();
List<string> ls = dt.AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
But this didn't:
List<string> ls = SomeObject.ReturnsDataTable().AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
I'm still not 100% sure why, but if anyone is frustrated by an error of this type, give this a try.
New CSS Specs contain an experimental :has
pseudo selector that might be able to do this thing.
li:has(a:active) {
/* ... */
}
The browser support on this is basically non-existent at this time, but it is in consideration on the official specs.
While it is true that CSS cannot ASCEND, it is incorrect that you cannot grab the parent element of another element. Let me reiterate:
Using your HTML example code, you are able to grab the li without specifying li
ul * a {
property:value;
}
In this example, the ul is the parent of some element and that element is the parent of anchor. The downside of using this method is that if there is a ul with any child element that contains an anchor, it inherits the styles specified.
You may also use the child selector as well since you'll have to specify the parent element anyway.
ul>li a {
property:value;
}
In this example, the anchor must be a descendant of an li that MUST be a child of ul, meaning it must be within the tree following the ul declaration. This is going to be a bit more specific and will only grab a list item that contains an anchor AND is a child of ul.
SO, to answer your question by code.
ul.menu > li a.active {
property:value;
}
This should grab the ul with the class of menu, and the child list item that contains only an anchor with the class of active.
Change Minute parameter to 0.
You can set the cron for every three hours as:
0 */3 * * * your command here ..
You can replace image automatically with newly selected image.
<div class="image-upload">
<label for="file-input">
<img id="previewImg" src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg" style="width: 100px; height: 100px;" />
</label>
<input id="file-input" type="file" onchange="previewFile(this);" style="display: none;" />
</div>
<script>
function previewFile(input){
var file = $("input[type=file]").get(0).files[0];
if(file){
var reader = new FileReader();
reader.onload = function(){
$("#previewImg").attr("src", reader.result);
}
reader.readAsDataURL(file);
}
}
</script>
There's something I bet you already heard about this! It's called jQuery.
$("#button1").click(function() {
$("#form1").show();
};
It's really easy and you can use CSS-like selectors and you can add animations. It's really easy to learn.
The answers above all over complicate the story.
That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.
Creating .exe distributions isn't typical for Java. While such wrappers do exist, the normal mode of operation is to create a .jar file.
To create a .jar file from a Java project in Eclipse, use file->export->java->Jar file. This will create an archive with all your classes.
On the command prompt, use invocation like the following:
java -cp myapp.jar foo.bar.MyMainClass
What worked for me :
div#scrollable {
overflow-y: scroll;
max-height: 100vh;
}
Get simple name instead of path.
String onlyClassName = this.getLocalClassName();
call above method in onCreate
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
My answer is inspired by cjohnson318's answer, but I didn't want to supply a hardcoded list of labels; I wanted to rotate the existing labels:
for tick in ax.get_xticklabels():
tick.set_rotation(45)
I got the opportunity to use both memcached and redis together in the caching proxy that i have worked on , let me share you where exactly i have used what and reason behind same....
Redis >
1) Used for indexing the cache content , over the cluster . I have more than billion keys in spread over redis clusters , redis response times is quite less and stable .
2) Basically , its a key/value store , so where ever in you application you have something similar, one can use redis with bothering much.
3) Redis persistency, failover and backup (AOF ) will make your job easier .
Memcache >
1) yes , an optimized memory that can be used as cache . I used it for storing cache content getting accessed very frequently (with 50 hits/second)with size less than 1 MB .
2) I allocated only 2GB out of 16 GB for memcached that too when my single content size was >1MB .
3) As the content grows near the limits , occasionally i have observed higher response times in the stats(not the case with redis) .
If you ask for overall experience Redis is much green as it is easy to configure, much flexible with stable robust features.
Further , there is a benchmarking result available at this link , below are few higlight from same,
Hope this helps!!
Usually, this problem resolve with using the modulo of a number in a loop or convert a number to a string. For convert a number to a string, you may can use the function itoa, so considering the variant with the modulo of a number in a loop.
Content of a file get_digits.c
$ cat get_digits.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// return a length of integer
unsigned long int get_number_count_digits(long int number);
// get digits from an integer number into an array
int number_get_digits(long int number, int **digits, unsigned int *len);
// for demo features
void demo_number_get_digits(long int number);
int
main()
{
demo_number_get_digits(-9999999999999);
demo_number_get_digits(-10000000000);
demo_number_get_digits(-1000);
demo_number_get_digits(-9);
demo_number_get_digits(0);
demo_number_get_digits(9);
demo_number_get_digits(1000);
demo_number_get_digits(10000000000);
demo_number_get_digits(9999999999999);
return EXIT_SUCCESS;
}
unsigned long int
get_number_count_digits(long int number)
{
if (number < 0)
number = llabs(number);
else if (number == 0)
return 1;
if (number < 999999999999997)
return floor(log10(number)) + 1;
unsigned long int count = 0;
while (number > 0) {
++count;
number /= 10;
}
return count;
}
int
number_get_digits(long int number, int **digits, unsigned int *len)
{
number = labs(number);
// termination count digits and size of a array as well as
*len = get_number_count_digits(number);
*digits = realloc(*digits, *len * sizeof(int));
// fill up the array
unsigned int index = 0;
while (number > 0) {
(*digits)[index] = (int)(number % 10);
number /= 10;
++index;
}
// reverse the array
unsigned long int i = 0, half_len = (*len / 2);
int swap;
while (i < half_len) {
swap = (*digits)[i];
(*digits)[i] = (*digits)[*len - i - 1];
(*digits)[*len - i - 1] = swap;
++i;
}
return 0;
}
void
demo_number_get_digits(long int number)
{
int *digits;
unsigned int len;
digits = malloc(sizeof(int));
number_get_digits(number, &digits, &len);
printf("%ld --> [", number);
for (unsigned int i = 0; i < len; ++i) {
if (i == len - 1)
printf("%d", digits[i]);
else
printf("%d, ", digits[i]);
}
printf("]\n");
free(digits);
}
Demo with the GNU GCC
$~/Downloads/temp$ cc -Wall -Wextra -std=c11 -o run get_digits.c -lm
$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Demo with the LLVM/Clang
$~/Downloads/temp$ rm run
$~/Downloads/temp$ clang -std=c11 -Wall -Wextra get_digits.c -o run -lm
setivolkylany$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Testing environment
$~/Downloads/temp$ cc --version | head -n 1
cc (Debian 4.9.2-10) 4.9.2
$~/Downloads/temp$ clang --version
Debian clang version 3.5.0-10 (tags/RELEASE_350/final) (based on LLVM 3.5.0)
Target: x86_64-pc-linux-gnu
Thread model: posix
I believe that your problem is due to the fact that -
is not a word character. Thus, the word boundary will match after the -
, and so will not capture it. Word boundaries match before the first and after the last word characters in a string, as well as any place where before it is a word character or non-word character, and after it is the opposite. Also note that word boundary is a zero-width match.
One possible alternative is
(?:(?:^|\s)-?)\d+\b
This will match any numbers starting with a space character and an optional dash, and ending at a word boundary. It will also match a number starting at the beginning of the string.
Beyond how UTF is a superset of ASCII, another good difference to know between ASCII and UTF is in terms of disk file encoding and data representation and storage in random memory. Programs know that given data should be understood as an ASCII or UTF string either by detecting special byte order mark codes at the start of the data, or by assuming from programmer intent that the data is text and then checking it for patterns that indicate it is in one text encoding or another.
Using the conventional prefix notation of 0x
for hexadecimal data, basic good reference is that ASCII text starts with byte values 0x00
to 0x7F
representing one of the possible ASCII character values. UTF text is normally indicated by starting with the bytes 0xEF 0xBB 0xBF
for UTF8. For UTF16, start bytes 0xFE 0xFF
, or 0xFF 0xFE
are used, with the endian-ness order of the text bytes indicated by the order of the start bytes. The simple presence of byte values that are not in the ASCII range of possible byte values also indicates that data is probably UTF.
There are other byte order marks that use different codes to indicate data should be interpreted as text encoded in a certain encoding standard.
The standard Mysql rename statement is:
ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]
for this example:
ALTER TABLE xyz CHANGE manufacurerid manufacturerid datatype(length)
Reference: MYSQL 5.1 ALTER TABLE Syntax
If you like, you could declare an infix
operator
to do it.
// Put this at file level anywhere in your project
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i = 2 ^^ 3
// ... or
println("2³ = \(2 ^^ 3)") // Prints 2³ = 8
I used two carets so you can still use the XOR operator.
Update for Swift 3
In Swift 3 the "magic number" precedence
is replaced by precedencegroups
:
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// ...
// Then you can do this...
let i2 = 2 ^^ 3
// ... or
print("2³ = \(2 ^^ 3)") // Prints 2³ = 8
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
Thank for the question. But I have found my own solution to this problem. At first, I created a method
public T GetSettingsWithDictionary<T>() where T:new()
{
IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
.AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();
var instance = new T();
foreach (var property in typeof(T).GetProperties())
{
if (property.PropertyType == typeof(Dictionary<string, string>))
{
property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
break;
}
}
return instance;
}
Then I used this method to produce an instance of a class
var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();
I have the next declaration of class
public class AuthMongoConnectionStrings
{
public Dictionary<string, string> ConnectionStrings { get; set; }
}
and I store my setting in App.config
<configuration>
<AuthMongoConnectionStrings
First="first"
Second="second"
Third="33" />
</configuration>
Oh my days!!
Feel so embarrassed but it is my first day on the C++.
I was getting the error because of two things.
I opened an empty project
I didn't add #include "stdafx.h"
It ran successfully on the win 32 console.
The biggest issue being missed by most solutions here is that an element's width is often changed by CSS based on where it is scoped in html.
If I was to determine offsetWidth of an element by appending a clone of it to body when it has styles that only apply in its current scope I would get the wrong width.
for example:
//css
.module-container .my-elem{ border: 60px solid black; }
now when I try to determine my-elem's width in context of body it will be out by 120px. You could clone the module container instead, but your JS shouldn't have to know these details.
I haven't tested it but essentially Soul_Master's solution appears to be the only one that could work properly. But unfortunately looking at the implementation it will likely be costly to use and bad for performance (as most of the solutions presented here are as well.)
If at all possible then use visibility: hidden instead. This will still render the element, allowing you to calculate width without all the fuss.
In my case (dealing with my assemblies loaded [as file] into Outlook):
typeof(OneOfMyTypes).Assembly.CodeBase
Note the use of CodeBase
(not Location
) on the Assembly
. Others have pointed out alternative methods of locating the assembly.
I just had a jaw-drop moment - Termux allows you to install NodeJS on an Android device!
It seems to work for a basic Websocket Speed Test I had on hand. The http served by it can be accessed both locally and on the network.
There is a medium post that explains the installation process
Basically: 1. Install termux 2. apt install nodejs 3. node it up!
One restriction I've run into - it seems the shared folders don't have the necessary permissions to install modules. It might just be a file permission thing. The private app storage works just fine.
You can init a Git directory in an directory containing other files. After that you can add files to the repository and commit there.
Create a project with some code:
$ mkdir my_project
$ cd my_project
$ echo "foobar" > some_file
Then, while inside the project's folder, do an initial commit:
$ git init
$ git add some_file
$ git commit -m "Initial commit"
Then for using Bitbucket or such you add a remote
and push up:
$ git remote add some_name user@host:repo
$ git push some_name
You also might then want to configure tracking branches, etc. See git remote set-branches
and related commands for that.
use
<div class="btn-group btn-group-justified">
...
</div>
but it only works for <a> elements and not <button> elements.
see: http://getbootstrap.com/components/#btn-groups-justified
If you have directory listing disabled in your webserver, then the only way somebody will find it is by guessing or by finding a link to it.
That said, I've seen hacking scripts attempt to "guess" a whole bunch of these common names. "secret.html" would probably be in such a guess list.
The more reasonable solution is to restrict access using a username/password via a htaccess file (for apache) or the equivalent setting for whatever webserver you're using.
Restart Android Studio Worked in my case
Alternative using Path
(Java 7+):
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();
Note that splitting the string on \\
is platform dependent as the file separator might vary. Path#getName
takes care of that issue for you.
Here is a simple context manager that prints to the console and writes the same output to an file. It also writes any exceptions to the file.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
@marc_s's answer is very great and I've been using it for few years. However, I noticed that the script misses data in some columnstore indexes and doesn't show complete picture. E.g. when you do SUM(TotalSpace)
against the script and compare it with total space database property in Management Studio the numbers don't match in my case (Management Studio shows larger numbers). I modified the script to overcome this issue and extended it a little bit:
select
tables.[name] as table_name,
schemas.[name] as schema_name,
isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown') as database_name,
sum(allocation_units.total_pages) * 8 as total_space_kb,
cast(round(((sum(allocation_units.total_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as total_space_mb,
sum(allocation_units.used_pages) * 8 as used_space_kb,
cast(round(((sum(allocation_units.used_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as used_space_mb,
(sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8 as unused_space_kb,
cast(round(((sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8) / 1024.00, 2) as numeric(36, 2)) as unused_space_mb,
count(distinct indexes.index_id) as indexes_count,
max(dm_db_partition_stats.row_count) as row_count,
iif(max(isnull(user_seeks, 0)) = 0 and max(isnull(user_scans, 0)) = 0 and max(isnull(user_lookups, 0)) = 0, 1, 0) as no_reads,
iif(max(isnull(user_updates, 0)) = 0, 1, 0) as no_writes,
max(isnull(user_seeks, 0)) as user_seeks,
max(isnull(user_scans, 0)) as user_scans,
max(isnull(user_lookups, 0)) as user_lookups,
max(isnull(user_updates, 0)) as user_updates,
max(last_user_seek) as last_user_seek,
max(last_user_scan) as last_user_scan,
max(last_user_lookup) as last_user_lookup,
max(last_user_update) as last_user_update,
max(tables.create_date) as create_date,
max(tables.modify_date) as modify_date
from
sys.tables
left join sys.schemas on schemas.schema_id = tables.schema_id
left join sys.indexes on tables.object_id = indexes.object_id
left join sys.partitions on indexes.object_id = partitions.object_id and indexes.index_id = partitions.index_id
left join sys.allocation_units on partitions.partition_id = allocation_units.container_id
left join sys.dm_db_index_usage_stats on tables.object_id = dm_db_index_usage_stats.object_id and indexes.index_id = dm_db_index_usage_stats.index_id
left join sys.dm_db_partition_stats on tables.object_id = dm_db_partition_stats.object_id and indexes.index_id = dm_db_partition_stats.index_id
group by schemas.[name], tables.[name], isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown')
order by 5 desc
Hope it will be helpful for someone. This script was tested against large TB-wide databases with hundreds of different tables, indexes and schemas.
From Wikipedia,
The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip. On American Express cards, the Card Security Code is a printed (NOT embossed) group of four digits on the front towards the right.
The Card Security Code (CSC), sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV)[1] is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.
There are actually several types of security codes:
* The first code, called CVC1 or CVV1, is encoded on the magnetic stripe of the card and used for transactions in person.
* The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
* Contactless Card and Chip cards may supply their own codes generated electronically, such as iCVV or Dynamic CVV.
The CVC should not be confused with the standard card account number appearing in embossed or printed digits. (The standard card number undergoes a separate validation algorithm called the Luhn algorithm which serves to determine whether a given card's number is appropriate.)
The CVC should not be confused with PIN codes such as MasterCard SecureCode or Visa Verified by Visa. These codes are not printed or embedded in the card but are entered at the time of transaction using a keypad.
I create my own solution without label
input[type=checkbox] {_x000D_
position: relative;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type=checkbox]:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
width: 16px;_x000D_
height: 16px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
border: 2px solid #555555;_x000D_
border-radius: 3px;_x000D_
background-color: white;_x000D_
}_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 5px;_x000D_
height: 10px;_x000D_
border: solid black;_x000D_
border-width: 0 2px 2px 0;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
position: absolute;_x000D_
top: 2px;_x000D_
left: 6px;_x000D_
}
_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">
_x000D_
input[type=checkbox] {_x000D_
position: relative;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type=checkbox]:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
background-color:#e9e9e9;_x000D_
}_x000D_
input[type=checkbox]:checked:before {_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
top: 0;_x000D_
left: 0;_x000D_
background-color:#1E80EF;_x000D_
}_x000D_
input[type=checkbox]:checked:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 5px;_x000D_
height: 10px;_x000D_
border: solid white;_x000D_
border-width: 0 2px 2px 0;_x000D_
-webkit-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
position: absolute;_x000D_
top: 2px;_x000D_
left: 6px;_x000D_
}
_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">_x000D_
<input type="checkbox" name="a">
_x000D_
Debounced / throttled model updates for angularjs : http://jsfiddle.net/lgersman/vPsGb/3/
In your case there is nothing more to do than using the directive in the jsfiddle code like this:
<input
id="searchText"
type="search"
placeholder="live search..."
ng-model="searchText"
ng-ampere-debounce
/>
Its basically a small piece of code consisting of a single angular directive named "ng-ampere-debounce" utilizing http://benalman.com/projects/jquery-throttle-debounce-plugin/ which can be attached to any dom element. The directive reorders the attached event handlers so that it can control when to throttle events.
You can use it for throttling/debouncing * model angular updates * angular event handler ng-[event] * jquery event handlers
Have a look : http://jsfiddle.net/lgersman/vPsGb/3/
The directive will be part of the Orangevolt Ampere framework (https://github.com/lgersman/jquery.orangevolt-ampere).
Maybe you don't need it anymore but if someone needs this using node: https://www.npmjs.com/package/btoa
To whomever may have this issue. My problem was border-collapse. It was set to:
border-collapse: collapse;
I set it to:
border-collapse: separate;
and it fixed the issue.
I'd recommend raising the connection timeout time before getting the output stream, like so:
urlConnection.setConnectTimeout(1000);
Where 1000 is in milliseconds (1000 milliseconds = 1 second).
If you want to keep the database between uninstalls you have to put it on the SD Card. This is the only place that won't be deleted at the moment your app is deleted. But in return it can be deleted by the user every time.
If you put your DB on the SD Card you can't use the SQLiteOpenHelper anymore, but you can use the source and the architecture of this class to get some ideas on how to implement the creation, updating and opening of a databse.
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
Using !important will override element.style via CSS like Change
color: #7D7D7D;
to
color: #7D7D7D !important;
That should do it.
It depends on the compiler. If you compile with, say, G++ on Linux and VC++ on Windows, this will do :
#ifdef linux
...
#elif _WIN32
...
#else
...
#endif
I was also trying to join my path using path.join(__dirname, 'access.log')
but it was throwing the same error.
Here is how I fixed it:
I first imported the path package and declared a variable named __dirname
, then called the resolve
path method.
In CommonJS
var path = require("path");
var __dirname = path.resolve();
In ES6+
import path from 'path';
const __dirname = path.resolve();
Happy coding.......
I know this is hyper-optimization land, but it seemed like a good excuse to kick the wheels of BenchmarkDotNet
. The result of this test (on .NET Core even) is that Substring
is ever so slightly faster than Remove
, in this sample test: 19.37ns vs 22.52ns for Remove
. So some ~16% faster.
using System;
using BenchmarkDotNet.Attributes;
namespace BenchmarkFun
{
public class StringSubstringVsRemove
{
public readonly string SampleString = " My name is Daffy Duck.";
[Benchmark]
public string StringSubstring() => SampleString.Substring(1);
[Benchmark]
public string StringRemove() => SampleString.Remove(0, 1);
public void AssertTestIsValid()
{
string subsRes = StringSubstring();
string remvRes = StringRemove();
if (subsRes == null
|| subsRes.Length != SampleString.Length - 1
|| subsRes != remvRes) {
throw new Exception("INVALID TEST!");
}
}
}
class Program
{
static void Main()
{
// let's make sure test results are really equal / valid
new StringSubstringVsRemove().AssertTestIsValid();
var summary = BenchmarkRunner.Run<StringSubstringVsRemove>();
}
}
}
Results:
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.253 (1809/October2018Update/Redstone5)
Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100-preview-010184
[Host] : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
DefaultJob : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
| Method | Mean | Error | StdDev |
|---------------- |---------:|----------:|----------:|
| StringSubstring | 19.37 ns | 0.3940 ns | 0.3493 ns |
| StringRemove | 22.52 ns | 0.4062 ns | 0.3601 ns |
For only vertical center
<div style="text-align: left; position: relative;height: 56px;background-color: pink;">
<div style="background-color: lightblue;position:absolute;top:50%; transform: translateY(-50%);">test</div>
</div>
_x000D_
I always do like this, it's a very short and easy code to center both horizontally and vertically
.center{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
_x000D_
<div class="center">Hello Centered World!</div>
_x000D_
The direct way to handle the hide keyboard + done action in Kotlin is:
// Set action
edittext.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Hide Keyboard
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
true
}
false
}
Use this to call edittext.onDone {/*action*/}
in your main code. Keeps it more readable and maintainable
edittext.onDone { edittext.hideKeyboard() }
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun EditText.onDone(callback: () -> Unit) {
// These lines optional if you don't want to set in Xml
imeOptions = EditorInfo.IME_ACTION_DONE
maxLines = 1
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
}
If you'd like more ways to simplify working with the keyboard (show, close, focus): Read this post
Don't forget to add these options to your edittext Xml, if not in code
<EditText ...
android:imeOptions="actionDone"
android:inputType="text"/>
Need
inputType="textMultiLine"
support? Read this post and don't addimeOptions
orinputType
in Xml
In angular 9, Before tried 'Content-Type': undefined, but it is not worked for me then I tried the below code and It works like charms for a file object
const request = this.http.post(url, data, {
headers: {
'Content-Type': 'file'
},
});
To remote server
mysqldump mydbname | ssh host2 "mysql mydbcopy"
To local server
mysqldump mydbname | mysql mydbcopy
Try this Script:
function addclassName(){
setTimeout(function(){
var c = document.querySelectorAll(".modal-backdrop");
for (var i = 0; i < c.length; i++) {
c[i].style.zIndex = 1040 + i * 20 ;
}
var d = document.querySelectorAll(".modal.fade");
for(var i = 0; i<d.length; i++){
d[i].style.zIndex = 1050 + i * 20;
}
}, 10);
}
In addition to @Bruno's answer, you need to supply the -name
for alias, otherwise Tomcat will throw Alias name tomcat does not identify a key entry
error
Sample Command:
openssl pkcs12 -export -in localhost.crt -inkey localhost.key -out localhost.p12 -name localhost
In my case, I had to remove the following from the .csproj file:
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
In fact, in this snippet you can see where the error message is coming from.
I was converting from MSBuild-Integrated Package Restore to Automatic Package Restore (http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore)
Does not work for multidimensional arrays, because references are used here.
import numpy as np
# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)
# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)
See also Swap slices of Numpy arrays
I had this error once and I found out the origin:
I was using a gcc compiler and my file was called CLIENT.C
despite I was doing a C program and not a C++ program.
gcc recognizes the .C
extension as C++ program and .c
extension as C program (be careful to the small c and big C).
So I renamed my file CLIENT.c
program and it worked.
Check out docs-to-pdf-converter on github. Its a lightweight solution designed specifically for converting documents to pdf.
Why?
I wanted a simple program that can convert Microsoft Office documents to PDF but without dependencies like LibreOffice or expensive proprietary solutions. Seeing as how code and libraries to convert each individual format is scattered around the web, I decided to combine all those solutions into one single program. Along the way, I decided to add ODT support as well since I encountered the code too.
On Debian (isn't this the case for most Linux distros?), it's saved in /var/lib/php5/. As mentioned above, it's configured in your php.ini.
Use numpy.fromfunction(function, shape, **kwargs)
See "https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html"
NEW ANSWER Use Glide library for this. This lib is also recommended by Google. See How to round an image with Glide library?
OLD ANSWER
Just add that image in a cardView
and set cardView's elevation on 0dp...will do the trick (in my case was a viewPager
with images - just replace the viewPager
with an ImageView
):
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="250dp"
app:cardElevation="0dp">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
Another simple way:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete
I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:
Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.
This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
Advantages:
display:table-cell
(that's not meant for layouts)markup
SCSS
for those who use gulp
or grunt
// closes the modal on click/tap below/above the modal_x000D_
_x000D_
$('.modal-dialog').on('click tap', function(e){_x000D_
if (e.target.classList.contains('modal-dialog')) {_x000D_
$('.modal').modal('hide');_x000D_
}_x000D_
})
_x000D_
.modal-dialog {_x000D_
display: -webkit-box;_x000D_
display: -webkit-flex;_x000D_
display: -moz-box;_x000D_
display: -ms-flexbox;_x000D_
display: flex;_x000D_
-webkit-box-orient: vertical;_x000D_
-webkit-box-direction: normal;_x000D_
-webkit-flex-direction: column;_x000D_
-moz-box-orient: vertical;_x000D_
-moz-box-direction: normal;_x000D_
-ms-flex-direction: column;_x000D_
flex-direction: column;_x000D_
-webkit-box-pack: center;_x000D_
-webkit-justify-content: center;_x000D_
-moz-box-pack: center;_x000D_
-ms-flex-pack: center;_x000D_
justify-content: center;_x000D_
overflow-y: auto;_x000D_
min-height: -webkit-calc(100vh - 60px);_x000D_
min-height: -moz-calc(100vh - 60px);_x000D_
min-height: calc(100vh - 60px);_x000D_
}_x000D_
@media (max-width: 767px) {_x000D_
.modal-dialog {_x000D_
min-height: -webkit-calc(100vh - 20px);_x000D_
min-height: -moz-calc(100vh - 20px);_x000D_
min-height: calc(100vh - 20px);_x000D_
}_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
Launch demo modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Note: I intend to keep this answer up to date with the latest specs of Bootstrap 3. For a Bootstrap 4 solution, see this answer (for now they are more or less the same, but in time they might diverge). If you find any bug or problem with it, let me know and I will update. Thanks.
Clean, un-prefixed SCSS
(for use with gulp
/grunt
):
.modal-dialog {
display: flex;
flex-direction: column;
justify-content: center;
overflow-y: auto;
min-height: calc(100vh - 60px);
@media (max-width: 767px) {
min-height: calc(100vh - 20px);
}
}
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
run - Create a container using image and Start the same. (Create & Start)
start - Start the container(s) in docker list which was in stopped state.
MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.
The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.
By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)
The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.
As 18 8-bit chars: 144 bits
As 18 4-bit nybbles: 72 bits
As 2 32-bit integers: 64 bits
Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.
So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.
With an 7-bit int: 0 - 99
With a 15-bit int: 0 - 9,999
With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)
1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.
This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.
Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.
In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.
The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.
As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.
Use the chrome.runtime.id
property from the chrome.runtime API.
Please check if you have the following entries in the element of your pom.xml especially the jdk.version because switching to an installed jre did not fix me the similar error.
<properties>
<jdk.version>1.7</jdk.version>
<spring.version>4.1.1.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<junit.version>4.11</junit.version>
</properties>
While implied by other answers, it's not explicitly mentioned - that structs are C compatible, depending on usage; classes are not.
This means if you're writing a header that you want to be C compatible then you've no option other than struct (which in the C world can't have functions; but can have function pointers).
Use Libre Office API Here is an example
libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path
firstly, in your main page use a loading icon
then, delete your </body>
and </HTML>
from your main page and replace it by
<?php include('footer.php');?>
in the footer.php file type :
<?php
$iconPath="myIcon.ico" // myIcon is the final icon
echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
echo '</body>';
echo '</HTML>';
?>
public static bool IsNegative<T>(T value)
where T : struct, IComparable<T>
{
return value.CompareTo(default(T)) < 0;
}
This did the trick for me: I was able to find which macro called a particular query. Incidentally, the reason someone who does know how to code in VBA would want to write something like this is when they've inherited something macro-ish written by someone who doesn't know how to code in VBA.
Function utlFindQueryInMacro
( strMacroNameLike As String
, strQueryName As String
) As String
' (c) 2012 Doug Den Hoed
' NOTE: requires reference to Microsoft Scripting Library
Dim varItem As Variant
Dim strMacroName As String
Dim oFSO As New FileSystemObject
Dim oFS
Dim strFileContents As String
Dim strMacroNames As String
For Each varItem In CurrentProject.AllMacros
strMacroName = varItem.Name
If Len(strMacroName) = 0 _
Or InStr(strMacroName, strMacroNameLike) > 0 Then
'Debug.Print "*** MACRO *** "; strMacroName
Application.SaveAsText acMacro, strMacroName, "c:\temp.txt"
Set oFS = oFSO.OpenTextFile("c:\temp.txt")
strFileContents = ""
Do Until oFS.AtEndOfStream
strFileContents = strFileContents & oFS.ReadLine
Loop
Set oFS = Nothing
Set oFSO = Nothing
Kill "c:\temp.txt"
'Debug.Print strFileContents
If InStr(strFileContents, strQueryName) 0 Then
strMacroNames = strMacroNames & strMacroName & ", "
End If
End If
Next varItem
MsgBox strMacroNames
utlFindQueryInMacro = strMacroNames
End Function
#define PADDING 5
@interface MyLabel : UILabel
@end
@implementation MyLabel
- (void)drawTextInRect:(CGRect)rect {
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(0, PADDING, 0, PADDING))];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
return CGRectInset([self.attributedText boundingRectWithSize:CGSizeMake(999, 999)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil], -PADDING, 0);
}
@end
You can also use function truncate
$truncate -s0 yourfile
if permission denied, use sudo
$sudo truncate -s0 yourfile
Help/Manual: man truncate
tested on ubuntu Linux
I use grep for removing prefixes from paths (which aren't handled well by sed
):
echo "$input" | grep -oP "^$prefix\K.*"
\K
removes from the match all the characters before it.
Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
Feature Matrix of Bean Factory vs Application Context sourced from spring docs
Screenshot of features of BeanFacotry and ApplicationContext
first convert your array too JSON
while($query->fetch()){
$col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
then vonvert back it to array
foreach($col as &$array){
$array = json_decode($array,true);
}
good luck
I took what you had, and added another X-Testing
header
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose',
"X-Testing" : "testing"
}
};
$http.get("/test", config);
And in the Chrome network tab, I see them being sent.
GET /test HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Accept: application/json;odata=verbose
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Authorization: Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==
X-Testing: testing
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Are you not seeing them from the browser, or on the server? Try the browser tooling or a debug proxy and see what is being sent out.
From Java 9, you can use the stream provided by Matcher.results()
long matches = matcher.results().count();
There is one way to make an immutable array in Java:
final String[] IMMUTABLE = new String[0];
Arrays with 0 elements (obviously) cannot be mutated.
This can actually come in handy if you are using the List.toArray
method to convert a List
to an array. Since even an empty array takes up some memory, you can save that memory allocation by creating a constant empty array, and always passing it to the toArray
method. That method will allocate a new array if the array you pass doesn't have enough space, but if it does (the list is empty), it will return the array you passed, allowing you to reuse that array any time you call toArray
on an empty List
.
final static String[] EMPTY_STRING_ARRAY = new String[0];
List<String> emptyList = new ArrayList<String>();
return emptyList.toArray(EMPTY_STRING_ARRAY); // returns EMPTY_STRING_ARRAY
if (true)
{
return View();
}
else
{
return View("another view name");
}
Might this can help you too. I have used this function to get classes of childern element..
function getClickClicked(){
var clickedElement=null;
var classes = null;<--- this is array
ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
clickedElement = $(e.target);
classes = clickedElement.attr("class").split(" ");
for(var i = 0; i<classes.length;i++){
console.log(classes[i]);
}
e.preventDefault();
});
}
In your case you want doler_ipsum class u can do like this now calsses[2];
.
One liner with java-8:
String str = "testString";
//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray =
str.chars().mapToObj(c -> (char)c).toArray(Character[]::new);
What it does is:
IntStream
of the characters (you may want to also look at codePoints()
)Character
(you need to cast to actually say that its really a char
, and then Java will box it automatically to Character
)toArray()
It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).
For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.
[Edit]
With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!
If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s///
should be all you need:
#!/usr/bin/perl -w
use strict;
main();
sub main{
my $foo = "blahblahblah";
print '$foo: ' , replace("lah","ar",$foo) , "\n"; #$foo: barbarbar
}
sub replace {
my ($from,$to,$string) = @_;
$string =~s/$from/$to/ig; #case-insensitive/global (all occurrences)
return $string;
}
Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker
It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.
The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker
There is no built-in auto_increment in Oracle.
You need to use sequences
and triggers
.
Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")
I found python in 1988 and fell in love with it. Our group at work had been dissolved and we were looking for other jobs on site, so I had a couple of months to play around doing whatever I wanted to. I spent the time profitably learning and using python. I suggest you spend time thinking up and writing utilities and various useful tools. I've got 200-300 in my python tools library now (can't even remember them all). I learned python from Guido's tutorial, which is a good place to start (a C programmer will feel right at home).
python is also a great tool for making models -- physical, math, stochastic, etc. Use numpy and scipy. It also wouldn't hurt to learn some GUI stuff -- I picked up wxPython and learned it, as I had some experience using wxWidgets in C++. wxPython has some impressive demo stuff!
It prints true
on my machine. And it should, otherwise nothing in Java would work as expected. (This is explained in the JLS: 4.3.4 When Reference Types Are the Same)
Do you have multiple classloaders in place?
Ah, and in response to this comment:
I realise I have a typo in my question. I should be like this:
MyImplementedObject obj = new MyImplementedObject ();
if(obj.getClass() == MyObjectInterface.class) System.out.println("true");
MyImplementedObject implements MyObjectInterface So in other words, I am comparing it with its implemented objects.
OK, if you want to check that you can do either:
if(MyObjectInterface.class.isAssignableFrom(obj.getClass()))
or the much more concise
if(obj instanceof MyobjectInterface)
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
This project has been tested with Xcode 10 and Swift 4.2.
It can be just a Single View App.
Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell
. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
}
We will connect this outlet later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
Notes
UICollectionViewDataSource
and UICollectionViewDelegate
are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout
protocol to change the size of the views programmatically, but it isn't necessary.Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.
Make sure that your defaults in the Attribute Inspector are also
The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.
Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell"
in ViewController.swift.
And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell
, our custom class that we made.
myLabel
in the MyCollectionViewCell
class. (You can Control-drag.)delegate
and dataSource
to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.
The example above works but it is rather ugly. Here are a few things you can play with:
Background color
In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.
Cell spacing
Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.
Cell shape
If you want rounded corners, a border, and the like, you can play around with the cell layer
. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan
in code above.
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8
See this answer for other things you can do with the layer (shadow, for example).
Changing the color when tapped
It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController
class:
// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.cyan
}
Here is the updated look:
Alternatively, consider The Glass Pane, discussed in the article How to Use Root Panes. You could draw your "Feature" content in the glass pane's paintComponent()
method.
Addendum: Working with the GlassPaneDemo, I added an image:
//Set up the content pane, where the "main GUI" lives.
frame.add(changeButton, BorderLayout.SOUTH);
frame.add(new JLabel(new ImageIcon("img.jpg")), BorderLayout.CENTER);
and altered the glass pane's paintComponent()
method:
protected void paintComponent(Graphics g) {
if (point != null) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f));
g2d.setColor(Color.yellow);
g2d.fillOval(point.x, point.y, 120, 60);
}
}
As noted here, Swing components must honor the opaque property; in this variation, the ImageIcon
completely fills the BorderLayout.CENTER
of the frame's default layout.
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
Add a Button or link to your page like this
<p><a href="#inline">click to open</a></p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.
In my case, when I went to the Targetted Runtimes, screen, Tomcat 7 was not listed (disabled) despite being installed.
To fix, I had to go to Preferences->Server->Runtime Environments then uninstall and reinstall Tomcat 7.
A functional requirement describes what a software system should do, while non-functional requirements place constraints on how the system will do so.
Let me elaborate.
An example of a functional requirement would be:
A related non-functional requirement for the system may be:
The functional requirement is describing the behavior of the system as it relates to the system's functionality. The non-functional requirement elaborates a performance characteristic of the system.
Typically non-functional requirements fall into areas such as:
A more complete list is available at Wikipedia's entry for non-functional requirements.
Non-functional requirements are sometimes defined in terms of metrics (i.e. something that can be measured about the system) to make them more tangible. Non-functional requirements may also describe aspects of the system that don't relate to its execution, but rather to its evolution over time (e.g. maintainability, extensibility, documentation, etc.).
If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum
, which may be is faster than FFT based methods:
EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. EDIT
def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
>>> a = np.arange(20)
>>> moving_average(a)
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.,
12., 13., 14., 15., 16., 17., 18.])
>>> moving_average(a, n=4)
array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5,
10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5])
So I guess the answer is: it is really easy to implement, and maybe numpy is already a little bloated with specialized functionality.
I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?
Google Gson supports generics and nested beans. The []
in JSON represents an array and should map to a Java collection such as List
or just a plain Java array. The {}
in JSON represents an object and should map to a Java Map
or just some JavaBean class.
You have a JSON object with several properties of which the groups
property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson()
.
Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.
Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;
This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.
SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.
I would expect XlsIO to have something similar.
Disclaimer: I own SpreadsheetGear LLC
You'll get that error once your numbers are greater than sys.maxsize
:
>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
You can confirm this by checking:
>>> import sys
>>> sys.maxsize
2147483647
To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:
>>> preds = np.zeros((1, 3))
MySQLI example where $con is the database connection variable and table name is: mytable.
mysqli_query($con,'TRUNCATE TABLE mytable');
Short answer in bolds:
collect
is mainly to serialize
(loss of parallelism preserving all other data characteristics of the dataframe)
For example with a PrintWriter pw
you can't do direct df.foreach( r => pw.write(r) )
, must to use collect
before foreach
, df.collect.foreach(etc)
.
PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.
select
is mainly to select columns, similar to projection in relational algebra
(only similar in framework's context because Spark select
not deduplicate data).
So, it is also a complement of filter
in the framework's context.
Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select
) and actions (as collect
). It is also good remember that transforms (including select
) are lazily evaluated.
You could also just do it in one go, by doing the sort first and using head to take the first 3 of each group.
In[34]: df.sort_values(['job','count'],ascending=False).groupby('job').head(3)
Out[35]:
count job source
4 7 sales E
2 6 sales C
1 4 sales B
5 5 market A
8 4 market D
6 3 market B
Building on @general03's answer, you can use Android's built-in style to customize the dialog quickly. You can find the dialog themes under android.R.style.Theme_DeviceDefault_Dialogxxx
.
For example:
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_MinWidth);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_DialogWhenLarge);
Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at
and updated_at
fields.
class TimeStampMixin(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.
class Posts(TimeStampMixin):
name = models.CharField(max_length=50)
...
...
In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)
for Play 2.5.x and Play 2.6.x
sbt "-Dhttp.port=9002"
then
run
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);
If this is a submit button, use <input type="image" src="..." ... />
.
http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html
If you want to specify the image with CSS, you'll have to use type="submit"
.
Javascript, the language, came first, from Netscape.
Microsoft reverse engineered Javascript and called it JScript to avoid trademark issues with Sun. (Netscape and Sun were partnered up at the time, so this was less of an issue)
The languages are identical, both are dialects of ECMA script, the after-the-fact standard.
Although the languages are identical, since JScript runs in Internet Explorer, it has access to different objects exposed by the browser (such as ActiveXObject)
Check this: How Do I Force the Browser to Use the Newest Version of my Stylesheet?
Assumming your css file is foo.css
, you can force the client to use the latest version by appending a query string as shown below.
<link rel="stylesheet" href="foo.css?v=1.1">
Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.
For best useful I create this function:
func dateFormatting() -> String {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
let mydt = dateFormatter.string(from: date).capitalized
return "\(mydt)"
}
You simply call it wherever you want like this:
print("Date = \(self.dateFormatting())")
this is the Output:
Date = Monday 15 October 2018 - 17:26:29
if want only the time simply change :
dateFormatter.dateFormat = "HH:mm:ss"
and this is the output:
Date = 17:27:30
and that's it...
Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.
Meanwhile you have to use double quotes not single quote to expand variables:
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
Semicolons at the end of a single command are also unnecessary.
So far:
#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
For su
you can run it with:
su -c 'sh /path/to/script.sh'
Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using .
or source
from the interactive shell. It could have been a standalone scipt, or it could have been source
'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.
TL;DR:
The ActionListener
s (there can be multiple) execute in the order they were registered BEFORE the action
Long Answer:
A business action
typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view
if that is not what you are doing an actionListener
is more appropriate i.e. for when the user interacts with the components, such as h:commandButton
or h:link
they can be handled by passing the name of the managed bean method in actionListener
attribute of a UI Component or to implement an ActionListener
interface and pass the implementation class name to actionListener
attribute of a UI Component.
Since you're looking for the ability to shoehorn binary data into a strictly text-based and very limited format, I think Base64's overhead is minimal compared to the convenience you're expecting to maintain with JSON. If processing power and throughput is a concern, then you'd probably need to reconsider your file formats.
A reference can not be NULL. The interface makes you pass a real object into the function.
So there is no need to test for NULL. This is one of the reasons that references were introduced into C++.
Note you can still write a function that takes a pointer. In this situation you still need to test for NULL. If the value is NULL then you return early just like in C. Note: You should not be using exceptions when a pointer is NULL. If a parameter should never be NULL then you create an interface that uses a reference.
You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.
Read up on the lock statement.
EDIT
Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.
public class Queue<T>
{
/// <summary>Used as a lock target to ensure thread safety.</summary>
private readonly Locker _Locker = new Locker();
private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();
/// <summary></summary>
public void Enqueue(T item)
{
lock (_Locker)
{
_Queue.Enqueue(item);
}
}
/// <summary>Enqueues a collection of items into this queue.</summary>
public virtual void EnqueueRange(IEnumerable<T> items)
{
lock (_Locker)
{
if (items == null)
{
return;
}
foreach (T item in items)
{
_Queue.Enqueue(item);
}
}
}
/// <summary></summary>
public T Dequeue()
{
lock (_Locker)
{
return _Queue.Dequeue();
}
}
/// <summary></summary>
public void Clear()
{
lock (_Locker)
{
_Queue.Clear();
}
}
/// <summary></summary>
public Int32 Count
{
get
{
lock (_Locker)
{
return _Queue.Count;
}
}
}
/// <summary></summary>
public Boolean TryDequeue(out T item)
{
lock (_Locker)
{
if (_Queue.Count > 0)
{
item = _Queue.Dequeue();
return true;
}
else
{
item = default(T);
return false;
}
}
}
}
EDIT 2
I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.
public class WorkState
{
private readonly Object _Lock = new Object();
private Int32 _State;
public Int32 GetState()
{
lock (_Lock)
{
return _State;
}
}
public void UpdateState()
{
lock (_Lock)
{
_State++;
}
}
}
public class Worker
{
private readonly WorkState _State;
private readonly Thread _Thread;
private volatile Boolean _KeepWorking;
public Worker(WorkState state)
{
_State = state;
_Thread = new Thread(DoWork);
_KeepWorking = true;
}
public void DoWork()
{
while (_KeepWorking)
{
_State.UpdateState();
}
}
public void StartWorking()
{
_Thread.Start();
}
public void StopWorking()
{
_KeepWorking = false;
}
}
private void Execute()
{
WorkState state = new WorkState();
Worker worker = new Worker(state);
worker.StartWorking();
while (true)
{
if (state.GetState() > 100)
{
worker.StopWorking();
break;
}
}
}
If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:
Right click your project folder and open up Properties.
From the right panel, select Java Build Path then go to Libraries tab.
Select Add External JARs to import the mysql driver.
From the right panel, select Deployment Assembly.
Select Add..., then select Java Build Path Entries and click Next.
You should see the sql driver on the list. Select it and click first.
And that's it! Try to run it again! Cheers!
There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery
in Apache commons-httpclient project
Like this (see URIUtil):
URIUtil.encodeQuery("http://www.google.com?q=a b")
will become:
http://www.google.com?q=a%20b
You can of course do it yourself, but URI parsing can get pretty messy...
This should do what you want:
$("#iframe").ready(function() {
var body = $("#iframe").contents().find("body");
body.append('Test');
});
Check this JSFiddle for working demo.
Edit: You can of course do it one line style:
$("#iframe").contents().find("body").append('Test');
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("@Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
You need
@ManagedBean(name="userBean")
Make sure you have getUser()
method.
Type of setUser()
method should be void
.
Make sure that User
class has proper setters
and getters
as well.
1. Change your DOCTYPE to something less strict. Don't use XHTML; it's silly. Just use the HTML 5 doctype and you're good:
<!doctype html>
2. You might need to make sure (depends on the browser) that the iframe's parent has a height. And its parent. And its parent. Etc:
html, body { height: 100%; }
When changing icon size with
UIEdgeInsetsMake(top, left, bottom, right)
, keep in mind button dimensions and the ability of UIEdgeInsetsMake to work with negative values as if they are positive.
Example: Two buttons with height 100 and aspect 1:1.
left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(45, 0, 45, 0)
left.imageEdgeInsets = UIEdgeInsetsMake(40, 0, 40, 0)
right.imageEdgeInsets = UIEdgeInsetsMake(60, 0, 60, 0)
Examples 1 and 3 are identical since ABS(100 - (40 + 40)) = ABS(100 - (60 + 60))
I've found a way around the top answer's complications, just by concatenating the variable rand to another variable that allows that number to be displayed inside the calling of myArray[];. By deleting the new array created and toying around with it's complications, I've come up with a working solution:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myArray = ['January', 'February', 'March', 'April', 'May'];
var rand = Math.floor(Math.random() * myArray.length);
var concat = myArray[rand];
function random() {
document.getElementById("demo").innerHTML = (concat);
}
</script>
<button onClick="random();">
Working Random Array generator
</button>
</body>
</html>
My advice is: don't do it!
Any scenario where you treat people as "wrongdoers" is going to result in them fighting back.
Here's my proposal.
Put a small unobtrusive message at the top of the page (regardless of whether ads are being blocked) with the text I *totally* respect your right to block ads
and a link to another page/pop-up entitled Read more ...
.
On the other page, make it clear that you understand it's their computer and they are free to use ad blocking.
Also make it clear in a non-accusatory way that the use of these blockers makes it more difficult for you to deliver great content (explaining why in detail) and that, while you'd prefer the ad blocking to not happen on your site, it's totally their decision. Focus on the positives of turning off blocking.
Those who are vehemently opposed to ads will ignore this but you never stood a chance of convincing them anyway. Those who are indifferent may well be swayed by your appeal since you're not doing the whole "let me get my way or I'll take my ball and go home" thing that honestly should be the exclusive domain of five year old children.
Remember, no-one held a gun to your head and forced you to put your stuff on the net. Treat your readership/users with respect and you'll probably find a good number of them will reciprocate.
What database are you on? With MS SQL Server, it's a database-wide setting, or you can over-ride it per-query with the COLLATE keyword.
I managed to stop the video using "get(0)" (Retrieve the DOM elements matched by the jQuery object):
$("#closeSimple").click(function() {
$("div#simpleModal").removeClass("show");
$("#videoContainer").get(0).pause();
return false;
});
Example
original
https://raw.githubusercontent.com/antelove19/qrcodejs/master/qrcode.min.js
cdn.jsdelivr.net
https://cdn.jsdelivr.net/gh/antelove19/qrcodejs/qrcode.min.js
I use it and I'm happy with it, as I have to type much less to make a new header. It worked fine for me in three platforms: Windows, Mac and Linux.
I don't have any performance information but I believe that the difference between #pragma and the include guard will be nothing comparing to the slowness of parsing the C++ grammar. That's the real problem. Try to compile the same number of files and lines with a C# compiler for example, to see the difference.
In the end, using the guard or the pragma, won't matter at all.
alter table table_name
rename column old_column_name/field_name to new_column_name/field_name;
example: alter table student column name to username;
Here is how the problem can solved in Java 8 just like the answer by shamimz.
Source : http://docs.oracle.com/javase/tutorial/datetime/iso/period.html
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() + " months, and " + p.getDays() + " days old. (" + p2 + " days total)");
The code produces output similar to the following:
You are 53 years, 4 months, and 29 days old. (19508 days total)
We have to use LocalDateTime http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html to get hour,minute,second differences.
Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.
However i found a solution. Maybe this solution helps other coders who have problem like mine.
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat
.
And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.
*PS = I am not sure about stride value but for 8bit it should be equal to columns.
And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
MP4 is just a container - the video and audio stream inside it will both be encoded in different formats.
Android natively only supports certain types of formats. This is the list here.
Make sure the video and audio encoding type is supported. Just because it says "mp4" doesn't automatically mean it should be playable.
With Swift 5, you can use String
's init(data:encoding:)
initializer in order to convert a Data
instance into a String
instance using UTF-8. init(data:encoding:)
has the following declaration:
init?(data: Data, encoding: String.Encoding)
Returns a
String
initialized by converting given data into Unicode characters using a given encoding.
The following Playground code shows how to use it:
import Foundation
let json = """
{
"firstName" : "John",
"lastName" : "Doe"
}
"""
let data = json.data(using: String.Encoding.utf8)!
let optionalString = String(data: data, encoding: String.Encoding.utf8)
print(String(describing: optionalString))
/*
prints:
Optional("{\n\"firstName\" : \"John\",\n\"lastName\" : \"Doe\"\n}")
*/
You can use the ProcessLifecycleOwner attaching a lifecycle observer to it.
public class ForegroundLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onAppCreated() {
Timber.d("onAppCreated() called");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppStarted() {
Timber.d("onAppStarted() called");
}
@OnLifecycleEvent(Event.ON_RESUME)
public void onAppResumed() {
Timber.d("onAppResumed() called");
}
@OnLifecycleEvent(Event.ON_PAUSE)
public void onAppPaused() {
Timber.d("onAppPaused() called");
}
@OnLifecycleEvent(Event.ON_STOP)
public void onAppStopped() {
Timber.d("onAppStopped() called");
}
}
then on the onCreate()
of your Application class you call this:
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ForegroundLifecycleObserver());
with this you will be able to capture the events of ON_PAUSE
and ON_STOP
of your application that happen when it goes in background.
Android Studio 3.5.3
Find the Memory Settings (Cmd + Shift + A on Mac or click on Help and start typing "Memory Settings") under Preferences/ Settings and increase the IDE Heap Size and/ or the Daemon Heap Size to your satisfaction
you have to assign null or empty string here
this.searchValue = null;
//or
this.searchValue = ' ';
because no event is being fired from angular change detection. so you have to assign some value either null or string with space
[(ngModel)]
it should work with ngModel
.why ?
because as you did binding with value
attribute which is only property binding not event binding. so
angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.
see working example of same with ngModel
I know this is a jQuery
related question, but I believe someone might get here expecting a pure Javascript
solution. So, if you were trying to do this using js
, you could use the innerHTML
property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:
in your onCreate you'll need to use a webview and assign a WebViewClient, as below:
browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());
then handle the click on a phone number like this:
private class InternalWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("tel:") > -1) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
Let me know if you need more pointers.
public static string Reverse(string input)
{
return string.Concat(Enumerable.Reverse(input));
}
Of course you can extend string class with Reverse method
public static class StringExtensions
{
public static string Reverse(this string input)
{
return string.Concat(Enumerable.Reverse(input));
}
}
Try this
SELECT CONCAT('"',GROUP_CONCAT(id),'"') FROM table_level
where parent_id=4 group by parent_id;
Result will be
"5,6,9,10,12,14,15,17,18,779"
I just want to clarify, because some of the answers refer to venv
and others refer to virtualenv
.
Use of the -p
or --python
flag is supported on virtualenv
, but not on venv
. If you have more than one Python version and you want to specify which one to create the venv
with, do it on the command line, like this:
malikarumi@Tetuoan2:~/Projects$ python3.6 -m venv {path to pre-existing dir you want venv in}
You can of course upgrade with venv
as others have pointed out, but that assumes you have already upgraded the Python that was used to create that venv
in the first place. You can't upgrade to a Python version you don't already have on your system somewhere, so make sure to get the version you want, first, then make all the venvs you want from it.
With async/await and promisification.
const crypto = require('crypto')
const randomBytes = Util.promisify(crypto.randomBytes)
const plain = (await randomBytes(24)).toString('base64').replace(/\W/g, '')
Generates something similar to VjocVHdFiz5vGHnlnwqJKN0NdeHcz8eM
Don't know another way of checking this, but this: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#getProperties()" implies "java.version" is a standard system property so I'd expect it to work with other JVMs.
Here's how and don't forget to check that the property is not on the prototype chain:
var element_count = 0;
for(var e in myArray)
if(myArray.hasOwnProperty(e))
element_count++;