In addition to the angular json
filter already mentioned, there is also the angular toJson()
function.
angular.toJson(obj, pretty);
The second param of this function lets you switch on pretty printing and set the number of spaces to use.
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.
(default: 2)
First, copy the script over to Machine B using scp
[user@machineA]$ scp /path/to/script user@machineB:/home/user/path
Then, just run the script
[user@machineA]$ ssh user@machineB "/home/user/path/script"
This will work if you have given executable permission to the script.
As stated in the JQuery documentation
The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
You can use Apache Commons Math:
Precision.round(double x, int scale)
Internet Explorer (IE8 and lower) doesn't support addEventListener(...)
. It has its own event model using the attachEvent
method. You could use some code like this:
var element = document.getElementById('container');
if (document.addEventListener){
element .addEventListener('copy', beforeCopy, false);
} else if (el.attachEvent){
element .attachEvent('oncopy', beforeCopy);
}
Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.
By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.
Try this:
function explode(){
alert("Boom!");
}
setTimeout(explode, 2000);
Do you mean byte size or string length?
Byte size is measured with strlen()
, whereas string length is queried using mb_strlen()
. You can use substr()
to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr()
to trim it to X characters in the encoding of the string.
You can add the button role to a table row and Bootstrap will change the cursor without any css changes. I decided to use that role as a way to easily make any row clickable with very little code.
Html
<table class="table table-striped table-hover">
<tbody>
<tr role="button" data-href="#">
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
</tbody>
</table>
jQuery
$(function(){
$(".table").on("click", "tr[role=\"button\"]", function (e) {
window.location = $(this).data("href");
});
});
You can apply this same principle to add the button role to any tag.
Is it literally just the second line you want to indent, or is it from the second line (ie. a hanging indent)?
If it is the latter, something along the lines of this JSFiddle would be appropriate.
div {_x000D_
padding-left: 1.5em;_x000D_
text-indent:-1.5em;_x000D_
}_x000D_
_x000D_
span {_x000D_
padding-left: 1.5em;_x000D_
text-indent:-1.5em;_x000D_
}
_x000D_
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</div>_x000D_
_x000D_
<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</span>
_x000D_
This example shows how using the same CSS syntax in a DIV or SPAN produce different effects.
Well, if Google is cheating on you, you can cheat Google back:
This is the user-agent for pageSpeed:
“Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.8 (KHTML, like Gecko; Google Page Speed Insights) Chrome/19.0.1084.36 Safari/536.8”
You can insert a conditional to avoid serving the analytics script to PageSpeed:
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
// your analytics code here
<?php endif; ?>
Obviously, it won't make any real improvement, but if your only concern is getting a 100/100 score this will do it.
try this it is working
MySqlCommand dbcmd = _conn.CreateCommand();
dbcmd.CommandText = sqlCommandString;
dbcmd.ExecuteNonQuery();
long imageId = dbcmd.LastInsertedId;
$('#lol').get(0).style.display=''
or..
$('#lol').css('display', '')
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
Possible duplicate of Limit text length of EditText in Android
Use android:maxLength="140"
That should work. :)
Hope that helps
You need a back inserter to copy into vectors:
std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));
Assuming there is a table config
with unique index on config_code
column:
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
config1 abc 123
config2 def 456
This query returns line for config1
values, because it exists in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config1'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
config1 abc 123
This one returns default record as config3
doesn't exist in the table:
SELECT *
FROM (SELECT *
FROM config
WHERE config_code = 'config3'
OR config_code = 'default_config'
ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
WHERE rownum = 1;
CONFIG_CODE PARAM1 PARAM2
--------------- -------- --------
default_config def 000
In comparison with other solutions this one queries table config
only once.
If you give your table a unique id, its easier:
<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
onmouseup="checkMultipleSelection(this,event);">
<table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table"
cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:50px; text-align:left;">09:15 AM</td>
<td style="width:50px; text-align:left;">Item001</td>
<td style="width:50px; text-align:left;">10</td>
<td style="width:50px; text-align:left;">Address1</td>
<td style="width:50px; text-align:left;">46545465</td>
<td style="width:50px; text-align:left;">ref1</td>
</tr>
</table>
</div>
var multiselect =
document.getElementById(
'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
).rows[0].cells,
timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];
//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];
Render Line Endings is a VS Code extension that is still actively maintained (as of Apr 2020):
https://marketplace.visualstudio.com/items?itemName=medo64.render-crlf
https://github.com/medo64/render-crlf/
It can be configured like this:
{
"editor.renderWhitespace": "all",
"code-eol.newlineCharacter": "¬",
"code-eol.returnCharacter" : "¤",
"code-eol.crlfCharacter" : "¤¬",
}
and looks like this:
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
First try this: dont use the php composer.phar [parameters]
simply use composer [parameters]
if this doesn't work for you than try the rest. Hope it helps.
try with:
tr:last-child td:last-child{
border:none;
/*any other style*/
}
this will only affect the very last td element in the table, assuming is the only one (else, you'll just have to identify your table). Though, is very general, and it will adapt to the last TD if you add more content to your table. So if it is a particular case
td:nth-child(5){
border:none;
}
should be enough.
You could use toArray() to convert into an array of Objects followed by this method to convert the array of Objects into an array of Strings:
Object[] objectArray = lst.toArray();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
This worked for me :
I made a custom image component which takes in a boolean to check if the image is from web or is being passed from a local folder.
// In index.ios.js after importing the component
<CustomImage fromWeb={false} imageName={require('./images/logo.png')}/>
// In CustomImage.js which is my image component
<Image style={styles.image} source={this.props.imageName} />
If you see the code, instead of using one of these:
// NOTE: Neither of these will work
source={require('../images/'+imageName)}
var imageName = require('../images/'+imageName)
I'm just sending the entire require('./images/logo.png')
as a prop. It works!
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).
This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.
Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.
Use Integer.toString(tmpInt)
instead.
unicode_escape
doesn't work in generalIt turns out that the string_escape
or unicode_escape
solution does not work in general -- particularly, it doesn't work in the presence of actual Unicode.
If you can be sure that every non-ASCII character will be escaped (and remember, anything beyond the first 128 characters is non-ASCII), unicode_escape
will do the right thing for you. But if there are any literal non-ASCII characters already in your string, things will go wrong.
unicode_escape
is fundamentally designed to convert bytes into Unicode text. But in many places -- for example, Python source code -- the source data is already Unicode text.
The only way this can work correctly is if you encode the text into bytes first. UTF-8 is the sensible encoding for all text, so that should work, right?
The following examples are in Python 3, so that the string literals are cleaner, but the same problem exists with slightly different manifestations on both Python 2 and 3.
>>> s = 'naïve \\t test'
>>> print(s.encode('utf-8').decode('unicode_escape'))
naïve test
Well, that's wrong.
The new recommended way to use codecs that decode text into text is to call codecs.decode
directly. Does that help?
>>> import codecs
>>> print(codecs.decode(s, 'unicode_escape'))
naïve test
Not at all. (Also, the above is a UnicodeError on Python 2.)
The unicode_escape
codec, despite its name, turns out to assume that all non-ASCII bytes are in the Latin-1 (ISO-8859-1) encoding. So you would have to do it like this:
>>> print(s.encode('latin-1').decode('unicode_escape'))
naïve test
But that's terrible. This limits you to the 256 Latin-1 characters, as if Unicode had never been invented at all!
>>> print('Erno \\t Rubik'.encode('latin-1').decode('unicode_escape'))
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0151'
in position 3: ordinal not in range(256)
(Surprisingly, we do not now have two problems.)
What we need to do is only apply the unicode_escape
decoder to things that we are certain to be ASCII text. In particular, we can make sure only to apply it to valid Python escape sequences, which are guaranteed to be ASCII text.
The plan is, we'll find escape sequences using a regular expression, and use a function as the argument to re.sub
to replace them with their unescaped value.
import re
import codecs
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U........ # 8-digit hex escapes
| \\u.... # 4-digit hex escapes
| \\x.. # 2-digit hex escapes
| \\[0-7]{1,3} # Octal escapes
| \\N\{[^}]+\} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
def decode_escapes(s):
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
And with that:
>>> print(decode_escapes('Erno \\t Rubik'))
Erno Rubik
Try this solution.
$mainModelData = mainModel::where('column', $value)
->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
->orderBy('relation_table.title', 'ASC')
->with(['relationModal' => function ($q) {
$q->where('column', 'value');
}])->get();
Example:
$user = User::where('city', 'kullu')
->join('salaries', 'users.id', '=', 'salaries.user_id')
->orderBy('salaries.amount', 'ASC')
->with(['salaries' => function ($q) {
$q->where('amount', '>', '500000');
}])->get();
You can change the column name in join()
as per your database structure.
Same applies for guard statements. The same error message lead me to this post and answer (thanks @nhgrif).
The code: Print the last name of the person only if the middle name is less than four characters.
func greetByMiddleName(name: (first: String, middle: String?, last: String?)) {
guard let Name = name.last where name.middle?.characters.count < 4 else {
print("Hi there)")
return
}
print("Hey \(Name)!")
}
Until I declared last as an optional parameter I was seeing the same error.
Quite simply:
git rm --cached <file>
makes git stop tracking the file completely (leaving it in the filesystem, unlike plain git rm
*)git reset HEAD <file>
unstages any modifications made to the file since the last commit (but doesn't revert them in the filesystem, contrary to what the command name might suggest**). The file remains under revision control.If the file wasn't in revision control before (i.e. you're unstaging a file that you had just git add
ed for the first time), then the two commands have the same effect, hence the appearance of these being "two ways of doing something".
* Keep in mind the caveat @DrewT mentions in his answer, regarding git rm --cached
of a file that was previously committed to the repository. In the context of this question, of a file just added and not committed yet, there's nothing to worry about.
** I was scared for an embarrassingly long time to use the git reset command because of its name -- and still today I often look up the syntax to make sure I don't screw up. (update: I finally took the time to summarize the usage of git reset
in a tldr page, so now I have a better mental model of how it works, and a quick reference for when I forget some detail.)
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
fixed my agent string evaluation by scrubbing the string for LOWERCASE "iphone os 5_0" as opposed to "iPhone OS 5_0." now i am properly assigning iOS 5 specific classes to my html, when the uppercase scrub failed.
I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.
import inspect, os
class ClassOne:
def method1(self):
classtwoObj.method2()
class ClassTwo:
def method2(self):
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 4)
print '\nI was called from', calframe[1][3], \
'in', calframe[1][4][0][6: -2]
# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()
# start the program
os.system('cls')
classoneObj.method1()
Advisory locking has been used for ages and it can be used in bash scripts. I prefer simple flock
(from util-linux[-ng]
) over lockfile
(from procmail
). And always remember about a trap on exit (sigspec == EXIT
or 0
, trapping specific signals is superfluous) in those scripts.
In 2009 I released my lockable script boilerplate (originally available at my wiki page, nowadays available as gist). Transforming that into one-instance-per-user is trivial. Using it you can also easily write scripts for other scenarios requiring some locking or synchronization.
Here is the mentioned boilerplate for your convenience.
#!/bin/bash
# SPDX-License-Identifier: MIT
## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]>
##
## This script is licensed under the terms of the MIT license.
## https://opensource.org/licenses/MIT
#
# Lockable script boilerplate
### HEADER ###
LOCKFILE="/var/lock/`basename $0`"
LOCKFD=99
# PRIVATE
_lock() { flock -$1 $LOCKFD; }
_no_more_locking() { _lock u; _lock xn && rm -f $LOCKFILE; }
_prepare_locking() { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _no_more_locking EXIT; }
# ON START
_prepare_locking
# PUBLIC
exlock_now() { _lock xn; } # obtain an exclusive lock immediately or fail
exlock() { _lock x; } # obtain an exclusive lock
shlock() { _lock s; } # obtain a shared lock
unlock() { _lock u; } # drop a lock
### BEGIN OF SCRIPT ###
# Simplest example is avoiding running multiple instances of script.
exlock_now || exit 1
# Remember! Lock file is removed when one of the scripts exits and it is
# the only script holding the lock or lock is not acquired at all.
It does 5 things:
this
variable point to the newly created object.this
is mentioned.null
object reference. In this case, that object reference is returned instead.Note: constructor function refers to the function after the new
keyword, as in
new ConstructorFunction(arg1, arg2)
Once this is done, if an undefined property of the new object is requested, the script will check the object's [[prototype]] object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.
The most difficult part about this is point number 2. Every object (including functions) has this internal property called [[prototype]]. It can only be set at object creation time, either with new, with Object.create, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with Object.getPrototypeOf(someObject). There is no other way to set or read this value.
Functions, in addition to the hidden [[prototype]] property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.
Here is an example:
ObjMaker = function() {this.a = 'first';};
// ObjMaker is just a function, there's nothing special about it that makes
// it a constructor.
ObjMaker.prototype.b = 'second';
// like all functions, ObjMaker has an accessible prototype property that
// we can alter. I just added a property called 'b' to it. Like
// all objects, ObjMaker also has an inaccessible [[prototype]] property
// that we can't do anything with
obj1 = new ObjMaker();
// 3 things just happened.
// A new, empty object was created called obj1. At first obj1 was the same
// as {}. The [[prototype]] property of obj1 was then set to the current
// object value of the ObjMaker.prototype (if ObjMaker.prototype is later
// assigned a new object value, obj1's [[prototype]] will not change, but you
// can alter the properties of ObjMaker.prototype to add to both the
// prototype and [[prototype]]). The ObjMaker function was executed, with
// obj1 in place of this... so obj1.a was set to 'first'.
obj1.a;
// returns 'first'
obj1.b;
// obj1 doesn't have a property called 'b', so JavaScript checks
// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype
// ObjMaker.prototype has a property called 'b' with value 'second'
// returns 'second'
It's like class inheritance because now, any objects you make using new ObjMaker()
will also appear to have inherited the 'b' property.
If you want something like a subclass, then you do this:
SubObjMaker = function () {};
SubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!
// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype
// is now set to the object value of ObjMaker.prototype.
// The modern way to do this is with Object.create(), which was added in ECMAScript 5:
// SubObjMaker.prototype = Object.create(ObjMaker.prototype);
SubObjMaker.prototype.c = 'third';
obj2 = new SubObjMaker();
// [[prototype]] property of obj2 is now set to SubObjMaker.prototype
// Remember that the [[prototype]] property of SubObjMaker.prototype
// is ObjMaker.prototype. So now obj2 has a prototype chain!
// obj2 ---> SubObjMaker.prototype ---> ObjMaker.prototype
obj2.c;
// returns 'third', from SubObjMaker.prototype
obj2.b;
// returns 'second', from ObjMaker.prototype
obj2.a;
// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype
// was created with the ObjMaker function, which assigned a for us
I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.
For those using MooTools, here is equivalent code:
'mousewheel': function(event){
var height = this.getSize().y;
height -= 2; // Not sure why I need this bodge
if ((this.scrollTop === (this.scrollHeight - height) && event.wheel < 0) ||
(this.scrollTop === 0 && event.wheel > 0)) {
event.preventDefault();
}
Bear in mind that I, like some others, had to tweak a value by a couple of px, that is what the height -= 2 is for.
Basically the main difference is that in MooTools, the delta info comes from event.wheel instead of an extra parameter passed to the event.
Also, I had problems if I bound this code to anything (event.target.scrollHeight for a bound function does not equal this.scrollHeight for a non-bound one)
Hope this helps someone as much as this post helped me ;)
I had a similar problem, here is what i did:
{{ longString | limitTo: 20 }} {{longString.length < 20 ? '' : '...'}}
Optionals and default parameters are two different things.
An Optional is a variable that can be nil
, that's it.
Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)
If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil
. If your function looks like this func test(param: Int?)
, you can't call it like this test()
. Even though the parameter is optional, it doesn't have a default value.
You can also combine the two and have a parameter that takes an optional where nil
is the default value, like this: func test(param: Int? = nil)
.
If you have Android open source code, you can find the styles definition under:
src/frameworks/base/core/res/res/values
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">
@android:drawable/btn_check_label_background
</item>
<item name="android:button">
?android:attr/listChoiceIndicatorMultiple
</item>
</style>
::Get a number of lines that Dir commands returns (/-c to eliminate number separators: . ,) ["Tokens = 3" to look only at the third column of each line in Dir]
FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO set /a i=!i!+1
Number of the penultimate line, where is the number of bytes of the sum of files:
set /a line=%i%-1
Finally get the number of bytes in the penultimate line - 3rd column:
set i=0
FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO (
set /a i=!i!+1
set bytes=%%a
If !i!==%line% goto :size
)
:size
echo %bytes%
As it does not use word search it would not have language problems.
Limitations:
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
The following lines can be added either in Apache directives or in .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Don't forget to apply the apache changes if you modify the vhost.
(based on the default Drupal7 .htaccess but should work in many cases)
One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.
export function foo() { console.log('foo') },
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }
In this case you are export all of the functions with names, so you could do
import * as fns from './foo';
to get an object with properties for each function instead of the import you'd use for your first example:
import fns from './foo';
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) - To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) - To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true)
, just write if(condition)
(This way, for example, you'll not write =
by mistake).
Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.
To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.
(source: mozilla.net)
If you're trying to put a button in a rounded-rectangle border, you should check out msdn's example. I found this by googling for images of the problem (instead of text). Their bulky outer rectangle is (thankfully) easy to remove.
Note that you will have to redefine the button's behavior (since you've changed the ControlTemplate). That is, you will need to define the button's behavior when clicked using a Trigger tag (Property="IsPressed" Value="true") in the ControlTemplate.Triggers tag. Hope this saves someone else the time I lost :)
To wait for visibility
const EC = protractor.ExpectedConditions;
browser.wait(EC.visibilityOf(element(by.css('.icon-spinner icon-spin ng-hide')))).then(function() {
//do stuff
})
Xpath trick to only find visible elements
element(by.xpath('//i[not(contains(@style,"display:none")) and @class="icon-spinner icon-spin ng-hide"]))
Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.
@Component({
selector: 'key-up3',
template: `
<input #box (keyup.enter)="doSomething($event)">
<p>{{values}}</p>
`
})
export class KeyUpComponent_v3 {
doSomething(e) {
alert(e);
}
}
This works for me!
I think that parse_str is what you're looking for, something like this should do the trick for you:
parse_str($_SERVER['QUERY_STRING'], $vars);
Then the $vars
array will hold all the passed arguments.
$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
$SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"
$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;
It's more generic and will fit for any array!!
Pay attention on fact that Round
rounds.
So (I don't know if it matters in your industry or not), but:
float a = 12.345f;
Math.Round(a,2);
//result:12,35, and NOT 12.34 !
To make it more precise for your case we can do something like this:
int aInt = (int)(a*100);
float aFloat= aInt /100.0f;
//result:12,34
Add a live template called "ser" to the other group, set it to "Applicable in Java: declaration", and untick "Shorten FQ names". Give it a template text of just:
$serial$
Now edit variables and set serial to:
groovyScript("(System.env.JDK_HOME+'/bin/serialver -classpath '+com.intellij.openapi.fileEditor.FileDocumentManager.instance.getFile(_editor.document).path.replaceAll('/java/.*','').replaceAll('/src/','/build/classes/')+' '+_1).execute().text.replaceAll('.*: *','')",qualifiedClassName())
It assumes the standard Gradle project layout. Change /build/ to /target/ for Maven.
Is there any good example to give the difference between a 'struct' and a 'union'?
An imaginary communications protocol
struct packetheader {
int sourceaddress;
int destaddress;
int messagetype;
union request {
char fourcc[4];
int requestnumber;
};
};
In this imaginary protocol, it has been sepecified that, based on the "message type", the following location in the header will either be a request number, or a four character code, but not both. In short, unions allow for the same storage location to represent more than one data type, where it is guaranteed that you will only want to store one of the types of data at any one time.
Unions are largely a low-level detail based in C's heritage as a system programming language, where "overlapping" storage locations are sometimes used in this way. You can sometimes use unions to save memory where you have a data structure where only one of several types will be saved at one time.
In general, the OS doesn't care or know about structs and unions -- they are both simply blocks of memory to it. A struct is a block of memory that stores several data objects, where those objects don't overlap. A union is a block of memory that stores several data objects, but has only storage for the largest of these, and thus can only store one of the data objects at any one time.
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.
import org.apache.poi.xssf.usermodel.*; //import needed
XSSFWorkbook wb = new XSSFWorkbook (); // Create workbook
XSSFSheet sheet = wb.createSheet(); // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet
//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy"));
//2. Apply the Date cell style to a cell
//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
The approach you're looking for is FillDown
. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:
Sub FillDown()
Dim strFormulas(1 To 3) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=SUM(A2:B2)"
strFormulas(2) = "=PRODUCT(A2:B2)"
strFormulas(3) = "=A2/B2"
.Range("C2:E2").Formula = strFormulas
.Range("C2:E11").FillDown
End With
End Sub
Screenshots:
Result as of line: .Range("C2:E2").Formula = strFormulas
:
Result as of line: .Range("C2:E11").FillDown
:
Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown
, much like what you did.
Hope this helps!
This is how you can create a simple observable for static data.
let observable = Observable.create(observer => {
setTimeout(() => {
let users = [
{username:"balwant.padwal",city:"pune"},
{username:"test",city:"mumbai"}]
observer.next(users); // This method same as resolve() method from Angular 1
console.log("am done");
observer.complete();//to show we are done with our processing
// observer.error(new Error("error message"));
}, 2000);
})
to subscribe to it is very easy
observable.subscribe((data)=>{
console.log(data); // users array display
});
I hope this answer is helpful. We can use HTTP call instead static data.
Just here to show my implementation for @herman solution
ZoneId americaLaPazZone = ZoneId.of("UTC-04:00");
static Date firstDateOfMonth(Date date) {
LocalDate localDate = convertToLocalDateWithTimezone(date);
YearMonth baseMonth = YearMonth.from(localDate);
LocalDateTime initialDate = baseMonth.atDay(firstDayOfMonth).atStartOfDay();
return Date.from(initialDate.atZone(americaLaPazZone).toInstant());
}
static Date lastDateOfMonth(Date date) {
LocalDate localDate = convertToLocalDateWithTimezone(date);
YearMonth baseMonth = YearMonth.from(localDate);
LocalDateTime lastDate = baseMonth.atEndOfMonth().atTime(23, 59, 59);
return Date.from(lastDate.atZone(americaLaPazZone).toInstant());
}
static LocalDate convertToLocalDateWithTimezone(Date date) {
return LocalDateTime.from(date.toInstant().atZone(americaLaPazZone)).toLocalDate();
}
In bootstrap you can use .text-center
to align center. also add .row
and .col-md-*
to your code.
align=
is deprecated,
Added .col-xs-*
for demo
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
<div class="container">
<div class="row">
<div class="col-xs-4">
<p>Hello there</p>
</div>
<div class="col-xs-4 text-center">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="col-xs-4 text-right">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
</div>
_x000D_
For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
<div class="d-flex justify-content-between">
<div class="p-1">
<p>Hello there</p>
</div>
<div class="p-1">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="p-1">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
_x000D_
I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .
public static class ThreadHelperClass
{
delegate void SetTextCallback(Form f, Control ctrl, string text);
/// <summary>
/// Set text property of various controls
/// </summary>
/// <param name="form">The calling form</param>
/// <param name="ctrl"></param>
/// <param name="text"></param>
public static void SetText(Form form, Control ctrl, string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (ctrl.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
form.Invoke(d, new object[] { form, ctrl, text });
}
else
{
ctrl.Text = text;
}
}
}
Using the code:
private void btnTestThread_Click(object sender, EventArgs e)
{
Thread demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe));
demoThread.Start();
}
// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
}
You can try this way.
byte ptext[] = myString.getBytes("ISO-8859-1");
String value = new String(ptext, "UTF-8");
If you are using the HttpURLConnection
, call setConnectTimeout()
as described here:
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
For PHP code running on XAMPP on Windows I found I needed to edit php.ini to include the below
[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo = curl-ca-bundle.crt
and then copy to a file https://curl.haxx.se/ca/cacert.pem and rename to curl-ca-bundle.crt and place it under \xampp path (I couldn't get curl.capath to work). I also found the CAbundle on the cURL site wasn't enough for the remote site I was connecting to, so used one that is listed with a pre-compiled Windows version of curl 7.47.1 at http://winampplugins.co.uk/curl/
I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext
implementation is in a different project than your startup project and you run ef migrations
, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations
know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s
and -p
are optionals that default to the current folder.
If your RDBMS supports the OVER clause...
SELECT
title
FROM
(
select
title, count(*) OVER (PARTITION BY title) as cnt
from
kmovies
) T
ORDER BY
cnt DESC
You can easily wrap the readFile command with a promise like so:
async function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
reject(err);
}
resolve(data);
});
});
}
then use:
await readFile("path/to/file");
Have you looked into rasdial?
Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network
ie
rasdial "VPN NETWORK NAME" "Username" *
it will then prompt for a password, else you can use "username" "password", this is however less secure
http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265
You can also use shorthand for describe as desc
for table description.
desc [db_name.]table_name;
or
use db_name;
desc table_name;
You can also use explain
for table description.
explain [db_name.]table_name;
See official doc
Will give output like:
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| age | int(10) | YES | | NULL | |
| sex | varchar(10) | YES | | NULL | |
| sal | int(10) | YES | | NULL | |
| location | varchar(20) | YES | | Pune | |
+----------+-------------+------+-----+---------+-------+
ok if you are getting a Uncaught Error: [$injector:modulerr]
and the angular module is in the error that is telling you, you have an duplicate ng-app module.
When you sort strings to present to the user, you should not use the simple compare:
method. Instead, you should always use localized comparison methods such as localizedCompare:
or localizedCaseInsensitiveCompare:
.
For more details, see Searching, Comparing, and Sorting Strings.
CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
There is generic solution for setting max length in Swift. By IBInspectable you can add new Attribute in Xcode Attribute Inspector.
import UIKit
private var maxLengths = [UITextField: Int]()
extension UITextField {
@IBInspectable var maxLength: Int {
get {
guard let length = maxLengths[self]
else {
return Int.max
}
return length
}
set {
maxLengths[self] = newValue
addTarget(
self,
action: Selector("limitLength:"),
forControlEvents: UIControlEvents.EditingChanged
)
}
}
func limitLength(textField: UITextField) {
guard let prospectiveText = textField.text
where prospectiveText.characters.count > maxLength else {
return
}
let selection = selectedTextRange
text = prospectiveText.substringWithRange(
Range<String.Index>(prospectiveText.startIndex ..< prospectiveText.startIndex.advancedBy(maxLength))
)
selectedTextRange = selection
}
}
Tests of the various methods:
var repeatMethods = {
control: function (n,s) {
/* all of these lines are common to all methods */
if (n==0) return '';
if (n==1 || isNaN(n)) return s;
return '';
},
divideAndConquer: function (n, s) {
if (n==0) return '';
if (n==1 || isNaN(n)) return s;
with(Math) { return arguments.callee(floor(n/2), s)+arguments.callee(ceil(n/2), s); }
},
linearRecurse: function (n,s) {
if (n==0) return '';
if (n==1 || isNaN(n)) return s;
return s+arguments.callee(--n, s);
},
newArray: function (n, s) {
if (n==0) return '';
if (n==1 || isNaN(n)) return s;
return (new Array(isNaN(n) ? 1 : ++n)).join(s);
},
fillAndJoin: function (n, s) {
if (n==0) return '';
if (n==1 || isNaN(n)) return s;
var ret = [];
for (var i=0; i<n; i++)
ret.push(s);
return ret.join('');
},
concat: function (n,s) {
if (n==0) return '';
if (n==1 || isNaN(n)) return s;
var ret = '';
for (var i=0; i<n; i++)
ret+=s;
return ret;
},
artistoex: function (n,s) {
var result = '';
while (n>0) {
if (n&1) result+=s;
n>>=1, s+=s;
};
return result;
}
};
function testNum(len, dev) {
with(Math) { return round(len+1+dev*(random()-0.5)); }
}
function testString(len, dev) {
return (new Array(testNum(len, dev))).join(' ');
}
var testTime = 1000,
tests = {
biggie: { str: { len: 25, dev: 12 }, rep: {len: 200, dev: 50 } },
smalls: { str: { len: 5, dev: 5}, rep: { len: 5, dev: 5 } }
};
var testCount = 0;
var winnar = null;
var inflight = 0;
for (var methodName in repeatMethods) {
var method = repeatMethods[methodName];
for (var testName in tests) {
testCount++;
var test = tests[testName];
var testId = methodName+':'+testName;
var result = {
id: testId,
testParams: test
}
result.count=0;
(function (result) {
inflight++;
setTimeout(function () {
result.start = +new Date();
while ((new Date() - result.start) < testTime) {
method(testNum(test.rep.len, test.rep.dev), testString(test.str.len, test.str.dev));
result.count++;
}
result.end = +new Date();
result.rate = 1000*result.count/(result.end-result.start)
console.log(result);
if (winnar === null || winnar.rate < result.rate) winnar = result;
inflight--;
if (inflight==0) {
console.log('The winner: ');
console.log(winnar);
}
}, (100+testTime)*testCount);
}(result));
}
}
Here's the simple, built-in way:
<span title="My tip">text</span>
That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
There are two ways to tackle this based on what you want:
Solution 1: Remove purple commits, preserving history (incase you want to roll back)
git revert -m 1 <SHA of merge>
-m 1
specifies which parent line to choose
Purple commits will still be there in history but since you have reverted, you will not see code from those commits.
Solution 2: Completely remove purple commits (disruptive change if repo is shared)
git rebase -i <SHA before branching out>
and delete (remove lines) corresponding to purple commits.
This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase
.
unsigned char
is the heart of all bit trickery. In almost ALL compiler for ALL platform an unsigned char
is simply a byte and an unsigned integer of (usually) 8 bits that can be treated as a small integer or a pack of bits.
In addiction, as someone else has said, the standard doesn't define the sign of a char. so you have 3 distinct char
types: char
, signed char
, unsigned char
.
I tried one after other and found a best answer at the time:
https://stackoverflow.com/a/3187524/985399
I skip old browsers so I made the code shorter to work on modern browsers (IE9+)
document.addEventListener("mouseout", function(e) {_x000D_
let t = e.relatedTarget || e.toElement;_x000D_
if (!t || t.nodeName == "HTML") {_x000D_
console.log("left window");_x000D_
}_x000D_
});_x000D_
_x000D_
document.write("<br><br>PROBLEM<br><br><div>Mouseout trigg on HTML elements</div>")
_x000D_
Here you see the browser support
That was pretty short I thought
But a problem still remained because "mouseout" trigg on all elements in the document.
To prevent it from happen, use mouseleave (IE5.5+). See the good explanation in the link.
The following code works without triggering on elements inside the element to be inside or outside of. Try also drag-release outside the document.
var x = 0_x000D_
_x000D_
document.addEventListener("mouseleave", function(e) { console.log(x++) _x000D_
})_x000D_
_x000D_
document.write("<br><br>SOLUTION<br><br><div>Mouseleave do not trigg on HTML elements</div>")
_x000D_
You can set the event on any HTML element. Do not have the event on document.body
though, because the windows scrollbar may shrink the body and fire when mouse pointer is abowe the scroll bar when you want to scroll but not want to trigg a mouseLeave event over it. Set it on document
instead, as in the example.
you can use like this:
string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");
Iterate through, keeping track as you go.
var min = null;
var max = null;
for (var i = 0, len = arr.length; i < len; ++i)
{
var elem = arr[i];
if (min === null || min > elem) min = elem;
if (max === null || max < elem) max = elem;
}
alert( "min = " + min + ", max = " + max );
This will leave min/max null if there are no elements in the array. Will set min and max in one pass if the array has any elements.
You could also extend Array with a range
method using the above to allow reuse and improve on readability. See a working fiddle at http://jsfiddle.net/9C9fU/
Array.prototype.range = function() {
var min = null,
max = null,
i, len;
for (i = 0, len = this.length; i < len; ++i)
{
var elem = this[i];
if (min === null || min > elem) min = elem;
if (max === null || max < elem) max = elem;
}
return { min: min, max: max }
};
Used as
var arr = [3, 9, 22, -7, 44, 18, 7, 9, 15];
var range = arr.range();
console.log(range.min);
console.log(range.max);
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
If you have a Java 8 Clock, then you can use clock.millis()
(although it recommends you use clock.instant()
to get a Java 8 Instant, as it's more accurate).
Why would you use a Java 8 clock? So in your DI framework you can create a Clock bean:
@Bean
public Clock getClock() {
return Clock.systemUTC();
}
and then in your tests you can easily Mock it:
@MockBean private Clock clock;
or you can have a different bean:
@Bean
public Clock getClock() {
return Clock.fixed(instant, zone);
}
which helps with tests that assert dates and times immeasurably.
It's simple. On the sender side, use Intent.putExtra
:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
On the receiver side, use Intent.getIntExtra
:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Apart from the excellent answers above I though I would write a C function that does not use any libraries and has some guards against bad strings.
uint8_t* datahex(char* string) {
if(string == NULL)
return NULL;
size_t slength = strlen(string);
if((slength % 2) != 0) // must be even
return NULL;
size_t dlength = slength / 2;
uint8_t* data = malloc(dlength);
memset(data, 0, dlength);
size_t index = 0;
while (index < slength) {
char c = string[index];
int value = 0;
if(c >= '0' && c <= '9')
value = (c - '0');
else if (c >= 'A' && c <= 'F')
value = (10 + (c - 'A'));
else if (c >= 'a' && c <= 'f')
value = (10 + (c - 'a'));
else {
free(data);
return NULL;
}
data[(index/2)] += value << (((index + 1) % 2) * 4);
index++;
}
return data;
}
Explanation:
a. index / 2 | Division between integers will round down the value, so 0/2 = 0, 1/2 = 0, 2/2 = 1, 3/2 = 1, 4/2 = 2, 5/2 = 2, etc. So, for every 2 string characters we add the value to 1 data byte.
b. (index + 1) % 2 | We want odd numbers to result to 1 and even to 0 since the first digit of a hex string is the most significant and needs to be multiplied by 16. so for index 0 => 0 + 1 % 2 = 1, index 1 => 1 + 1 % 2 = 0 etc.
c. << 4 | Shift by 4 is multiplying by 16. example: b00000001 << 4 = b00010000
simply: document.cookie="name=value;path=/";
There is a negative point to it
Now, the cookie will be available to all directories on the domain it is set from. If the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to your cookie information.
Since most of the answers use ifconfig
to extract the IPv4 from the eth0 interface, which is deprecated in favor of ip addr
, the following code could be used instead:
import os
ipv4 = os.popen('ip addr show eth0 | grep "\<inet\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip()
ipv6 = os.popen('ip addr show eth0 | grep "\<inet6\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip()
Alternatively, you can shift part of the parsing task to the python interpreter by using split()
instead of grep and awk, as @serg points out in the comment:
import os
ipv4 = os.popen('ip addr show eth0').read().split("inet ")[1].split("/")[0]
ipv6 = os.popen('ip addr show eth0').read().split("inet6 ")[1].split("/")[0]
But in this case you have to check the bounds of the array returned by each split()
call.
Another version using regex:
import os
import re
ipv4 = re.search(re.compile(r'(?<=inet )(.*)(?=\/)', re.M), os.popen('ip addr show eth0').read()).groups()[0]
ipv6 = re.search(re.compile(r'(?<=inet6 )(.*)(?=\/)', re.M), os.popen('ip addr show eth0').read()).groups()[0]
In addition to answer by Dinesh Prajapati, Use
adb -d logcat <your package name>:<log level>
where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.
Now your command goes like:
adb -d logcat com.example.example:V > logfileName_WithPath.txt
this
reference a javascript object and $(this)
used to encapsulate with jQuery.
Example =>
// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')
// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)
// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()
//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()
//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value
or
this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')
You can do it this with two replace's
//let stw be "John Smith $100,000.00 M"
sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"
sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"
sw.WriteLine(sb_trim);
$user = $_SERVER['REMOTE_USER'];
http://php.net/manual/en/reserved.variables.server.php
Authenticated user
If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:
Oracle Java SE 6: java.awt.Font
There is a tutorial available from Oracle that shows this example:
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
//Handle exception
}
I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.
An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.
Mac OS (MacBook Pro):
Back: CTRL(control) + - (Hyphen)
Back Forward: CTRL + Shift + - (Hyphen)
It's the same way you run it from command line. Just put that "command line" into a ".bat" file.
So, if you use java -cp .;foo.jar Bar
, put that into a .bat file as
@echo off
java -cp .;foo.jar Bar
You are mixing mysqli and mysql extensions, which will not work.
You need to use
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");
mysqli
has many improvements over the original mysql
extension, so it is recommended that you use mysqli
.
The following works for me:
?rel=0&fs=0&showinfo=0
You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-
@JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = Bike.class, name = "bike"),
@Type(value = Auto.class, name = "auto"),
@Type(value = Car.class, name = "car")
})
public abstract class Vehicle {
// fields, constructors, getters, setters
}
In test file:
const APP_PORT = process.env.APP_PORT || 8080;
In the test script of ./package.json
:
"scripts": {
"test": "jest --setupFiles dotenv/config",
}
In ./env
:
APP_PORT=8080
One easy non-loop approach would be to use genvarname
to create a cell array of strings:
>> N = 5;
>> f = genvarname(repmat({'f'}, 1, N), 'f')
f =
'f1' 'f2' 'f3' 'f4' 'f5'
The function genvarname
has been deprecated, so matlab.lang.makeUniqueStrings
can be used instead in the following way to get the same output:
>> N = 5;
>> f = strrep(matlab.lang.makeUniqueStrings(repmat({'f'}, 1, N), 'f'), '_', '')
f =
1×5 cell array
'f1' 'f2' 'f3' 'f4' 'f5'
I show you this with an example:
string userName= textBox1.text;
and then use it as you wish
According to the documentation, timestamp
is a synonym for rowversion
- it's automatically generated and guaranteed1 to be unique. datetime
isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.
1 Assuming you use it properly, of course. See comments.
If you need this for your admin site, there is also the ModelAdmin.get_fields
method (docs), which returns a list
of field name strings
.
For example:
class MyModelAdmin(admin.ModelAdmin):
# extending change_view, just as an example
def change_view(self, request, object_id=None, form_url='', extra_context=None):
# get the model field names
field_names = self.get_fields(request)
# use the field names
...
Try set a user in nginx.conf, maybe that's why he can not start the service:
User www-data;
In 9.4.4 using the #>>
operator works for me:
select to_json('test'::text) #>> '{}';
To use with a table column:
select jsoncol #>> '{}' from mytable;
SELECT *
FROM TableName
WHERE julianday(substr(date,7)||'-'||substr(date,4,2)||'-'||substr(date,1,2)) BETWEEN julianday('2011-01-11') AND julianday('2011-08-11')
Note that I use the format : dd/mm/yyyy
If you use d/m/yyyy, Change in substr()
Hope this will help you.
Use System.Diagnostics.Process to launch an instance of Notepad.exe.
ObservableCollection < T > has a constructor overload which takes IEnumerable < T >
Example for a List of int
:
ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);
One more example for a List of ObjectA
:
ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);
GetWindowThreadProcessId((IntPtr)app.Hwnd, out iProcessId);
wb.Close(true,Missing.Value,Missing.Value);
app.Quit();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (p.Id == iProcessId)
{
try
{
p.Kill();
}
catch { }
}
}
}
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
uint iProcessId = 0;
this GetWindowThreadProcessId finds the correct Process Id o excell .... After kills it.... Enjoy It!!!
Another library that might be useful for HTML processing is jsoup. Jsoup tries to clean malformed HTML and allows html parsing in Java using jQuery like tag selector syntax.
I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.
http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET
If you want to add a class to the first and second td you can use .each()
and slice()
$(".location table tbody tr").each(function(){
$(this).find("td").slice(0, 2).addClass("black");
});
for set empty all input such textarea select and input run this code:
$('#message').val('').change();
In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)
I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".
see here
The consumable media types of the mapped request, narrowing the primary mapping.
the producer is used to narrow the primary mapping, you send request should specify the exact header to match it.
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
Your classes should look like this
[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}
public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}
Here is my testcode.
string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";
XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}
If you want to read a text file you should load the file into a FileStream and deserialize this.
using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open))
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}
The correct answer is already given, nevertheless here is the better way (than switch):
private Dictionary<Operator, Func<int, int, double>> operators =
new Dictionary<Operator, Func<int, int, double>>
{
{ Operator.PLUS, ( a, b ) => a + b },
{ Operator.MINUS, ( a, b ) => a - b },
{ Operator.MULTIPLY, ( a, b ) => a * b },
{ Operator.DIVIDE ( a, b ) => (double)a / b },
};
public double Calculate( int left, int right, Operator op )
{
return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}
What you need is this:
a, b, c = [0,3,5] # Unpack the list, now a, b, and c are ints
a = 1 # `a` did equal 0, not [0,3,5]
print(a)
print(b)
print(c)
If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);
or
for(int i=0; i<4; i++)
sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
sub3[i] = baseString[i+8];
sub3[4] = 0;
Prefer strncpy if possible.
My 2 Cent ->
Very late to party
DataGrid -> Column -> Width="*" only work if DataGrid parent container has fix width.
example : i put the DataGrid in Grid -> Column whose width="Auto" then Width="*" in DataGrid does not work but if you set Grid -> Column Width="450" mean fixed then it work fine
Anybody facing the same issues, follow the simple steps:
Import the project android
from downloaded zxing-master
zip file using option Import project (Eclipse ADT, Gradle, etc.)
and add the dollowing 2 lines of codes in your app level build.gradle
file and and you are ready to run.
So simple, yahh...
dependencies {
// https://mvnrepository.com/artifact/com.google.zxing/core
compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
// https://mvnrepository.com/artifact/com.google.zxing/android-core
compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'
}
You can always find latest version core
and android core
from below links:
https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0
UPDATE (29.05.2019)
Add these dependencies instead:
dependencies {
implementation 'com.google.zxing:core:3.4.0'
implementation 'com.google.zxing:android-core:3.3.0'
}
You could try:
UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];
Another nice and useful solution is to create this kind of extension:
extension Array where Element: Equatable {
@discardableResult mutating func remove(object: Element) -> Bool {
if let index = index(of: object) {
self.remove(at: index)
return true
}
return false
}
@discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
if let index = self.index(where: { (element) -> Bool in
return predicate(element)
}) {
self.remove(at: index)
return true
}
return false
}
}
In this way, if you have your array with custom objects:
let obj1 = MyObject(id: 1)
let obj2 = MyObject(id: 2)
var array: [MyObject] = [obj1, obj2]
array.remove(where: { (obj) -> Bool in
return obj.id == 1
})
// OR
array.remove(object: obj2)
If you just want to display some html text and don't really need a TextView
, then take a WebView
and use it like following:
String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);
This does not restrict you to a few html tags either.
FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.
http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY
Try docker logout
first, then relogin with docker login
The return
statement exits a function from anywhere within the function:
function something(x)
{
if (x >= 10)
// this leaves the function if x is at least 10.
return;
// this message displays only if x is less than 10.
alert ("x is less than 10!");
}
Actually, the problem is now solved. I added the 'pause' argument to the method 'carousel' like below:
$(document).ready(function() {
$('.carousel').carousel('pause');
});
Anyway, thanks so much @Yohn for your tips toward this solution.
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Change the frame size of viewcontroller.view.frame
, and then add to subview. [viewcontrollerparent.view addSubview:viewcontroller.view]
I'd say the most famous programming game there has been is the core wars. I don't know if you can still find active "rings" although there was a lot when I tried it some time ago (4 or 5 years).
If you want to download an image from https:
$output_filename = 'output.png';
$host = "https://.../source.png"; // <-- Source image url (FIX THIS)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // <-- don't forget this
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // <-- and this
$result = curl_exec($ch);
curl_close($ch);
$fp = fopen($output_filename, 'wb');
fwrite($fp, $result);
fclose($fp);
A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See JavaBeans Conventions for more details.
A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.
I know this post is very old, For those who don't want to use android:fillViewport="true"
because it sometimes doesn't bring up the edittext above keyboard.
Use Relative layout instead of LinearLayout it solves the purpose.
Just as reference let me quote the osxfuse FAQ
4.8. How should I unmount my "FUSE for OS X" file system? I cannot find the fusermount program anywhere.
Just use the standard umount command in OS X. You do not need the Linux-specific fusermount with "FUSE for OS X".
As mentioned above, either diskutil unmount
or umount
should work
I wanted to answer to the following question which is a little bit different than this:
Best way to print messages on multiple lines
He wanted to show lines from repeated characters too. He wanted this output:
----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000
----------------------------------------
You can create those lines inside f-strings with a multiplication, like this:
run_mode, num_repeats, num_runs = 'short', 5, 1000
s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}
{'-'*40}
"""
print(s)
I'm the author of iso8601 utils. It can be found on GitHub or on PyPI. Here's how you can parse your example:
>>> from iso8601utils import parsers
>>> parsers.datetime('2008-09-03T20:56:35.450686Z')
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)
$("div.test:not(:first)").hide();
or:
$("div.test:not(:eq(0))").hide();
or:
$("div.test").not(":eq(0)").hide();
or:
$("div.test:gt(0)").hide();
or: (as per @Jordan Lev's comment):
$("div.test").slice(1).hide();
and so on.
See:
You should be aware that in C, unlike Java or C#, there is absolutely no possibility to successfully "guess" the type of object a void*
pointer points at. Something similar to getClass()
simply doesn't exist, since this information is nowhere to be found. For that reason, the kind of "generic" you are looking for always comes with explicit metainformation, like the int b
in your example or the format string in the printf
family of functions.
You can simply use This one line code to get date in year
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.
Theres a reason that ASP.Net does not look into your nested controls recursively by default:
Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.
As long as you don't need the definition (think pointers and references) you can get away with forward declarations. This is why mostly you'd see them in headers while implementation files typically will pull the header for the appropriate definition(s).
Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail
and firstOrFail
methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException
will be thrown:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
If this problem same me.You maybe forget set team in unittest in your target project try do this picture
First, add a textView in the XML file
<TextView
android:id="@+id/rate_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/what_U_want_to_display_in_first_time"
/>
then add a button in xml file with id btn_change_textView and write this two line of code in onCreate()
method of activity
Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);
then use clickListener()
on button object like this
btn.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
textView.setText("write here what u want to display after button click in string");
}
});
This must have happened because by mistake you reinitialized git in the same directory. Delete the .git folder using the following command Go to repository you want to upload open the terminal and then use the following commands
sudo rm -r .git
git init
git commit -m "first commit"
git remote add origin https://github.com/user_name/repo
git push -u origin master
After that enter the username and password and you are good to goFaster than the above solutions, including the highest rated one:
(x < 0) ? -1 : (x > 0)
key
is simply a variable.
For Python2.X:
d = {'x': 1, 'y': 2, 'z': 3}
for my_var in d:
print my_var, 'corresponds to', d[my_var]
... or better,
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.iteritems():
print the_key, 'corresponds to', the_value
For Python3.X:
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.items():
print(the_key, 'corresponds to', the_value)
How about something like this?
<div id="leftContainer">
<span>Company Name</span>
<br><input type="text" value="John Lewis Partnership">
</div>
<div id="rightContainer">
<span>Contact Name</span>
<br><input type="text" value="Timothy Patten">
</div>
Then, you can align the 2 divs by floating them left and right:-
#leftContainer {
float:left;
}
#rightContainer {
float:right;
}
Please try the below code for repeated fade-out/fade-in animation
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.3f);
anim.setRepeatCount(Animation.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
anim.setDuration(300);
view.setAnimation(anim); // to start animation
view.setAnimation(null); // to stop animation
localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost
they'll be connecting to their computer instead or yours.
To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all
on a command line.
You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.
In case you can't for some reason use the same Random
again and again, try initializing it with something that changes all the time, like the time itself.
new Random(new System.DateTime().Millisecond).Next();
Remember this is bad practice though.
EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:
Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.
The code below is probably your best option:
new Random().Next();
You can use format like here,
public static double getDoubleValue(String value,int digit){
if(value==null){
value="0";
}
double i=0;
try {
DecimalFormat digitformat = new DecimalFormat("#.##");
digitformat.setMaximumFractionDigits(digit);
return Double.valueOf(digitformat.format(Double.parseDouble(value)));
} catch (NumberFormatException numberFormatExp) {
return i;
}
}
Set @TableName to the name of your table.
declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'
select @Result = @Result + '
public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
select
replace(col.name, ' ', '_') ColumnName,
column_id ColumnId,
case typ.name
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'bool'
when 'char' then 'string'
when 'date' then 'DateTime'
when 'datetime' then 'DateTime'
when 'datetime2' then 'DateTime'
when 'datetimeoffset' then 'DateTimeOffset'
when 'decimal' then 'decimal'
when 'float' then 'double'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'decimal'
when 'nchar' then 'string'
when 'ntext' then 'string'
when 'numeric' then 'decimal'
when 'nvarchar' then 'string'
when 'real' then 'float'
when 'smalldatetime' then 'DateTime'
when 'smallint' then 'short'
when 'smallmoney' then 'decimal'
when 'text' then 'string'
when 'time' then 'TimeSpan'
when 'timestamp' then 'long'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'Guid'
when 'varbinary' then 'byte[]'
when 'varchar' then 'string'
else 'UNKNOWN_' + typ.name
end ColumnType,
case
when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
then '?'
else ''
end NullableSign
from sys.columns col
join sys.types typ on
col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
where object_id = object_id(@TableName)
) t
order by ColumnId
set @Result = @Result + '
}'
print @Result
As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:
http://zurb.com/ink/inliner.php
This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.
I figured out this try this it worked for me.
In visual studio 2017 community edition it creates a project at this path "C:\Users\mark\source\repos\mipmaps\mipmaps" This will create a access to file is denied issue
Now, you can fix that this way.
close your visual studio process. Then, find your project and copy the project folder But, first make a Sub-folder Named Projects inside of your visual studio 2017 folder in documents. Next, paste the project folder inside of your visual studio 2017 Project folder not the main visual studio 2017 folder it should go into the Sub-folder called Projects. Next, restart Visual studio 2017 Then, choose Open project Solution Then, find your project you pasted in your visual studio 2017 Projects folder Then clean the Project and rebuild it , It, should build and compile just fine. Hope, this Helped out anybody else. Not to sure why Microsoft thought building your projects in a path where it needs write permissions is beyond me.
You can overflow:hidden
to your #content
. Write like this:
#content
{
min-width:700px;
margin-left:10px;
overflow:hidden;
background-color:AppWorkspace;
}
Check this http://jsfiddle.net/Zvt2j/1/
You can use below to find a particular trigger definition.
SHOW TRIGGERS LIKE '%trigger_name%'\G
or the below to show all the triggers in the database. It will work for MySQL 5.0 and above.
SHOW TRIGGERS\G
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
It doesn't apply to this particular code example, but as Google food, since I got the same error message:
<script>document.write('<script src="…"></script>');</script>
will give this error but
<script>document.write('<script src="…"><'+'/script>');</script>
will not.
Further explanation here: Why split the <script> tag when writing it with document.write()?
curl icanhazepoch.com
Basically it's unix timestamps as a service (UTaaS)
You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.
So it could relate to the current directory (get it from Directory.GetCurrentDirectory()
) or to the application executable path (eg. Application.ExecutablePath
comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location
) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath()
with one element of the Environment.SpecialFolder
enumeration).
Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!
In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
I just had same issue when I installed the oracle 11g and then creating the database.
I don't even know that the listener has to create manually. Hence, I open Net Configuration Assistant and manually create the listener.
And I can connect the database that I created locally through sql developer.
If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:
body
of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body
matching the selector specified will retain proper binding.The Code:
// Define the element we wish to bind to.
var bind_to = ':input';
// Prevent double-binding.
$(document.body).off('change', bind_to);
// Bind the event to all body descendants matching the "bind_to" selector.
$(document.body).on('change keyup', bind_to, function(event) {
alert('something happened!');
});
Please notice! I'm making use of $.on()
and $.off()
rather than other methods for several reasons:
$.live()
and $.die()
are deprecated and have been omitted from more recent versions of jQuery.$.change()
and $.keyup()
separately, or pass the same function declaration to each function called; Duplicating logic... Which is absolutely unacceptable.$.bind()
does not dynamically bind to elements as they are created. Therefore if you bind to :input
and then add an input to the DOM, that bind method is not attached to the new input. You'd then need to explicitly un-bind and then re-bind to all elements in the DOM (otherwise you'll end up with binds being duplicated). This process would need to be repeated each time an input was added to the DOM.My routes have a pattern like this:
When i am on Edit page, for example, and i need go back to list page, i will return 2 levels up on the route.
Thinking about that, i created my method with a "level" parameter.
goBack(level: number = 1) {
let commands = '../';
this.router.navigate([commands.repeat(level)], { relativeTo: this.route });
}
So, to go from edit to list i call the method like that:
this.goBack(2);
While JonSkeet's answer explains the difference in a typically excellent way there is another difference: exception handling.
Task.WaitAll
throws an AggregateException
when any of the tasks throws and you can examine all thrown exceptions. The await
in await Task.WhenAll
unwraps the AggregateException
and 'returns' only the first exception.
When the program below executes with await Task.WhenAll(taskArray)
the output is as follows.
19/11/2016 12:18:37 AM: Task 1 started
19/11/2016 12:18:37 AM: Task 3 started
19/11/2016 12:18:37 AM: Task 2 started
Caught Exception in Main at 19/11/2016 12:18:40 AM: Task 1 throwing at 19/11/2016 12:18:38 AM
Done.
When the program below is executed with Task.WaitAll(taskArray)
the output is as follows.
19/11/2016 12:19:29 AM: Task 1 started
19/11/2016 12:19:29 AM: Task 2 started
19/11/2016 12:19:29 AM: Task 3 started
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 1 throwing at 19/11/2016 12:19:30 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 2 throwing at 19/11/2016 12:19:31 AM
Caught AggregateException in Main at 19/11/2016 12:19:32 AM: Task 3 throwing at 19/11/2016 12:19:32 AM
Done.
The program:
class MyAmazingProgram
{
public class CustomException : Exception
{
public CustomException(String message) : base(message)
{ }
}
static void WaitAndThrow(int id, int waitInMs)
{
Console.WriteLine($"{DateTime.UtcNow}: Task {id} started");
Thread.Sleep(waitInMs);
throw new CustomException($"Task {id} throwing at {DateTime.UtcNow}");
}
static void Main(string[] args)
{
Task.Run(async () =>
{
await MyAmazingMethodAsync();
}).Wait();
}
static async Task MyAmazingMethodAsync()
{
try
{
Task[] taskArray = { Task.Factory.StartNew(() => WaitAndThrow(1, 1000)),
Task.Factory.StartNew(() => WaitAndThrow(2, 2000)),
Task.Factory.StartNew(() => WaitAndThrow(3, 3000)) };
Task.WaitAll(taskArray);
//await Task.WhenAll(taskArray);
Console.WriteLine("This isn't going to happen");
}
catch (AggregateException ex)
{
foreach (var inner in ex.InnerExceptions)
{
Console.WriteLine($"Caught AggregateException in Main at {DateTime.UtcNow}: " + inner.Message);
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught Exception in Main at {DateTime.UtcNow}: " + ex.Message);
}
Console.WriteLine("Done.");
Console.ReadLine();
}
}
That's not how to add an item to a string. This:
newinv=inventory+str(add)
Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append()
method.
inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory
Hope this helps!
You can find examples for writing OAuth clients here:
In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails
. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:
@EnableOAuth2Client
@Configuration
class MyConfig{
@Value("${oauth.resource:http://localhost:8082}")
private String baseUrl;
@Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
private String authorizeUrl;
@Value("${oauth.token:http://localhost:8082/oauth/token}")
private String tokenUrl;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource;
resource = new ResourceOwnerPasswordResourceDetails();
List scopes = new ArrayList<String>(2);
scopes.add("write");
scopes.add("read");
resource.setAccessTokenUri(tokenUrl);
resource.setClientId("restapp");
resource.setClientSecret("restapp");
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername("**USERNAME**");
resource.setPassword("**PASSWORD**");
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
Do not forget about @EnableOAuth2Client
on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger
with debug
enabled set.
Good luck
I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .
$(document).ready(function () {
$("#txt1").attr("onfocus", "blur()");
});
$(document).ready(function () {_x000D_
$("#txt1").attr("onfocus", "blur()");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="txt1">
_x000D_
Like this
add the Unix (epoch) datetime to the base date in seconds
this will get it for now (2010-05-25 07:56:23.000)
SELECT dateadd(s,1274756183,'19700101 05:00:00:000')
If you want to go reverse, take a look at this http://wiki.lessthandot.com/index.php/Epoch_Date
Create listener interface.
public interface YourCustomListener
{
public void onCustomClick(View view);
// pass view as argument or whatever you want.
}
And create method setOnCustomClick in another activity(or fragment) , where you want to apply your custom listener......
public void setCustomClickListener(YourCustomListener yourCustomListener)
{
this.yourCustomListener= yourCustomListener;
}
Call this method from your First activity, and pass the listener interface...
Google has introduced new AndroidX dependencies. You need to migrate to AndroidX, it's simple.
I replaced all dependencies to AndroidX dependencies
Old design dependency
implementation 'com.android.support:design:28.0.0'
New AndroidX design dependency
implementation 'com.google.android.material:material:1.0.0-rc01'
you can find AndroidX dependencies here https://developer.android.com/jetpack/androidx/migrate
Automatic AndroidX migration option (supported on android studio 3.3+)
Migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
It's also worth noting that ActiveX controls only work in Windows, whereas Form Controls will work on both Windows and MacOS versions of Excel.
Another alternative is String.format()
. We are using it in jcabi-log (static utility wrapper around slf4j).
Logger.debug(this, "some variable = %s", value);
It's much more maintainable and extendable. Besides, it's easy to translate.
FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here
Do you really need to keep the session (do you have data in it?) or is it enough to fake this by reinstantiating the session when a request comes in? If the first, use the method above. If the second, try something like using the Session_End event handler.
If you have Forms Authentication, then you get something in the Global.asax.cs like
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(formsCookie.Value);
if (ticket.Expired)
{
Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
FormsAuthentication.SignOut();
...
}
else
{ ...
// renew ticket if old
ticket = FormsAuthentication.RenewTicketIfOld(ticket);
...
}
And you set the ticket lifetime much longer than the session lifetime. If you're not authenticating, or using a different authentication method, there are similar tricks. Microsoft TFS web interface and SharePoint seem to use these - the give away is that if you click a link on a stale page, you get authentication prompts in the popup window, but if you just use a command, it works.
Another simple way is to use a tuple:
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10];
// Access elements
console.log("First: " + x["0"] + " Second: " + x["1"]);
Output:
First: hello Second: 10
No, it is like I want to run Form_Load of Form A,if it is possible
-- Varun Mahajan
The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:
Form B:
Sub RunFormALoad()
Forms!FormA.ToDoOnLoad
End Sub
Form A:
Public Sub Form_Load()
ToDoOnLoad
End Sub
Sub ToDoOnLoad()
txtText = "Hi"
End Sub
you can use this code
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
Log.d("message", "" + mainString.substring(startIndex, endIndex));
endString = mainString.substring(startIndex, endIndex);
return endString;
}
in this mainString
is a Super string.like
"I_AmANDROID.Devloper"
and lastString
is a string like"." and startString is like"_".
so this function
returns "AmANDROID".
enjoy your code time.:)
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
You can pass --rcfile
to Bash to cause it to read a file of your choice. This file will be read instead of your .bashrc
. (If that's a problem, source ~/.bashrc
from the other script.)
Edit: So a function to start a new shell with the stuff from ~/.more.sh
would look something like:
more() { bash --rcfile ~/.more.sh ; }
... and in .more.sh
you would have the commands you want to execute when the shell starts. (I suppose it would be elegant to avoid a separate startup file -- you cannot use standard input because then the shell will not be interactive, but you could create a startup file from a here document in a temporary location, then read it.)
DateTime
is not a function, but the class.
When you just reference a class like new DateTime()
PHP searches for the class in your current namespace. However the DateTime
class obviously doesn't exists in your controllers namespace but rather in root namespace.
You can either reference it in the root namespace by prepending a backslash:
$now = new \DateTime();
Or add an import statement at the top:
use DateTime;
$now = new DateTime();
To get the number of votes for a specific item, you would use:
vote_count = Item.objects.filter(votes__contest=contestA).count()
If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:
contest = Contest.objects.get(pk=contest_id)
votes = contest.votes_set.select_related()
vote_counts = {}
for vote in votes:
if not vote_counts.has_key(vote.item.id):
vote_counts[vote.item.id] = {
'item': vote.item,
'count': 0
}
vote_counts[vote.item.id]['count'] += 1
This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.
With Java 7 or newer you can use Files.move(from, to, CopyOption... options)
.
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
os.rename(old, new)
This is found in the Python docs: http://docs.python.org/library/os.html
The problem is in this line:
with pattern.findall(row) as f:
You are using the with
statement. It requires an object with __enter__
and __exit__
methods. But pattern.findall
returns a list
, with
tries to store the __exit__
method, but it can't find it, and raises an error. Just use
f = pattern.findall(row)
instead.
Though this question has been answered many times before, I thought I would add to it with a more complete and solid answer for future users. The main answer does solve the problem, but I believe it may be better to know/understand the some of various ways to show/hide things.
.
This is the way I used to do it until I found some of these other ways.
Javascript:
$("#element_to_hide").css("display", "none"); // To hide
$("#element_to_hide").css("display", ""); // To unhide
Pros:
Cons:
$("#element_to_hid").css("display", "inline");
otherwise it will default back to "block" or whatever else that it will be forced into.Example: https://jsfiddle.net/4chd6e5r/1/
.
While setting up the example for this one, I actually ran into some flaws on this method that make it very very unreliable.
Css/Javascript:
.hidden {display:none}
$("#element_to_hide").addClass("hidden"); // To hide
$("#element_to_hide").removeClass("hidden"); // To unhide
Pros:
$(".hidden")
.Cons:
Example: https://jsfiddle.net/476oha8t/8/
.
Javascript:
$("element_to_hide").toggle(); // To hide and to unhide
Pros:
Cons:
Example: https://jsfiddle.net/cxcawkyk/1/
.
Javascript:
$("#element_to_hide").hide(); // To hide
$("#element_to_hide").show(); // To show
Pros:
Cons:
Example: https://jsfiddle.net/k0ukhmfL/
.
Overall, I would say the best to be hide()/show() unless you specifically need it to be a toggle. I hope you found this information to be helpful.
An easy way to print the sorted contents of the dictionary, in Python 3:
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
... print("{} : {}".format(key, value))
...
a : 3
b : 2
c : 1
The expression dict_example.items()
returns tuples, which can then be sorted by sorted()
:
>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]
Below is an example to pretty print the sorted contents of a Python dictionary's values.
for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]):
print("{} : {}".format(key, value))
Big-O is to little-o as =
is to <
. Big-O is an inclusive upper bound, while little-o is a strict upper bound.
For example, the function f(n) = 3n
is:
O(n²)
, o(n²)
, and O(n)
O(lg n)
, o(lg n)
, or o(n)
Analogously, the number 1
is:
= 2
, < 2
, and = 1
= 0
, < 0
, or < 1
Here's a table, showing the general idea:
(Note: the table is a good guide but its limit definition should be in terms of the superior limit instead of the normal limit. For example, 3 + (n mod 2)
oscillates between 3 and 4 forever. It's in O(1)
despite not having a normal limit, because it still has a lim sup
: 4.)
I recommend memorizing how the Big-O notation converts to asymptotic comparisons. The comparisons are easier to remember, but less flexible because you can't say things like nO(1) = P.
If we have parameter like below in our POM XML
<version>${project.version}.${svn.version}</version>
<packaging>war</packaging>
I run maven command line as follows :
mvn clean install package -Dproject.version=10 -Dsvn.version=1
Yes, there is a threading pool similar to the multiprocessing Pool, however, it is hidden somewhat and not properly documented. You can import it by following way:-
from multiprocessing.pool import ThreadPool
Just I show you simple example
def test_multithread_stringio_read_csv(self):
# see gh-11786
max_row_range = 10000
num_files = 100
bytes_to_df = [
'\n'.join(
['%d,%d,%d' % (i, i, i) for i in range(max_row_range)]
).encode() for j in range(num_files)]
files = [BytesIO(b) for b in bytes_to_df]
# read all files in many threads
pool = ThreadPool(8)
results = pool.map(self.read_csv, files)
first_result = results[0]
for result in results:
tm.assert_frame_equal(first_result, result)
Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.
These two toturial will help to implement the trigger.
I had the same problem, even the gradle build ran for 8 hours and i was worried. But later on i changed the compile sdk version and minimum sdk version in build.gradle file like this.
Older:
android {
compileSdkVersion 25
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.uwebtechnology.salahadmin"
minSdkVersion 9
targetSdkVersion 25
}
New (Updated):
android
{
compileSdkVersion 28
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.uwebtechnology.salahadmin"
minSdkVersion 15
targetSdkVersion 28
}