This allows you to just get the image data and set to the img src, which is cool.
var oReq = new XMLHttpRequest();
oReq.open("post", '/somelocation/getmypic', true );
oReq.responseType = "blob";
oReq.onload = function ( oEvent )
{
var blob = oReq.response;
var imgSrc = URL.createObjectURL( blob );
var $img = $( '<img/>', {
"alt": "test image",
"src": imgSrc
} ).appendTo( $( '#bb_theImageContainer' ) );
window.URL.revokeObjectURL( imgSrc );
};
oReq.send( null );
The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.
Why don't you use the MySQL built in password hasher:
http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
for comparison you could something like this:
select id from PassworTable where Userid='<userid>' and Password=PASSWORD('<password>')
and if it returns a value then the user is correct.
I'm keeping the following list updated for a couple of years now:
1.0.0.0/24
1.1.1.0/24
1.2.3.0/24
8.6.48.0/21
8.8.8.0/24
8.35.192.0/21
8.35.200.0/21
8.34.216.0/21
8.34.208.0/21
23.236.48.0/20
23.251.128.0/19
63.161.156.0/24
63.166.17.128/25
64.9.224.0/19
64.18.0.0/20
64.233.160.0/19
64.233.171.0/24
65.167.144.64/28
65.170.13.0/28
65.171.1.144/28
66.102.0.0/20
66.102.14.0/24
66.249.64.0/19
66.249.92.0/24
66.249.86.0/23
70.32.128.0/19
72.14.192.0/18
74.125.0.0/16
89.207.224.0/21
104.154.0.0/15
104.132.0.0/14
107.167.160.0/19
107.178.192.0/18
108.59.80.0/20
108.170.192.0/18
108.177.0.0/17
130.211.0.0/16
142.250.0.0/15
144.188.128.0/24
146.148.0.0/17
162.216.148.0/22
162.222.176.0/21
172.253.0.0/16
173.194.0.0/16
173.255.112.0/20
192.158.28.0/22
193.142.125.0/28
199.192.112.0/22
199.223.232.0/21
206.160.135.240/24
207.126.144.0/20
208.21.209.0/24
209.85.128.0/17
216.239.32.0/19
If you've deleted your root
user by mistake you can do one thing:
mysqld_safe --skip-grant-tables &
mysql -u root -p
and press enter.use mysql;
Then execute this query:
insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
then restart the mysqld
EDIT: October 6, 2018
In case anyone else needs this answer, I tried it today using innodb_version 5.6.36-82.0 and 10.1.24-MariaDB and it works if you REMOVE THE BACKTICKS (no single quotes either, just remove them):
insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, ssl_type, ssl_cipher, x509_issuer, x509_subject, max_questions, max_updates, max_connections, max_user_connections)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
If you want to have all the classes, that belong to the current module, you could use this :
import sys, inspect
def print_classes():
is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)
If you use Nadia's answer and you were importing other classes on your module, that classes will be being imported too.
So that's why member.__module__ == __name__
is being added to the predicate used on is_class_member
. This statement checks that the class really belongs to the module.
A predicate is a function (callable), that returns a boolean value.
Or better
window.location.assign("relative or absolute address");
that tends to work best across all browsers and mobile
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
#many .more.selectors h4 + p { ... }
This is called the adjacent sibling selector.
Easy solution in Python3+:
import time
todaysdate = time.strftime("%d/%m/%Y")
#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")
session = (Session) getEntityManager().getDelegate();
Criteria criteria = session.createCriteria(ComputedProdDaily.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("user.id"), "userid");
projList.add(Projections.property("loanState"), "state");
criteria.setProjection(Projections.distinct(projList));
criteria.add(Restrictions.isNotNull("this.loanState"));
criteria.setResultTransformer(Transformers.aliasToBean(UserStateTransformer.class));
This helped me :D
The good way to draw a Drawable on a canvas is not decoding it yourself but leaving it to the system to do so:
Drawable d = getResources().getDrawable(R.drawable.foobar, null);
d.setBounds(left, top, right, bottom);
d.draw(canvas);
This will work with all kinds of drawables, not only bitmaps. And it also means that you can re-use that same drawable again if only the size changes.
One of the most direct ways to use optionals is the following:
Assuming xyz
is of optional type, like Int?
for example.
if let possXYZ = xyz {
// do something with possXYZ (the unwrapped value of xyz)
} else {
// do something now that we know xyz is .None
}
This way you can both test if xyz
contains a value and if so, immediately work with that value.
With regards to your compiler error, the type UInt8
is not optional (note no '?') and therefore cannot be converted to nil
. Make sure the variable you're working with is an optional before you treat it like one.
Swift 4.2
func isValid(_ object:AnyObject!) -> Bool
{
if let _:AnyObject = object
{
return true
}
return false
}
Usage
if isValid(selectedPost)
{
savePost()
}
Simply remove the dot for the relative import and do:
from p_02_paying_debt_off_in_a_year import compute_balance_after
Change in your html with adding the function on the button click
<input type="button" value="Clear" onclick="javascript:eraseText();">
<textarea id='output' rows=20 cols=90></textarea>
Try this in your js file:
function eraseText() {
document.getElementById("output").value = "";
}
What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.
If you load the search criteria from elsewhere, then you should probably have some mapping logic.
I would recommend you using the Conditional Attribute!
Update: 3.5 years later
You can use #if
like this (example copied from MSDN):
// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass
{
static void Main()
{
#if (DEBUG && !VC_V7)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
Console.WriteLine("DEBUG and VC_V7 are defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}
Only useful for excluding parts of methods.
If you use #if
to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.
If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if
with a method that returns a value you have to hide all pieces of code that call it too.
Here is an example:
// calling Class1.ConditionalMethod() will be ignored at runtime // unless the DEBUG constant is defined using System.Diagnostics; class Class1 { [Conditional("DEBUG")] public static void ConditionalMethod() { Console.WriteLine("Executed Class1.ConditionalMethod"); } }
Summary:
I would use #ifdef
in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though.
You may want to use #if
to avoid dependencies because with Conditional attribute your code is still compiled.
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.setLayoutParams(labelLayoutParams);
// If you want to add some controls in this Relative Layout
labelLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
ImageView mImage = new ImageView(this);
mImage.setBackgroundResource(R.drawable.popupnew_bg);
layout.addView(mImage,labelLayoutParams);
setContentView(layout);
If you want to round the decimal, look at Math.Round()
Another important point
JAX-WS represents SOAP
JAX-RS represents REST
How to choose between JAX-RS and JAX-WS web services implementation?
As an appendix to Clint's answer, you can simplify PackageResource
using contextlib.contextmanager
:
@contextlib.contextmanager
def packageResource():
class Package:
...
package = Package()
yield package
package.cleanup()
Alternatively, though probably not as Pythonic, you can override Package.__new__
:
class Package(object):
def __new__(cls, *args, **kwargs):
@contextlib.contextmanager
def packageResource():
# adapt arguments if superclass takes some!
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
yield package
package.cleanup()
def __init__(self, *args, **kwargs):
...
and simply use with Package(...) as package
.
To get things shorter, name your cleanup function close
and use contextlib.closing
, in which case you can either use the unmodified Package
class via with contextlib.closing(Package(...))
or override its __new__
to the simpler
class Package(object):
def __new__(cls, *args, **kwargs):
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
return contextlib.closing(package)
And this constructor is inherited, so you can simply inherit, e.g.
class SubPackage(Package):
def close(self):
pass
In addition to indexOf
(which other posters have suggested), using prototype's Enumerable.include() can make this more neat and concise:
var list = ['a', 'b', 'c'];
if (list.include(str)) {
// do stuff
}
Escape your HTML tags ...
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
#For scheduling task execution
import schedule
import time
def job():
print("I'm working...")
schedule.every(1).minutes.do(job)
#schedule.every().hour.do(job)
#schedule.every().day.at("10:30").do(job)
#schedule.every(5).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("13:15").do(job)
#schedule.every().minute.at(":17").do(job)
while True:
schedule.run_pending()
time.sleep(1)
If you're swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it's also a one liner.
public static void swap(int[] arr, int i, int j) {
arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}
What I've seen from some primitive benchmarks is that the performance difference is basically negligible as well.
This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.
The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.
This explains the "strange results".
"Better" results can be obtained using the expressions below:
//*[text() = 'qwerty']
The above selects every element in the document that has at least one text-node child with value 'qwerty'.
//*[text() = 'qwerty' and not(text()[2])]
The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.
Why do we need Virtual Methods in C++?
In Bjarne Stroustrup C++ Programming: Principles and Practice, (14.3):
The virtual function provides the ability to define a function in a base class and have a function of the same name and type in a derived class called when a user calls the base class function. That is often called run-time polymorphism, dynamic dispatch, or run-time dispatch because the function called is determined at run time based on the type of the object used.
To handle a virtual call, one needs one or more pieces of data related to the derived object 3. The way that is usually done is to add the address of table of functions. This table is usually referred to as virtual table or virtual function table and its address is often called the virtual pointer. Each virtual function gets a slot in the virtual table. Depending of the caller's object (derived) type, the virtual function, in its turn, invokes the respective override.
1.The use of inheritance, run-time polymorphism, and encapsulation is the most common definition of object-oriented programming.
2. You can't code functionality to be any faster or to use less memory using other language features to select among alternatives at run time. Bjarne Stroustrup C++ Programming: Principles and Practice.(14.3.1).
3. Something to tell which function is really invoked when we call the base class containing the virtual function.
Javascript solution for your case:
console.log(unique(standardsList));
function unique(obj){
var uniques=[];
var stringify={};
for(var i=0;i<obj.length;i++){
var keys=Object.keys(obj[i]);
keys.sort(function(a,b) {return a-b});
var str='';
for(var j=0;j<keys.length;j++){
str+= JSON.stringify(keys[j]);
str+= JSON.stringify(obj[i][keys[j]]);
}
if(!stringify.hasOwnProperty(str)){
uniques.push(obj[i]);
stringify[str]=true;
}
}
return uniques;
}
if ($('#A').attr('myattr')) {
// attribute exists
} else {
// attribute does not exist
}
EDIT:
The above will fall into the else
-branch when myattr
exists but is an empty string or "0". If that's a problem you should explicitly test on undefined
:
if ($('#A').attr('myattr') !== undefined) {
// attribute exists
} else {
// attribute does not exist
}
You need to use something like iteritems
.
for field, possible_values in fields.iteritems():
print field, possible_values
See this answer for more information on iterating through dictionaries, such as using items()
, across python versions.
Since Python 3 iteritems()
is no longer supported. Use items()
instead.
for field, possible_values in fields.items():
print(field, possible_values)
This is very easy to implement. You can use:
window.location.href = "http://www.example.com/";
This will remember the history of the previous page. So one can go back by clicking on the browser's back button.
Or:
window.location.replace("http://www.example.com/");
This method does not remember the history of the previous page. The back button becomes disabled in this case.
Based on @balupton's answer:
$(document).on('focus', '[contenteditable]', e => {_x000D_
const self = $(e.target)_x000D_
self.data('before', self.html())_x000D_
})_x000D_
$(document).on('blur', '[contenteditable]', e => {_x000D_
const self = $(e.target)_x000D_
if (self.data('before') !== self.html()) {_x000D_
self.trigger('change')_x000D_
}_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Script to recursively count all non-blank lines with a certain file extension in the current directory:
#!/usr/bin/env bash
(
echo 0;
for ext in "$@"; do
for i in $(find . -name "*$ext"); do
sed '/^\s*$/d' $i | wc -l ## skip blank lines
#cat $i | wc -l; ## count all lines
echo +;
done
done
echo p q;
) | dc;
Sample usage:
./countlines.sh .py .java .html
Cannot say about the "official nomenclature" - infact I wonder whose word will be "official" anyway - but here's how they can be called:
I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.
Here are some differences:
You can call app.render
on root level and res.render
only inside a route/middleware.
app.render
always returns the html
in the callback function, whereas res.render
does so only when you've specified the callback function as your third parameter. If you call res.render
without the third parameter/callback function the rendered html is sent to the client with a status code of 200
.
Take a look at the following examples.
app.render
app.render('index', {title: 'res vs app render'}, function(err, html) {
console.log(html)
});
// logs the following string (from default index.jade)
<!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
res.render
without third parameter
app.get('/render', function(req, res) {
res.render('index', {title: 'res vs app render'})
})
// also renders index.jade but sends it to the client
// with status 200 and content-type text/html on GET /render
res.render
with third parameter
app.get('/render', function(req, res) {
res.render('index', {title: 'res vs app render'}, function(err, html) {
console.log(html);
res.send('done');
})
})
// logs the same as app.render and sends "done" to the client instead
// of the content of index.jade
res.render
uses app.render
internally to render template files.
You can use the render
functions to create html emails. Depending on your structure of your app, you might not always have acces to the app
object.
For example inside an external route:
app.js
var routes = require('routes');
app.get('/mail', function(req, res) {
// app object is available -> app.render
})
app.get('/sendmail', routes.sendmail);
routes.js
exports.sendmail = function(req, res) {
// can't use app.render -> therefore res.render
}
You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="imgAbt">_x000D_
<img width="220" height="220" src="img/me.jpg" />_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or, if you wish the text to closely wrap the image, change your markup to:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>
_x000D_
IMHO the best option is to use YAML's native block scalars. Specifically in this case, the folded style block.
By invoking sh -c
you can pass arguments to your container as commands, but if you want to elegantly separate them with newlines, you'd want to use the folded style block, so that YAML will know to convert newlines to whitespaces, effectively concatenating the commands.
A full working example:
apiVersion: v1
kind: Pod
metadata:
name: myapp
labels:
app: myapp
spec:
containers:
- name: busy
image: busybox:1.28
command: ["/bin/sh", "-c"]
args:
- >
command_1 &&
command_2 &&
...
command_n
Answer for Question #1 - You could simply have your if statement stop being TRUE
$project.PropertyGroup | Foreach {
if(($_.GetAttribute('Condition').Trim() -eq $propertyGroupConditionName.Trim()) -and !$FinishLoop) {
$a = $project.RemoveChild($_);
Write-Host $_.GetAttribute('Condition')"has been removed.";
$FinishLoop = $true
}
};
body
has default margins: http://www.w3.org/TR/CSS2/sample.html
body { margin:0; } /* Remove body margins */
Or you could use this useful Global reset
* { margin:0; padding:0; box-sizing:border-box; }
If you want something less *
global than:
html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, hgroup, menu, nav, section, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
vertical-align: baseline;
background: transparent;
}
some other CSS Reset:
http://yui.yahooapis.com/3.5.0/build/cssreset/cssreset-min.css
http://meyerweb.com/eric/tools/css/reset/
https://github.com/necolas/normalize.css/
http://html5doctor.com/html-5-reset-stylesheet/
…
brief mnemonics:
git reset HEAD : index = HEAD
git checkout : file_tree = index
git reset --hard HEAD : file_tree = index = HEAD
SELECT name,
type
FROM dbo.sysobjects
WHERE (type = 'P')
Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...
If one uses gcc (clang?) and have -Werror
and -Wbad-function-cast
defined,
int val = (int)pow(10,9);
will result:
error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]
(for a good reason, overflow and where values are rounded needs to be thought out)
EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).
After properly thought out (that parameters to pow() are good), int val = pow(10,9);
seems to work with gcc 9.2 x86-64 ...
but note:
printf("%d\n", pow(10,4));
may output e.g.
-1121380856
(did for me) where
int i = pow(10,4); printf("%d\n", i);
printed
10000
in one particular case I tried.
Another easy way to get this:
Person myPet = GetPersonFromDatabase();
// check for myPet == null... AND for myPet.PetType == null
if ( myPet.PetType == "cat" ) <--- fall down go boom!
Simple, Effective and Efficient way to count row in HBASE:
Whenever you insert a row trigger this API which will increment that particular cell.
Htable.incrementColumnValue(Bytes.toBytes("count"), Bytes.toBytes("details"), Bytes.toBytes("count"), 1);
To check number of rows present in that table. Just use "Get" or "scan" API for that particular Row 'count'.
By using this Method you can get the row count in less than a millisecond.
If you want to use your custom pipe in your components, you can add
@Injectable({
providedIn: 'root'
})
annotation to your custom pipe. Then, you can use it as a service
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
Try This One:
@list_of_params varchar(20) -- value 1, 2, 5, 7, 20
SELECT d.[Name]
FROM Department d
where @list_of_params like ('%'+ CONVERT(VARCHAR(10),d.Id) +'%')
very simple.
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data(this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data(this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data(this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data(this)">90 Days</a></li>
</ul>
</div>
<script>
function Data(element)
{
element.removeClass('active');
element.addClass('active') ;
}
</script>
Any file manager allow to avoid such issues, e.g Far Manager
I also have faced the same issue. Initially tried modifying System PATH which does not worked out. Later resolved by installing Micro Visual Studio express.
@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded()
. It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.
1: a pair of brackets is missing.
case TelephonyManager.CALL_STATE_IDLE:
// Went to idle- this is the end of a call. What type depends on previous state(s)
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
// Ring but no pickup- a miss
onMissedCall(context, savedNumber, callStartTime);
} else {
// this one is missing
if(isIncoming){
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());
}
}
// this one is missing
break;
2: lastState
is not updated by the state
if it is at the end of the function. It should be replaced to the first line of this function by
public void onCallStateChanged(Context context, int state, String number) {
int lastStateTemp = lastState;
lastState = state;
// todo replace all the "lastState" by lastStateTemp from here.
if (lastStateTemp == state) {
//No change, debounce extras
return;
}
//....
}
Additional I've put lastState
and savedNumber
into shared preference as you suggested.
Just tested it with above changes. Bug fixed at least on my phones.
There is no difference, except that Pragma
is only defined as applicable to the requests by the client, whereas Cache-Control
may be used by both the requests of the clients and the replies of the servers.
So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:
HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.
Note: because the meaning of "Pragma: no-cache as a response header field is not actually specified, it does not provide a reliable replacement for "Cache-Control: no-cache" in a response
The way I would read the above:
if you're writing a client and need no-cache
:
Pragma: no-cache
in your requests, since you may not know if Cache-Control
is supported by the server;Cache-Control
if you're writing a server:
Cache-Control
; if not found, check for Pragma: no-cache
, and execute the Cache-Control: no-cache
logic;Cache-Control
.Of course, reality might be different from what's written or implied in the RFC!
"dev" is not a string
it is a const char *
like var1
. Thus you are indeed comparing the memory adresses. Being that var1
is a char pointer, *var1
is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.
Being that this is tagged as c++, it would be sensible to use std::string
instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1
instead of const char *var1
.
You can use the .tostring() method with datetime format specifiers to format to whatever you need:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
Until PHP 5.3, const
could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum.
define
can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.
An example of good const
usage is to get rid of magic numbers. Take a look at PDO's constants. When you need to specify a fetch type, you would type PDO::FETCH_ASSOC
, for example. If consts were not used, you'd end up typing something like 35
(or whatever FETCH_ASSOC
is defined as). This makes no sense to the reader.
An example of good define
usage is maybe specifying your application's root path or a library's version number.
Above many of the answers are good but none of the worked for me fully. So i combined the answer from @nmr and got this one.
final Dialog d = new Dialog(getActivity());
// d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.dialog_box_shipment_detail);
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
Display display = wm.getDefaultDisplay(); // getting the screen size of device
Point size = new Point();
display.getSize(size);
int width = size.x - 20; // Set your heights
int height = size.y - 80; // set your widths
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = width;
lp.height = height;
d.getWindow().setAttributes(lp);
d.show();
Use
=SUBSTITUTE(A1,",",CHAR(10) & CHAR(13))
This will replace each comma with a new line. Change A1
to the cell you are referencing.
If you are working with Ubuntu, sometimes you need to run as sudo
:
For Python2:
sudo python gameover.py
For Python3:
sudo python3 gameover.py
There's a very simple way to do on/off
flags without parsing the arguments. gulpfile.js
is just a file that's executed like any other, so you can do:
var flags = {
production: false
};
gulp.task('production', function () {
flags.production = true;
});
And use something like gulp-if
to conditionally execute a step
gulp.task('build', function () {
gulp.src('*.html')
.pipe(gulp_if(flags.production, minify_html()))
.pipe(gulp.dest('build/'));
});
Executing gulp build
will produce a nice html, while gulp production build
will minify it.
Spring 3.1 and Guava 1.13.1:
@EnableCaching
@Configuration
public class CacheConfiguration implements CachingConfigurer {
@Override
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {
@Override
protected Cache createConcurrentMapCache(final String name) {
return new ConcurrentMapCache(name,
CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
}
};
return cacheManager;
}
@Override
public KeyGenerator keyGenerator() {
return new DefaultKeyGenerator();
}
}
For rows you can simply use wc -l file
-l
stands for total line
for columns uou can simply use head -1 file | tr ";" "\n" | wc -l
Explanation
head -1 file
Grabbing the first line of your file, which should be the headers,
and sending to it to the next cmd through the pipe
| tr ";" "\n"
tr
stands for translate.
It will translate all ;
characters into a newline character.
In this example ;
is your delimiter.
Then it sends data to next command.
wc -l
Counts the total number of lines.
Had this issue. My main app and extension belonged to the same app group id correctly, but there was also one more app ID not in my project that shared said app group id. I had to remove this last app ID's association with the app group.
I struggled with this from behind a proxy so I thought I should post what I did. Below one is worked for me.
-> "export HTTPS_PROXY=(yourproxy)"
There are a few important rules to install Tensorflow:
You have to install Python x64. It doesn't work on 32b and it gives the same error as yours.
It doesn't support Python versions later than 3.8 and Python 3.8 requires TensorFlow 2.2 or later.
For example, you can install Python3.8.6-64bit and it works like a charm.
assylias and Head of Catering have already given your the reason why the error is occurring.
Now regarding what you are doing, from what I understand, you don't need to use Select
at all
I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as
Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String
filepath = CStr(FileDialog)
'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")
lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)
lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)
I was using an old version of nodemailer 0.4.1 and had this issue. I updated to 0.5.15 and everything is working fine now.
Edited package.json to reflect changes then
npm install
You can use ButtonTheme()
also
Here is a example code -
ButtonTheme(
minWidth: 200.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.green)),
child: RaisedButton(
elevation: 5.0,
hoverColor: Colors.green,
color: Colors.amber,
child: Text(
"Place Order",
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
onPressed: () {},
),
),
You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.
See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955
Go to Instance -> sessions and watch the SQL Tab of each session.
There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage
And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.
Making Hadley's comment to an answer (hope to make it better visible). Use of apply family without printing is possible with use of the plyr
package
x <- 1:2
lapply(x, function(x) x + 1)
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 3
plyr::l_ply(x, function(x) x + 1)
Created on 2020-05-19 by the reprex package (v0.3.0)
When your certificate expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. There is no ‘Renew’ button that allows you to renew your certificate. You can revoke a certificate and generate a new one before it expires. Or you can wait for it to expire and disappear, then generate a new certificate. In Apple's App Distribution Guide:
Replacing Expired Certificates
When your development or distribution certificate expires, remove it and request a new certificate in Xcode.
When your certificate expires or is revoked, any provisioning profile that made use of the expired/revoked certificate will be reflected as ‘Invalid’. You cannot build and sign any app using these invalid provisioning profiles. As you can imagine, I'd rather revoke and regenerate a certificate before it expires.
Q: If I do that then will all my live apps be taken down?
Apps that are already on the App Store continue to function fine. Again, in Apple's App Distribution Guide:
Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the store nor does it affect your ability to update them.
So…
Q: How to I properly renew it?
As mentioned above, there is no renewing of certificates. Follow the steps below to revoke and regenerate a new certificate, along with the affected provisioning profiles. The instructions have been updated for Xcode 8.3 and Xcode 9.
Login to Member Center > Certificates, Identifiers & Profiles, select the expiring certificate. Take note of the expiry date of the certificate, and click the ‘Revoke’ button.
Optionally, if you don't want to have the revoked certificate lying around in your system, you can delete them from your system. Unfortunately, the ‘Delete Certificate’ function in Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates… seems to be always disabled, so we have to delete them manually using Keychain Access.app (/Applications/Utilities/Keychain Access.app).
Filter by ‘login’ Keychains and ‘Certificates’ Category. Locate the certificate that you've just revoked in Step 1.
Depending on the certificate that you've just revoked, search for either ‘Mac’ or ‘iPhone’. Mac App Store distribution certificates begin with “3rd Party Mac Developer”, and iOS App Store distribution certificates begin with “iPhone Distribution”.
You can locate the revoked certificate based on the team name, the type of certificate (Mac or iOS) and the expiry date of the certificate you've noted down in Step 1.
Under Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates…, click on the ‘+’ button on the lower left, and select the same type of certificate that you've just revoked to let Xcode request a new one for you.
After which, head back to Member Center > Certificates, Identifiers & Profiles > Provisioning Profiles > All. You'll notice that any provisioning profile that made use of the revoked certificate is now reflected as ‘Invalid’.
Click on any profile that are now ‘Invalid’, click ‘Edit’, then choose the newly created certificate, then click on ‘Generate’. Repeat this until all provisioning profiles are regenerated with the new certificate.
Tip: Before you download the new profiles using Xcode, you may want to clear any existing and possibly invalid provisioning profiles from your Mac. You can do so by removing all the profiles from ~/Library/MobileDevice/Provisioning Profiles
Back in Xcode > Preferences > Accounts > [Apple ID], click on the ‘Download All Profiles’ button to ask Xcode to download all the provisioning profiles from your developer account.
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
You need to download the font and reference it locally.
Download the CSS
from the link you posted, then download all of the WOFF
files and (if needed) convert them to TTF
.
Then change the CSS
from the link you posted to include the fonts locally.
From
url(http://themes.googleusercontent.com/static/fonts/opensans/v6/
DXI1ORHCpsQm3Vp6mXoaTXhCUOGz7vYGh680lGh-uXM.woff)
To
url(/path/to/font/font.woff)
Voila! There might be some more you need to do but the above is the basics. This article explains a little better.
There is a gem called active_record_union that might be what you are looking for.
It's example usages is the following:
current_user.posts.union(Post.published)
current_user.posts.union(Post.published).where(id: [6, 7])
current_user.posts.union("published_at < ?", Time.now)
user_1.posts.union(user_2.posts).union(Post.published)
user_1.posts.union_all(user_2.posts)
The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:
When you iterate over it with for i in ar:
the values of i will be 2, 4 and 6. So, when you try to access ar[i]
for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.
If you intend to use indexes anyhow, try using for index, value in enumerate(ar):
, then theSum = theSum + ar[index]
should work just fine.
Using Angular
In my case using ng-href
instead of href
solved it for me.
Note :
I am working with laravel as back-end
There is no difference in the location of the asterisk (at in C, which Obj-C is based on, it doesn't matter). It is purely preference (style).
A final
variable means that it can be instantiated only one time.
in Java you can't use non-final variables in lambda as well as in anonymous inner classes.
You can refactor your code with the old for-each loop:
private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
try {
for(Component component : cal.getComponents().getComponents("VTIMEZONE")) {
VTimeZone v = (VTimeZone) component;
v.getTimeZoneId();
if(calTz==null) {
calTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
}
}
} catch (Exception e) {
log.warn("Unable to determine ical timezone", e);
}
return null;
}
Even if I don't get the sense of some pieces of this code:
v.getTimeZoneId();
without using its return valuecalTz = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
you don't modify the originally passed calTz
and you don't use it in this methodnull
, why don't you set void
as return type?Hope also these tips helps you to improve.
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
It's very simple using System.Security.Cryptography.MD5:
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return md5.ComputeHash(stream);
}
}
(I believe that actually the MD5 implementation used doesn't need to be disposed, but I'd probably still do so anyway.)
How you compare the results afterwards is up to you; you can convert the byte array to base64 for example, or compare the bytes directly. (Just be aware that arrays don't override Equals
. Using base64 is simpler to get right, but slightly less efficient if you're really only interested in comparing the hashes.)
If you need to represent the hash as a string, you could convert it to hex using BitConverter
:
static string CalculateMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
I got it
Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"
Basically, I need to set the cell format, instead of setting the date.
Cool tricks here, I've got a nit pick with a lot of the safe traditional answers not caching the length of the array.
function arraySum(array){
var total = 0,
len = array.length;
for (var i = 0; i < len; i++){
total += array[i];
}
return total;
};
var my_array = [1,2,3,4];
// Returns 10
console.log( arraySum( my_array ) );
Without caching the length of the array the JS compiler needs to go through the array with every iteration of the loop to calculate the length, it's unnecessary overhead in most cases. V8 and a lot of modern browsers optimize this for us, so it is less of a concern then it was, but there are older devices that benefit from this simple caching.
If the length is subject to change, caching's that could cause some unexpected side effects if you're unaware of why you're caching the length, but for a reusable function who's only purpose is to take an array and add the values together it's a great fit.
Here's a CodePen link for this arraySum function. http://codepen.io/brandonbrule/pen/ZGEJyV
It's possible this is an outdated mindset that's stuck with me, but I don't see a disadvantage to using it in this context.
Elegant easy solution using jQuery.
<script>
function call() {
var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() {
});
}
</script>
and in your html :
<div onclick="call()"><img src="../img/[email protected]"></div>
For the benefit of anyone searching for similar, see worksheet .UsedRange
,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next
None of the answers here worked for me in Chrome. AAverin on GitHub has created some useful Javascript for this purpose and this worked for me:
Just add the js to your code and add the class 'splitForPrint' to your table and it will neatly split the table into multiple pages and add the table header to each page.
.live() is used if elements are being added after the initial page load. Say you have a button which gets added by an AJAX call after the page gets loaded. This new button will not be accessible using .click(), so you'll have to use .live('click')
If you have a class that you use in an activity and you want to have access the ressource in that class, I recommend you to define a context as a private variable in class and initial it in constructor:
public class MyClass (){
private Context context;
public MyClass(Context context){
this.context=context;
}
public testResource(){
String s=context.getString(R.string.testString).toString();
}
}
Making an instant of class in your activity:
MyClass m=new MyClass(this);
Some disadvantage of "INTERVAL '1' DAY" is that bind variables cannot be used for the number of days added. Instead, numtodsinterval can be used, like in this small example:
select trunc(sysdate) + numtodsinterval(:x, 'day') tag
from dual
See also: NUMTODSINTERVAL in Oracle Database Online Documentation
I think your problem is inside CheckCircular, in the while condition:
Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException
I had to do something very similar to find out why my iPhone was bleeding cellular network data, eating 80% of my 500Mb allowance in a couple of days.
Unfortunately I had to packet sniff whilst on 3G/4G and couldn't rely on being on wireless. So if you need an "industrial" solution then this is how you sniff all traffic (not just http) on any network.
Basic recipe:
Detailed'ish instructions:
Note that the above implementation is not security focussed it's simply about getting a detailed packet capture of all of your iPhone's traffic on 3G/4G/Wireless networks
Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip
to text
.
Create proper gradient:
background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);
Then clip the backgroud with text:
background-clip: text;
color: transparent;
https://jsfiddle.net/simonmysun/2h61Ljbn/4/
Tested under Chrome 75 under Windows 10.
There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file
in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave
gem .
I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.
Wrap it in double quotes
alter user "dell-sys" with password 'Pass@133';
Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys"
then you will have to issue exact the same whenever you refer to that user.
I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.
I had this problem when I reopened a project (which was developed on XCode 3.something on Leopard) after upgrading to Snow Leopard and XCode 3.2. Curious enough, it only affected some kinds of builds (emulator builds went fine, device ones gave me the error). And I have libxml2 at /usr/include, and it indeed contains libxml/tree.h.
Even the magic "Clean" did not work, but "Empty Caches..." under the "XCode" menu (between the Apple logo and File) did the trick (was that menu there in previous versions?). Beats me the reason, but after a clean there were no more complaints regarding libxml/tree.h
Case sensitive Tables (table names created with double-quotes) can throw this same error as well. See this answer for more information.
Simply wrap the table in double quotes:
INSERT INTO "customer" (c_id,name,surname) VALUES ('1','Micheal','Jackson')
I tried all the above codes and none of them fixed my issues. Here is what worked for me. I used input-group-addon.
<div class = "input-group">
<span class = "input-group-addon">Go</span>
<input type = "text" class = "form-control" placeholder="you are the man!">
</div>
Kindly try this code when str is less than 5.
string strModified = str.Substring(0,str.Length>5?5:str.Length);
What I found the best and short solution is
array_shift(explode(".",$_SERVER['HTTP_HOST']));
PHP 7 ready version. It uses openssl_encrypt function from PHP OpenSSL Library.
class Openssl_EncryptDecrypt {
function encrypt ($pure_string, $encryption_key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$hash_algo = 'sha256';
$sha2len = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv);
$hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
return $iv.$hmac.$ciphertext_raw;
}
function decrypt ($encrypted_string, $encryption_key) {
$cipher = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$hash_algo = 'sha256';
$sha2len = 32;
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($encrypted_string, 0, $ivlen);
$hmac = substr($encrypted_string, $ivlen, $sha2len);
$ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv);
$calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
if(function_exists('hash_equals')) {
if (hash_equals($hmac, $calcmac)) return $original_plaintext;
} else {
if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext;
}
}
/**
* (Optional)
* hash_equals() function polyfilling.
* PHP 5.6+ timing attack safe comparison
*/
function hash_equals_custom($knownString, $userString) {
if (function_exists('mb_strlen')) {
$kLen = mb_strlen($knownString, '8bit');
$uLen = mb_strlen($userString, '8bit');
} else {
$kLen = strlen($knownString);
$uLen = strlen($userString);
}
if ($kLen !== $uLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $kLen; $i++) {
$result |= (ord($knownString[$i]) ^ ord($userString[$i]));
}
return 0 === $result;
}
}
define('ENCRYPTION_KEY', '__^%&Q@$&*!@#$%^&*^__');
$string = "This is the original string!";
$OpensslEncryption = new Openssl_EncryptDecrypt;
$encrypted = $OpensslEncryption->encrypt($string, ENCRYPTION_KEY);
$decrypted = $OpensslEncryption->decrypt($encrypted, ENCRYPTION_KEY);
Tried this on firefox, works http://jsfiddle.net/Tm26Q/1/
$(function(){
/** Just to mimic a blinking box on the page**/
setInterval(function(){$("div#box").hide();},2001);
setInterval(function(){$("div#box").show();},1000);
/**/
});
$("div#box").on("DOMAttrModified",
function(){if($(this).is(":visible"))console.log("visible");});
UPDATE
Currently the Mutation Events (like
DOMAttrModified
used in the solution) are replaced by MutationObserver, You can use that to detect DOM node changes like in the above case.
Here's is a way of doing it without any Javascript and it's also compatible with any browser.
EDIT: In Safari, the input
gets disabled when hidden with display: none
. A better approach would be to use position: fixed; top: -100em
.
<label>
Open file dialog
<input type="file" style="position: fixed; top: -100em">
</label>
Also, if you prefer you can go the "correct way" by using for
in the label
pointing to the id
of the input like this:
<label for="inputId">file dialog</label>
<input id="inputId" type="file" style="position: fixed; top: -100em">
My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:
CREATE EVENT applog_clean_event
ON SCHEDULE
EVERY 1 DAY
STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO
It was discussed before here.
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
You can use this way either :
Add this line to your recyclerView xml view :
android:nestedScrollingEnabled="false"
try it ,recyclerview will be smoothly scrolled with flexible height
hope this helped .
You can of course use a loop, or you can insert them in a single statement, e.g.
Insert into db
(names,email,password)
Values
('abc','def','mypassword')
,('ghi','jkl','mypassword2')
,('mno','pqr','mypassword3')
It really depends where you're getting your data from.
If you use a loop, wrapping it in a transaction will make it a bit faster.
UPDATE
What if i want to insert unique names?
If you want to insert unique names, then you need to generate data with unique names. One way to do this is to use Visual Studio to generate test data.
You can just try this :
str.replace(/[.#]/g, 'replacechar');
this will replace .,- and # with your replacechar !
You are getting this problem because the activity you are trying to apply the android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
to is extending ActionBarActivity which requires the AppCompat theme to be applied.
Extend your activity from Activity
rather than from ActionBarActivity
You might have to change your Java class accordingly little bit.
If you want to remove status bar too then use this before setContentView(layout)
in onCreateView
method
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Layout Weight works like a ratio. For example, if there is a vertical layout and there are two items(such as buttons or textviews), one having layout weight 2 and the other having layout weight 3 respectively. Then the 1st item will occupy 2 out of 5 portion of the screen/layout and the other one 3 out of 5 portion. Here 5 is the weight sum. i.e. Weight sum divides the whole layout into defined portions. And Layout Weight defines how much portion does the particular item occupies out of the total Weight Sum pre-defined. Weight sum can be manually declared as well. Buttons, textviews, edittexts etc all are organized using weightsum and layout weight when using linear layouts for UI design.
This is the deep cloning method I use, I think it Great, hope you make suggestions
function deepClone (obj) {
var _out = new obj.constructor;
var getType = function (n) {
return Object.prototype.toString.call(n).slice(8, -1);
}
for (var _key in obj) {
if (obj.hasOwnProperty(_key)) {
_out[_key] = getType(obj[_key]) === 'Object' || getType(obj[_key]) === 'Array' ? deepClone(obj[_key]) : obj[_key];
}
}
return _out;
}
Try:
#include <typeinfo>
// …
std::cout << typeid(a).name() << '\n';
You might have to activate RTTI in your compiler options for this to work. Additionally, the output of this depends on the compiler. It might be a raw type name or a name mangling symbol or anything in between.
#kinda like the one above but better :P
from __future__ import print_function
from time import sleep
for i in range(101):
str1="Downloading File FooFile.txt [{}%]".format(i)
back="\b"*len(str1)
print(str1, end="")
sleep(0.1)
print(back, end="")
Swift 2
Using Trailing Closures this becomes:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
Trailing Closures is Swift syntactic sugar that enables defining the closure outside of the function parameter scope. For more information see Trailing Closures in Swift 2.2 Programming Language Guide.
In dispatch_async case the API is func dispatch_async(queue: dispatch_queue_t, _ block: dispatch_block_t)
since dispatch_block_t
is type alias for () -> Void
- A closure that receives 0 parameters and does not have a return value, and block being the last parameter of the function we can define the closure in the outer scope of dispatch_async
.
In another scenario just I would like to add is In my scenario, the name space was different for controller as it was mistake of copying controller from another project.
Create an ouput
<div id="output"></div>
Write to it using JavaScript
var output = document.getElementById("output");
output.innerHTML = "hello world";
If you would like it to handle more complex output values, you can use JSON.stringify
var myObj = {foo: "bar"};
output.innerHTML = JSON.stringify(myObj);
The following method should work via Command Prompt (cmd):
start microsoft-edge:http://www.cnn.com
You also need to install Docker Compose. See the manual. Here are the commands you need to execute
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo mv /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose
Yes.
Create a file called template.php
in your views
folder.
The contents of template.php
:
$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');
Then from your controller you can do something like:
$d['v'] = 'body';
$this->load->view('template', $d);
This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:
Consider if you create a view called init.php
that contains the single line:
$this->load->view('html');
Now create the view html.php
with contents:
<!DOCTYPE html>
<html lang="en">
<? $this->load->view('head'); ?>
<? $this->load->view('body'); ?>
</html>
Now create a view head.php
with contents:
<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>
And a body.php
view with contents:
<body>
<div id="mainWrap">
<? $this->load->view('header'); ?>
<? //FINALLY LOAD THE VIEW!!! ?>
<? $this->load->view($v); ?>
<? $this->load->view('footer'); ?>
</div>
</body>
And create header.php
and footer.php
views as appropriate.
Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html>
and <body>
tags, your headers and footers will be loaded in.
$d['v'] = 'fooview'
$this->load->view('init', $d);
var arrayDiv = new Array();
for(var i=0; i <= 1; i++){
arrayDiv[i] = document.createElement('div');
arrayDiv[i].id = 'block' + i;
arrayDiv[i].className = 'block' + i;
}
document.body.appendChild(arrayDiv[0].appendChild(arrayDiv[1]));
abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc. what if I want neither def nor xyz will it be abc(?!(def)(xyz)) ???
I had the same question and found a solution:
abc(?:(?!def))(?:(?!xyz))
These non-counting groups are combined by "AND", so it this should do the trick. Hope it helps.
This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the =
to match the data on the other side according to a set of predefined rules.
When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int).
In this case you have
double var = integer result
which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error).
If you'd like to keep the result as a double you're going to want to create a situation where you have
double var = double result
The easiest way to do that is to force the expression on the right side of an equation to cast to double:
c = a/(double)b
Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss).
After the upcast, a
will wind up as a double and now you have division between two doubles. This will create the desired division and assignment.
AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically.
I assume that you're trying to edit a column that you have already added data on, so dropping column and adding again as a nullable column is not possible without losing data. We'll alter
the existing column.
However, Laravel's schema builder does not support modifying columns other than renaming the column. So you will need to run raw queries to do them, like this:
function up()
{
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}
And to make sure you can still rollback your migration, we'll do the down()
as well.
function down()
{
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
One note is that since you are converting between nullable and not nullable, you'll need to make sure you clean up data before/after your migration. So do that in your migration script both ways:
function up()
{
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
DB::statement('UPDATE `throttle` SET `user_id` = NULL WHERE `user_id` = 0;');
}
function down()
{
DB::statement('UPDATE `throttle` SET `user_id` = 0 WHERE `user_id` IS NULL;');
DB::statement('ALTER TABLE `throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
I created the Path Length Checker tool for this purpose, which is a nice, free GUI app that you can use to see the path lengths of all files and directories in a given directory.
I've also written and blogged about a simple PowerShell script for getting file and directory lengths. It will output the length and path to a file, and optionally write it to the console as well. It doesn't limit to displaying files that are only over a certain length (an easy modification to make), but displays them descending by length, so it's still super easy to see which paths are over your threshold. Here it is:
$pathToScan = "C:\Some Folder" # The path to scan and the the lengths for (sub-directories will be scanned as well).
$outputFilePath = "C:\temp\PathLengths.txt" # This must be a file in a directory that exists and does not require admin rights to write to.
$writeToConsoleAsWell = $true # Writing to the console will be much slower.
# Open a new file stream (nice and fast) and write all the paths and their lengths to it.
$outputFileDirectory = Split-Path $outputFilePath -Parent
if (!(Test-Path $outputFileDirectory)) { New-Item $outputFileDirectory -ItemType Directory }
$stream = New-Object System.IO.StreamWriter($outputFilePath, $false)
Get-ChildItem -Path $pathToScan -Recurse -Force | Select-Object -Property FullName, @{Name="FullNameLength";Expression={($_.FullName.Length)}} | Sort-Object -Property FullNameLength -Descending | ForEach-Object {
$filePath = $_.FullName
$length = $_.FullNameLength
$string = "$length : $filePath"
# Write to the Console.
if ($writeToConsoleAsWell) { Write-Host $string }
#Write to the file.
$stream.WriteLine($string)
}
$stream.Close()
<?php
// create a "numeric" array
$animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');
//Normarl display
print_r($animals);
echo "<br/><br/>";
//If splice the array
//array_splice($animals, 2, 2);
unset($animals[3]); // you can unset the particular value
print_r($animals);
?>
The general idea is to sweep the function across. You have many options, one is apply()
:
R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R>
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.
<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />
Some frameworks (e.g. rails) put these in by default.
However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.
All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)
The current alternative for pluck()
is value()
.
I was getting the same error on Cygwin; I did the following (one of them fixed it):
TABS
to SPACES
dos2unix
on the .(ba)sh
file As mentioned in the comments height:100% relies on the height of the parent container being explicitly defined. One way to achieve what you want is to use absolute/relative positioning, and specifying the left/right/top/bottom properties to "stretch" the content out to fill the available space. I have implemented what I gather you want to achieve in jsfiddle. Try resizing the Result window and you will see the content resizes automatically.
The limitation of this approach in your case is that you have to specify an explicit margin-top on the parent container to offset its contents down to make room for the header content. You can make it dynamic if you throw in javascript though.
$("form input:[name=gender]").filter('[value=Male]').attr('checked', true);
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password@sid @tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
in batch file abc.bat
cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3
I am assuming that your executible.exe
is present in c:\user\ben_dchost\documents\
I am also assuming that the parameters it takes are -flag1
-flag2
-flag3
Edited:
For the command you say you want to execute, do:
cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause
Hope this helps
File -> Settings -> Keymap Change keymaps settings to your previous IDE to which you are familiar with
Old question, but thought I'd share my solution anyway. Pretty simple.
dicta_set = set(dicta.items()) # creates a set of tuples (k/v pairs)
dictb_set = set(dictb.items())
setdiff = dictb_set.difference(dicta_set) # any set method you want for comparisons
for k, v in setdiff: # unpack the tuples for processing
print(f"k/v differences = {k}: {v}")
This code creates two sets of tuples representing the k/v pairs. It then uses a set method of your choosing to compare the tuples. Lastly, it unpacks the tuples (k/v pairs) for processing.
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
find
's optionsThere is actually no exec of /bin/ls
needed;
Find has an option that does just that:
find . -maxdepth 2 -type d -ls
To see only the one level of subdirectories you are interested in, add -mindepth
to the same level as -maxdepth
:
find . -mindepth 2 -maxdepth 2 -type d -ls
When the details that get shown should be different, -printf
can show any detail about a file in custom format;
To show the symbolic permissions and the owner name of the file, use -printf
with %M
and %u
in the format
.
I noticed later you want the full ownership information, which includes
the group. Use %g
in the format for the symbolic name, or %G
for the group id (like also %U
for numeric user id)
find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
This should give you just the details you need, for just the right files.
I will give an example that shows actually different values for user and group:
$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data www-data /tmp/user/33
drwx------ octopussy root /tmp/user/126
drwx------ root root /tmp/user/0
drwx------ siegel root /tmp/user/1000
drwxrwxrwt root root /tmp/systemd-[...].service-HRUQmm/tmp
(Edited for readability: indented, shortened last line)
Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:
Not only do we save creating a new process for each name - a huge task -
the information does not even need to be read, as find
already knows it.
A Pending Intent specifies an action to take in the future. It lets you pass a future Intent to another application and allow that application to execute that Intent as if it had the same permissions as your application, whether or not your application is still around when the Intent is eventually invoked.
It is a token that you give to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code.
If you give the foreign application an Intent, and that application sends/broadcasts the Intent you gave, they will execute the Intent with their own permissions. But if you instead give the foreign application a Pending Intent you created using your own permission, that application will execute the contained Intent using your application’s permission.
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
It is an Intent action that you want to perform, but at a later time. Think of it a putting an Intent on ice. The reason it’s needed is because an Intent must be created and launched from a valid Context in your application, but there are certain cases where one is not available at the time you want to run the action because you are technically outside the application’s context (the two common examples are launching an Activity from a Notification or a BroadcastReceiver.
By creating a PendingIntent you want to use to launch, say, an Activity while you have the Context to do so (from inside another Activity or Service) you can pass that object around to something external in order for it to launch part of your application on your behalf.
A PendingIntent provides a means for applications to work, even after their process exits. Its important to note that even after the application that created the PendingIntent has been killed, that Intent can still run. A description of an Intent and target action to perform with it. Instances of this class are created with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), getService (Context, int, Intent, int); the returned object can be handed to other applications so that they can perform the action you described on your behalf at a later time.
By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: often, for example, the base Intent you supply will have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else.
A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application’s process is killed, the PendingIntent itself will remain usable from other processes that have been given it. If the creating application later re-retrieves the same kind of PendingIntent (same operation, same Intent action, data, categories, and components, and same flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK
Private Sub CommandButton1_Click()
Dim Data As Object, Employee As Object
Application.ScreenUpdating = False
Set Data = ThisWorkbook.Sheets("Data")
Set Employee = ThisWorkbook.Sheets("Employee Names")
Data.Range("AK1").Value = "Lookup"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"
Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"
Application.DisplayAlerts = False
Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
Data.Range("AK:AK").Delete
Data.AutoFilterMode = False
'Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"
Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")
Dr.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
'DrfeeRequested.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")
Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")
Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"
Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")
Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Selection.AutoFilter
TodayDT = Format(Now())
Weekdy = Weekday(Now())
If Weekdy = 2 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 3 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 4 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 5 Then
LastTwoDays = Now() - Weekday(Now(), 3)
ElseIf Weekdy = 6 Then
LastTwoDays = Now() - Weekday(Now(), 3)
Else
MsgBox "Today Satuarday OR Sunday Data is not Available"
End If
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"
Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")
Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.AutoFilterMode = False
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"
'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"
Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"
Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")
Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Data.Range("A1").AutoFilter
End Sub
Private Sub CommandButton2_Click()
Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear
MsgBox "Please paste new data in data sheet"
End Sub
Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.
There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:
config.properties:
timeout.default=30
timeout.myBean=60
context.xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>config.properties</value>
</property>
</bean>
<bean id="myBean" class="Test">
<property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>
To use the default while still being able to easily override later, do this in config.properties:
timeout.myBean = ${timeout.default}
==
has higher precedence than &
. You might want to wrap your operations in ()
to specify how you want your operands to bind to the operators.
((a[0] & 1) == 0)
Similarly for all parts of the if
condition.
You can't.
As a workaround you can use a // @ts-nocheck
comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/
So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)
You can try VbsEdit. Get the latest version from Adersoft's VbsEdit http://www.vbsedit.com its a small download but it is a powerful tool to create and edit vbs files and convert them into executables without unpacking to temporary folder. (unless you get an old version like version 4.x.x.x) I've been using this program since 2008, and it's free to evaluate forever but comes with a reminder to activate and each time you Start your script from the vbsedit window you will have to wait a few seconds, Or you could purchase it for $60 to remove those minor annoyances.
Unlike ScriptCryptor, the converted exe won't have any limitations if you are still evaluating, it will run without any unwanted additional windows.
for example!
const TextBold = (props) => <Text style={{fontWeight: 'bold'}}>Text bold</Text>
<Text>
123<TextBold/>
</Text>
In Smalltalk:
'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]
I know noone cares about Smalltalk, but it's so beautiful to me.
Set the original background-color in you CSS file:
.forum{
background-color:#f0f;
}?
You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.
$(function() {
$(".forum").hover(
function() {
$(this).css('background-color', '#ff0')
}, function() {
$(this).css('background-color', '')
});
});?
==
checks for reference equality, however when writing code like:
Integer a = 1;
Integer b = 1;
Java is smart enough to reuse the same immutable for a
and b
, so this is true: a == b
. Curious, I wrote a small example to show where java stops optimizing in this way:
public class BoxingLol {
public static void main(String[] args) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
Integer a = i;
Integer b = i;
if (a != b) {
System.out.println("Done: " + i);
System.exit(0);
}
}
System.out.println("Done, all values equal");
}
}
When I compile and run this (on my machine), I get:
Done: 128
They're already ints. Why not just use subtraction?
compare = a - b;
Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.
This one is even simpler and execs no external commands.
$ PROC_NAME="JBoss"
$ PROC_STATUS="UP"
$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"
JBoss............... [UP]
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
Watch that your file name doesn't have :
in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt
and then scp no-colons.txt server:
then don't forget to mv
back on the server. Just in case this was an issue.
these functions will solve the problem, you need to implement the DrawThumbnails
function and have a global variable to store the images. I love to get this to work with a class object that has the ThumbnailImageArray
as a member variable, but am struggling!
called as in addThumbnailImages(10);
var ThumbnailImageArray = [];
function addThumbnailImages(MaxNumberOfImages)
{
var imgs = [];
for (var i=1; i<MaxNumberOfImages; i++)
{
imgs.push(i+".jpeg");
}
preloadimages(imgs).done(function (images){
var c=0;
for(var i=0; i<images.length; i++)
{
if(images[i].width >0)
{
if(c != i)
images[c] = images[i];
c++;
}
}
images.length = c;
DrawThumbnails();
});
}
function preloadimages(arr)
{
var loadedimages=0
var postaction=function(){}
var arr=(typeof arr!="object")? [arr] : arr
function imageloadpost()
{
loadedimages++;
if (loadedimages==arr.length)
{
postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter
}
};
for (var i=0; i<arr.length; i++)
{
ThumbnailImageArray[i]=new Image();
ThumbnailImageArray[i].src=arr[i];
ThumbnailImageArray[i].onload=function(){ imageloadpost();};
ThumbnailImageArray[i].onerror=function(){ imageloadpost();};
}
//return blank object with done() method
//remember user defined callback functions to be called when images load
return { done:function(f){ postaction=f || postaction } };
}
According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.
What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:
var m map[keyType]valueType
keys := sliceOfKeys(m) // you'll have to implement this
for _, k := range keys {
v := m[k]
// k is the key and v is the value; do your computation here
}
None of the solutions above worked for me. What did was removing the main.iml file manually and it suddenly worked.
Updated 2017-12-16
I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.
Synchronous
<script src...>
will block downloading of the resources below it until it is downloaded and executed
This is no longer true. Have a look at the waterfall generated by Chrome 63:
<head>
<script src="//alias-0.redacted.com/payload.php?type=js&delay=333&rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&delay=333&rand=3"></script>
</head>
<link rel=stylesheet>
will not block download and execution of scripts below it
This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:
<link href="//alias-0.redacted.com/payload.php?type=css&delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&block=1000"></script>
Keeping the above in mind, the results in OP can be explained as follows:
CSS First:
CSS Download 500ms:<------------------------------------------------>
JS Download 400ms:<-------------------------------------->
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1500ms: ?
JS First:
JS Download 400ms:<-------------------------------------->
CSS Download 500ms:<------------------------------------------------>
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1400ms: ?
Basically I was trying to get my code to have a middle section on a 'row' to auto-adjust to the content on both sides (in my case, a dotted line separator). Like @Michael_B suggested, the key is using display:flex
on the row container and at least making sure your middle container on the row has a flex-grow
value of at least 1 higher than the outer containers (if outer containers don't have any flex-grow
properties applied, middle container only needs 1 for flex-grow
).
Here's a pic of what I was trying to do and sample code for how I solved it.
.row {
background: lightgray;
height: 30px;
width: 100%;
display: flex;
align-items:flex-end;
margin-top:5px;
}
.left {
background:lightblue;
}
.separator{
flex-grow:1;
border-bottom:dotted 2px black;
}
.right {
background:coral;
}
_x000D_
<div class="row">
<div class="left">Left</div>
<div class="separator"></div>
<div class="right">Right With Text</div>
</div>
<div class="row">
<div class="left">Left With More Text</div>
<div class="separator"></div>
<div class="right">Right</div>
</div>
<div class="row">
<div class="left">Left With Text</div>
<div class="separator"></div>
<div class="right">Right With More Text</div>
</div>
_x000D_
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
Try wrapping your dates in single quotes, like this:
'15-6-2005'
It should be able to parse the date this way.
This is work perfect for me if you don't allow sorting the first column then use
<script>
$(document).ready(function () {
$('#example2').DataTable({
'order':[],
'columnDefs': [{
"targets": 0,
"orderable": false
}]
});
});
</script>
here index row starts with 0, so put 0 in targets.
And if you disable sorting for one or more column then use,
<script>
$(document).ready(function () {
$('#example2').DataTable({
'order':[],
'columnDefs': [{
"targets": [0,3],
"orderable": false
}]
});
});
</script>
Above my checkbox column at 0 positions and Action column at 3rd position so sorting disable in both table.
require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http');
// Register with spl_autoload:
$loader->register();
$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
You can also say:
cut -d\ -f 2
Note that there are two spaces after the backslash.
git rebase origin
means "rebase from the tracking branch of origin
", while git rebase origin/master
means "rebase from the branch master
of origin
"
You must have a tracking branch in ~/Desktop/test
, which means that git rebase origin
knows which branch of origin
to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie
), git doesn't know which branch of origin
it must take, and fails.
To fix this, you can make the branch track origin/master
with:
git branch --set-upstream-to=origin/master
Or, if master
isn't the currently checked-out branch:
git branch --set-upstream-to=origin/master master
I transfered some Java enums to javascript objects.
These objects returned correct arrays for me. if object keys are mixed type (string, int, char), there is a problem.
var Helper = {_x000D_
isEmpty: function (obj) {_x000D_
return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
},_x000D_
_x000D_
isObject: function (obj) {_x000D_
return (typeof obj === 'object');_x000D_
},_x000D_
_x000D_
sortObjectKeys: function (object) {_x000D_
return Object.keys(object)_x000D_
.sort(function (a, b) {_x000D_
c = a - b;_x000D_
return c_x000D_
});_x000D_
},_x000D_
containsItem: function (arr, item) {_x000D_
if (arr && Array.isArray(arr)) {_x000D_
return arr.indexOf(item) > -1;_x000D_
} else {_x000D_
return arr === item;_x000D_
}_x000D_
},_x000D_
_x000D_
pushArray: function (arr1, arr2) {_x000D_
if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
function TypeHelper() {_x000D_
var _types = arguments[0],_x000D_
_defTypeIndex = 0,_x000D_
_currentType,_x000D_
_value;_x000D_
_x000D_
if (arguments.length == 2) {_x000D_
_defTypeIndex = arguments[1];_x000D_
}_x000D_
_x000D_
Object.defineProperties(this, {_x000D_
Key: {_x000D_
get: function () {_x000D_
return _currentType;_x000D_
},_x000D_
set: function (val) {_x000D_
_currentType.setType(val, true);_x000D_
},_x000D_
enumerable: true_x000D_
},_x000D_
Value: {_x000D_
get: function () {_x000D_
return _types[_currentType];_x000D_
},_x000D_
set: function (val) {_x000D_
_value.setType(val, false);_x000D_
},_x000D_
enumerable: true_x000D_
}_x000D_
});_x000D_
_x000D_
this.getAsList = function (keys) {_x000D_
var list = [];_x000D_
Helper.sortObjectKeys(_types).forEach(function (key, idx, array) {_x000D_
if (key && _types[key]) {_x000D_
_x000D_
if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
var json = {};_x000D_
json.Key = key;_x000D_
json.Value = _types[key];_x000D_
Helper.pushArray(list, json);_x000D_
}_x000D_
}_x000D_
});_x000D_
return list;_x000D_
};_x000D_
_x000D_
this.setType = function (value, isKey) {_x000D_
if (!Helper.isEmpty(value)) {_x000D_
Object.keys(_types).forEach(function (key, idx, array) {_x000D_
if (Helper.isObject(value)) {_x000D_
if (value && value.Key == key) {_x000D_
_currentType = key;_x000D_
}_x000D_
} else if (isKey) {_x000D_
if (value && value.toString() == key.toString()) {_x000D_
_currentType = key;_x000D_
}_x000D_
} else if (value && value.toString() == _types[key]) {_x000D_
_currentType = key;_x000D_
}_x000D_
});_x000D_
} else {_x000D_
this.setDefaultType();_x000D_
}_x000D_
return isKey ? _types[_currentType] : _currentType;_x000D_
};_x000D_
_x000D_
this.setTypeByIndex = function (index) {_x000D_
var keys = Helper.sortObjectKeys(_types);_x000D_
for (var i = 0; i < keys.length; i++) {_x000D_
if (index === i) {_x000D_
_currentType = keys[index];_x000D_
break;_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
this.setDefaultType = function () {_x000D_
this.setTypeByIndex(_defTypeIndex);_x000D_
};_x000D_
_x000D_
this.setDefaultType();_x000D_
}_x000D_
_x000D_
_x000D_
var TypeA = {_x000D_
"-1": "Any",_x000D_
"2": "2L",_x000D_
"100": "100L",_x000D_
"200": "200L",_x000D_
"1000": "1000L"_x000D_
};_x000D_
_x000D_
var TypeB = {_x000D_
"U": "Any",_x000D_
"W": "1L",_x000D_
"V": "2L",_x000D_
"A": "100L",_x000D_
"Z": "200L",_x000D_
"K": "1000L"_x000D_
};_x000D_
console.log('keys of TypeA', Helper.sortObjectKeys(TypeA));//keys of TypeA ["-1", "2", "100", "200", "1000"]_x000D_
_x000D_
console.log('keys of TypeB', Helper.sortObjectKeys(TypeB));//keys of TypeB ["U", "W", "V", "A", "Z", "K"]_x000D_
_x000D_
var objectTypeA = new TypeHelper(TypeA),_x000D_
objectTypeB = new TypeHelper(TypeB);_x000D_
_x000D_
console.log('list of objectA = ', objectTypeA.getAsList());_x000D_
console.log('list of objectB = ', objectTypeB.getAsList());
_x000D_
Types:
var TypeA = {
"-1": "Any",
"2": "2L",
"100": "100L",
"200": "200L",
"1000": "1000L"
};
var TypeB = {
"U": "Any",
"W": "1L",
"V": "2L",
"A": "100L",
"Z": "200L",
"K": "1000L"
};
Sorted Keys(output):
Key list of TypeA -> ["-1", "2", "100", "200", "1000"]
Key list of TypeB -> ["U", "W", "V", "A", "Z", "K"]
Android locked down GET_ACCOUNTS
recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.
AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
MainActivity.java
package com.example.patrick.app2;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.*;
public class MainActivity extends AppCompatActivity {
final static int requestcode = 4; //arbitrary constant less than 2^16
private static String getEmailId(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
return "length is zero";
}
return account.name;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case requestcode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String emailAddr = getEmailId(getApplicationContext());
ShowMessage(emailAddr);
} else {
ShowMessage("Permission Denied");
}
}
}
public void ShowMessage(String email)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(email);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
!= PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions( this, new String[]
{ android.Manifest.permission.GET_ACCOUNTS },requestcode );
}
else
{
String possibleEmail = getEmailId(getApplicationContext());
ShowMessage(possibleEmail);
}
}
}
The Gantt charts given by Hifzan and Raja are for FCFS algorithms.
With an SJF algorithm, processes can be interrupted. That is, every process doesn't necessarily execute straight through their given burst time.
P3|P2|P4|P3|P5|P1|P5
1|2|3|5|7|8|11|14
P3 arrives at 1ms, then is interrupted by P2 and P4 since they both have smaller burst times, and then P3 resumes. P5 starts executing next, then is interrupted by P1 since P1's burst time is smaller than P5's. You must note the arrival times and be careful. These problems can be trickier than how they appear at-first-glance.
EDIT: This applies only to Preemptive SJF algorithms. A plain SJF algorithm is non-preemptive, meaning it does not interrupt a process.
SHA1 is a one way hash. So you can not really revert it.
That's why applications use it to store the hash of the password and not the password itself.
Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.
Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.
Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.
In his blog he shows a table that tells us the probability of collisions for a given input set.
As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.
A simple java program will show us what his table shows:
public class Main {
public static void main(String[] args) {
char[] inputValue = new char[10];
Map<Integer, String> hashValues = new HashMap<Integer, String>();
int collisionCount = 0;
for (int i = 0; i < 77163; i++) {
String asString = nextValue(inputValue);
int hashCode = asString.hashCode();
String collisionString = hashValues.put(hashCode, asString);
if (collisionString != null) {
collisionCount++;
System.out.println("Collision: " + asString + " <-> " + collisionString);
}
}
System.out.println("Collision count: " + collisionCount);
}
private static String nextValue(char[] inputValue) {
nextValue(inputValue, 0);
int endIndex = 0;
for (int i = 0; i < inputValue.length; i++) {
if (inputValue[i] == 0) {
endIndex = i;
break;
}
}
return new String(inputValue, 0, endIndex);
}
private static void nextValue(char[] inputValue, int index) {
boolean increaseNextIndex = inputValue[index] == 'z';
if (inputValue[index] == 0 || increaseNextIndex) {
inputValue[index] = 'A';
} else {
inputValue[index] += 1;
}
if (increaseNextIndex) {
nextValue(inputValue, index + 1);
}
}
}
My output end with:
Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135
It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A
and z
.
Let's take the last reported collision and check
System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());
My output is
86390
86390
Conclusion:
If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.
And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.
For extra themes, including making VS 2012 look like VS 2010 see:
http://visualstudiogallery.msdn.microsoft.com/366ad100-0003-4c9a-81a8-337d4e7ace05
Inspired by the comment of @MitMaro, I wrote a small benchmark to test the speed of solutions of @Gumbo, @Matt Bridges and @justin the proposal in the question:
function teststrtok($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$str = strtok($str,'?');
}
}
function testexplode($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$str = explode('?', $str);
}
}
function testregexp($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
preg_replace('/\\?.*/', '', $str);
}
}
function teststrpos($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$qPos = strpos($str, "?");
$url_without_query_string = substr($str, 0, $qPos);
}
}
$number_of_runs = 10;
for($runs = 0; $runs < $number_of_runs; $runs++){
$number_of_tests = 40000;
$functions = array("strtok", "explode", "regexp", "strpos");
foreach($functions as $func){
$starttime = microtime(true);
call_user_func("test".$func, $number_of_tests);
echo $func.": ". sprintf("%0.2f",microtime(true) - $starttime).";";
}
echo "<br />";
}
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
Result: @justin's strtok is the fastest.
Note: tested on a local Debian Lenny system with Apache2 and PHP5.
Using execComand:
<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">
In the next link: execCommand
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
I know this is old but this is how you do it:
git clone https://oauth2:[email protected]/vendor/package.git
WinSCp now supports S3 protocol
First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.
Make sure New site node is selected.
On the New site node, select Amazon S3 protocol.
Enter your AWS user Access key ID and Secret access key
Save your site settings using the Save button.
Login using the Login button.
This will alert the index of the clicked selector (starting with 0 for the first):
$('selector').click(function(){
alert( $('selector').index(this) );
});
An IEnumerator
is a thing that can enumerate: it has the Current
property and the MoveNext
and Reset
methods (which in .NET code you probably won't call explicitly, though you could).
An IEnumerable
is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator
.
Which do you use? The only reason to use IEnumerator
is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator
. But you'd still need to return that IEnumerator
in an IEnumerable
class.
For a look at what an enumerator (implementing IEnumerator<T>
) looks like, see any Enumerator<T>
class, such as the ones contained in List<T>
, Queue<T>,
or Stack<T>
. For a look at a class implementing IEnumerable
, see any standard collection class.
I was having same issue.
String[] arr= new String[] { "A", "B", "C" };
Object obj = arr;
And then passed the obj as varargs argument. It worked.
SWIFT 3 useful extension for set space between lines more easily :)
extension UILabel
{
func setLineHeight(lineHeight: CGFloat)
{
let text = self.text
if let text = text
{
let attributeString = NSMutableAttributedString(string: text)
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
attributeString.addAttribute(NSParagraphStyleAttributeName,
value: style,
range: NSMakeRange(0, text.characters.count))
self.attributedText = attributeString
}
}
}
The pdfrw
library can do this quite easily, assuming you don't need to preserve bookmarks and annotations, and your PDFs aren't encrypted. cat.py
is an example concatenation script, and subset.py
is an example page subsetting script.
The relevant part of the concatenation script -- assumes inputs
is a list of input filenames, and outfn
is an output file name:
from pdfrw import PdfReader, PdfWriter
writer = PdfWriter()
for inpfn in inputs:
writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)
As you can see from this, it would be pretty easy to leave out the last page, e.g. something like:
writer.addpages(PdfReader(inpfn).pages[:-1])
Disclaimer: I am the primary pdfrw
author.
sudo find / -Bmin 60
From the man
page:
-Bmin n
True if the difference between the time of a file's inode creation and the time
find
was started, rounded up to the next full minute, is n minutes.
Obviously, you may want to set up a bit differently, but this primary seems the best solution for searching for any file created in the last N minutes.
If you wirte to a .csv file in C++ - you should use the syntax of :
myfile <<" %s; %s; %d", string1, string2, double1 <<endl;
This will write the three variables (string 1&2 and double1) into separate columns and leave an empty row below them. In excel the ; means the new row, so if you want to just take a new row - you can alos write a simple ";" before writing your new data into the file. If you don't want to have an empty row below - you should delete the endl and use the:
myfile.open("result.csv", std::ios::out | std::ios::app);
syntax when opening the .csv file (example the result.csv). In this way next time you write something into your result.csv file - it will write it into a new row directly below the last one - so you can easily manage a for cycle if you would like to.
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
It is very simple. check for string empty condition in while condition.
You can use strlen function to check for the string length.
#include<stdio.h>
#include <string.h>
int main()
{
char url[63] = {'\0'};
do
{
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (strlen(url)<=0);
return(0);
}
check first character is '\0'
#include <stdio.h>
#include <string.h>
int main()
{
char url[63] = {'\0'};
do
{
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (url[0]=='\0');
return(0);
}
For your reference:
C arrays:
https://www.javatpoint.com/c-array
https://scholarsoul.com/arrays-in-c/
C strings:
https://www.programiz.com/c-programming/c-strings
https://scholarsoul.com/string-in-c/
https://en.wikipedia.org/wiki/C_string_handling
You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..
But another question is this: How do you set the color of the text You write?
Answer: You use the turtle.color() method or turtle.fillcolor(), like this:
turtle.fillcolor("blue")
or just:
turtle.color("orange")
These calls must come before the turtle.write() command..
explode('.', $string)
If you know your string has a fixed number of components you could use something like
list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;
Prints:
object
attribute
Just in case you guys need it, Here a couple of links that can help you:
Cheers
when referencing images in CSS or in an IMG tag, use image-name.jpg
while the image is really located under ./assets/images/image-name.jpg
I'd suggest:
document.querySelector('.rateRecipe.btns-one-small').click();
The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:
document.querySelector('.rateRecipe .btns-one-small').click();
The method getElementsByClassName()
takes a single class-name (rather than document.querySelector()
/document.querySelectorAll()
, which take a CSS selector), and you passed two (presumably class-names) to the method.
References:
There are a couple of Expression Language implementations out there that does this for you, could be preferable to using your own implementation as or if your requirments grow, see for example JUEL and MVEL
I like and have successfully used MVEL in at least one project.
Also see the Stackflow post JSTL/JSP EL (Expression Language) in a non JSP (standalone) context
A developer recently added subtitle support to VideoView.
When the MediaPlayer
starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set.
It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.
Short answer: Don't care about this "Exception".
Edit :
Still present in Lollipop,
If MediaPlayer
is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController
to the MediaPlayer
.
It should not be used in production environment and may have some side effects.
static MediaPlayer getMediaPlayer(Context context){
MediaPlayer mediaplayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return mediaplayer;
}
try {
Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );
Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
Object subtitleInstance = constructor.newInstance(context, null, null);
Field f = cSubtitleController.getDeclaredField("mHandler");
f.setAccessible(true);
try {
f.set(subtitleInstance, new Handler());
}
catch (IllegalAccessException e) {return mediaplayer;}
finally {
f.setAccessible(false);
}
Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);
setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
//Log.e("", "subtitle is setted :p");
} catch (Exception e) {}
return mediaplayer;
}
This code is trying to do the following from the hidden API
SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)
The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.
You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.
The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).
Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* @method - String value; the name of the Web Method to execute
* @data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* @beforeSend - Function(xhr, sett)
* @success - Function(data, status, xhr)
* @error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // @beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // @success
alert("a");
}, function(xhr, status, err){ // @error
alert("Sorry!!!");
});
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:
Controller action:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
for (int i = 0; i < 3; i++)
{
DataRow row = dt.NewRow();
row["Col1"] = "col 1, row " + i;
row["Col2"] = "col 2, row " + i;
row["Col3"] = "col 3, row " + i;
dt.Rows.Add(row);
}
return View(dt); //passing the DataTable as my Model
}
View: (w/ Model strongly typed as System.Data.DataTable)
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%=col.Caption %></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%=cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
</table>
Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.
You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.
I hope this helps!
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast
Stream<Object>
to aStream<Client>
?
No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object>
is not a super type of List<String>
, so you can't just cast a List<Object>
to a List<String>
.
Similar is the issue here. You can't cast Stream<Object>
to Stream<Client>
. Of course you can cast it indirectly like this:
Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;
but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream
it is at runtime. Everything is just Stream
.
BTW, what's wrong with your approach? Looks fine to me.