The Accepted Answer is not working for me, This is what works for me
WebSettings webSetting = webView.getSettings();
webSetting.setBuiltInZoomControls(true);
webView1.setWebViewClient(new WebViewClient());
webView.loadUrl("file:///android_asset/index.html");
You can try this:
db.Account.find().sort("UserName")
db.Account.find().sort("UserName",pymongo.ASCENDING)
db.Account.find().sort("UserName",pymongo.DESCENDING)
As Wagner Francisco said, (in JADE)
input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`
And in your controller :
$scope.someScopeVariable = 'somevalue'
You can do objects the JavaScript way... It makes no sense but it works ;)
>>> def FakeObject():
... def test():
... print "foo"
... FakeObject.test = test
... return FakeObject
>>> x = FakeObject()
>>> x.test()
foo
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
...
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters «
and »
just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
var i = 1, p = document.getElementById("form_part"+1);_x000D_
while (p !== null){_x000D_
if (i === n){_x000D_
p.style.display = "";_x000D_
}_x000D_
else{_x000D_
p.style.display = "none";_x000D_
}_x000D_
i++;_x000D_
p = document.getElementById("form_part"+i);_x000D_
}_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
var sum =_x000D_
parseInt(document.getElementById("num1").value) +_x000D_
parseInt(document.getElementById("num2").value) +_x000D_
parseInt(document.getElementById("num3").value);_x000D_
_x000D_
alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
Part 1<br>_x000D_
<input type="number" value="1" id="num1"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
Part 2<br>_x000D_
<input type="number" value="2" id="num2"><br>_x000D_
<button type="button" onclick="shows_form_part(1)">«</button>_x000D_
<button type="button" onclick="shows_form_part(3)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
Part 3<br>_x000D_
<input type="number" value="3" id="num3"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">«</button>_x000D_
<button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
You could also use Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/
Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:
$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>
I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone
I needed, but push
. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push
command worked exactly the same as the clone
above, and the remote did not change:
$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>
(@YMHuang put me on the right track with the documentation link.)
You need a /g
on there, like this:
var textTitle = "this is a test";_x000D_
var result = textTitle.replace(/ /g, '%20');_x000D_
_x000D_
console.log(result);
_x000D_
You can play with it here, the default .replace()
behavior is to replace only the first match, the /g
modifier (global) tells it to replace all occurrences.
You can Kill a specific instance of MS Word.
foreach (var process in Process.GetProcessesByName("WINWORD"))
{
// Temp is a document which you need to kill.
if (process.MainWindowTitle.Contains("Temp"))
process.Kill();
}
You should use the notification to solve this problem,because the other method will listen to the input box not the actually input,especially when you use the Chinese input method. In viewDidload
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
name:@"UITextFieldTextDidChangeNotification"
object:youTarget];
then
- (void)textFiledEditChanged:(NSNotification *)obj {
UITextField *textField = (UITextField *)obj.object;
NSString *toBestring = textField.text;
NSArray *currentar = [UITextInputMode activeInputModes];
UITextInputMode *currentMode = [currentar firstObject];
if ([currentMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position) {
if (toBestring.length > kMaxLength)
textField.text = toBestring;
}
}
finally,you run,will done.
recreate()
(as mentioned by TPReal) will only restart current activity, but the previous activities will still be in back stack and theme will not be applied to them.
So, another solution for this problem is to recreate the task stack completely, like this:
TaskStackBuilder.create(getActivity())
.addNextIntent(new Intent(getActivity(), MainActivity.class))
.addNextIntent(getActivity().getIntent())
.startActivities();
EDIT:
Just put the code above after you perform changing of theme on the UI or somewhere else. All your activities should have method setTheme()
called before onCreate()
, probably in some parent activity. It is also a normal approach to store the theme chosen in SharedPreferences
, read it and then set using setTheme()
method.
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
_x000D_
If you want to download binary data look here
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
Pure Python2 w/o dep:
def relpath(cwd, path):
"""Create a relative path for path from cwd, if possible"""
if sys.platform == "win32":
cwd = cwd.lower()
path = path.lower()
_cwd = os.path.abspath(cwd).split(os.path.sep)
_path = os.path.abspath(path).split(os.path.sep)
eq_until_pos = None
for i in xrange(min(len(_cwd), len(_path))):
if _cwd[i] == _path[i]:
eq_until_pos = i
else:
break
if eq_until_pos is None:
return path
newpath = [".." for i in xrange(len(_cwd[eq_until_pos+1:]))]
newpath.extend(_path[eq_until_pos+1:])
return os.path.join(*newpath) if newpath else "."
get
returns Collection
and is rather supposed to fetch multiple rows.
count
is a generic way of checking the result:
$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user
// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException
// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users
Use &
symbol in windows to use command in one line
C:\Users\Arshdeep Singh>cd Desktop\PROJECTS\PYTHON\programiz & jupyter notebook
like in linux we use,
touch thisfile ; ls -lstrh
On Visual Studio 2013 RC2, there is a template for this. Just add it to App_Start folder.
The template produces such a class:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApiOsp.App_Start.Startup))]
namespace WebApiOsp.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
}
}
}
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);
I have seen that the new versions when you define the resulting entities better define them in the following way if you handle a different scheme, I had a similar problem
You must add System.ComponentModel.DataAnnotations.Schema
using System.ComponentModel.DataAnnotations.Schema;
[Table("InstitucionesMilitares", Schema = "configuracion")]
I have done for
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
How to call method:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
Hope this would help you.
Any simple constraint should do the job, if an exception is acceptable. Examples :
Sorry is this seems deceptively simple. I know it looks bad confronted to the link you share with us. ;-(
But I neverleless give this answer, because it seem to fill your need. (If not, it may trigger your updating your requirements, which would be "a Good Thing"(TM) also).
Edited: If an insert would break the database unique constraint, an exception is throw at the database level, relayed by the driver. It will certainly stop your script, with a failure. It must be possible in PHP to adress that case ...
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
I specifically got the "[module_name]:prepareDebugUnitTestDependencies" task not found
error, every time I ran gradle build. This happened to me after updating my Android Studio to 3.0.0.
I had previously added command-line options to the gradle-based compiler, which you can find under: File -> Settings -> Build, Execution, Deployment -> Compiler -> Command-line Options. Specifically, I had excluded a number of tasks, including the aforementioned task. While that worked fine on the previous stable version (2.3 at that time), it seems like this was the reason behind the build failure.
This is one of many possible solutions. Make sure you have the correct command-line options specified in the settings under: File -> Settings -> Build, Execution, Deployment -> Compiler -> Command-line Options, and that none of them is causing this problem.
In my case, I removed the exclusion of this task (and other tasks that seemed related), left the unrelated tasks excluded, and it worked!
The answer by Jones Agyemang is probably sufficient for most use cases and was a great starting point for my solution. For scripting in Git Bent, the git wrapper library I made, I needed something a bit more robust. I'm posting the prototype I've written which is not yet totally script-friendly
<<<<<<< HEAD
which doesn't work for merge conflicts from using git stash apply
which has <<<<<<< Updated Upstream
=======
& >>>>>>>
You need the str_split_line
function from below.
# Root git directory
dir="$(git rev-parse --show-toplevel)"
# Put the grep output into an array (see below)
str_split_line "$(grep -r "^<<<<<<< " "${dir})" files
bn="$(basename "${dir}")"
for i in "${files[@]}"; do
# Remove the matched string, so we're left with the file name
file="$(sed -e "s/:<<<<<<< .*//" <<< "${i}")"
# Remove the path, keep the project dir's name
fileShort="${file#"${dir}"}"
fileShort="${bn}${fileShort}"
# Confirm merge divider & closer are present
c1=$(grep -c "^=======" "${file}")
c2=$(grep -c "^>>>>>>> " "${file}")
if [[ c1 -gt 0 && c2 -gt 0 ]]; then
echo "${fileShort} has a merge conflict"
fi
done
projectdir/file-name
projectdir/subdir/file-name
You can just copy the block of code if you don't want this as a separate function
function str_split_line(){
# for IFS, see https://stackoverflow.com/questions/16831429/when-setting-ifs-to-split-on-newlines-why-is-it-necessary-to-include-a-backspac
IFS="
"
declare -n lines=$2
while read line; do
lines+=("${line}")
done <<< "${1}"
}
The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.
You can enable whitespace trimming at file save time from settings:
"files.trimTrailingWhitespace": true
setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).
In summary:
If you want to develop in java, you need the JDK, but if you just want run java, you need the JRE.
Instead of:
var host = req.get('host');
var origin = req.get('origin');
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
DROP EVENT IF EXISTS xxxEVENTxxx;
CREATE EVENT xxxEVENTxxx
ON SCHEDULE
EVERY 1 DAY
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
DO
--process;
¡IMPORTANT!->
SET GLOBAL event_scheduler = ON;
fileinput
seems to be for multiple input streams. This is what I would do:
with open("test.txt") as file:
for line in file:
line = line.rstrip()
if line:
print(line)
Best Solution
The only difference is
1.Mutex -> lock and unlock are under the ownership of a thread that locks the mutex.
2.Semaphore -> No ownership i.e; if one thread calls semwait(s) any other thread can call sempost(s) to remove the lock.
for me it is daterangepicker worked by this :
$('#host1field').daterangepicker({
locale: {
format: 'DD/MM/YYYY'
}
});
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`)
line.ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
For my case, the issue was with using Lombok's experimental feature @UtilityClass in my java project in Intellij Idea, to annotate a class methods as "static". When I explicitly made each method of the class as "static" instead of using the annotation, all the compilation issues disappeared.
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
You can also use weightSum
and layout_weight
property to adjust your different screen.
For that, you have to make android:layout_width
= 0dp,
and android:layout_width
= (whatever you want);
Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".
As mentioned above by others,
Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.
So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.
Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role
Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.
Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.
Scrum Master:- There are 6 types of meetings in scrum:
Let me know if any one need more inputs on this.
You call super()
to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super()
or super(param,param)
oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.
HTTPS (HTTP over SSL) sends all HTTP content over a SSL tunel, so HTTP content and headers are encrypted as well.
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
I found this nice summary of which annotations are picked up by which declarations. By studying it you will find that <context:component-scan/>
recognizes a superset of annotations recognized by <context:annotation-config/>
, namely:
@Component
, @Service
, @Repository
, @Controller
, @Endpoint
@Configuration
, @Bean
, @Lazy
, @Scope
, @Order
, @Primary
, @Profile
, @DependsOn
, @Import
, @ImportResource
As you can see <context:component-scan/>
logically extends <context:annotation-config/>
with CLASSPATH component scanning and Java @Configuration features.
Do
setTimeout(
function() {
this.setState({ position: 1 });
}
.bind(this),
3000
);
Otherwise, you are passing the result of setState
to setTimeout
.
You can also use ES6 arrow functions to avoid the use of this
keyword:
setTimeout(
() => this.setState({ position: 1 }),
3000
);
Use Integer.compare(int, int)
. And don'try to micro-optimize your code unless you can prove that you have a performance issue.
PS: Take backup of your code in case it changes App.js
This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically
select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'
exec (@sql)
of course #tables is a dynamic table in the stored procedure
I know this message is old and was a long time ago - but i also had problem with with the exact same error:
the problem I had was relates to the fact the encrypted text was converted to String and to byte[]
when trying to DECRYPT it.
private Key getAesKey() throws Exception {
return new SecretKeySpec(Arrays.copyOf(key.getBytes("UTF-8"), 16), "AES");
}
private Cipher getMutual() throws Exception {
Cipher cipher = Cipher.getInstance("AES");
return cipher;// cipher.doFinal(pass.getBytes());
}
public byte[] getEncryptedPass(String pass) throws Exception {
Cipher cipher = getMutual();
cipher.init(Cipher.ENCRYPT_MODE, getAesKey());
byte[] encrypted = cipher.doFinal(pass.getBytes("UTF-8"));
return encrypted;
}
public String getDecryptedPass(byte[] encrypted) throws Exception {
Cipher cipher = getMutual();
cipher.init(Cipher.DECRYPT_MODE, getAesKey());
String realPass = new String(cipher.doFinal(encrypted));
return realPass;
}
Combining the answers of kiamlaluno and Mark, along with formatOnSave to autointent code for Python:
{
"editor.formatOnSave": true,
"editor.autoIndent": "advanced",
"editor.detectIndentation": true,
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"editor.formatOnPaste": true,
"editor.multiCursorModifier": "ctrlCmd",
"editor.snippetSuggestions": "top",
"editor.rulers": [
{
"column": 79,
"color": "#424142"
},
100, // <- a ruler in the default color or as customized at column 0
{
"column": 120,
"color": "#ff0000"
},
],
}
document.getElementById('username').value="moo"
document.forms[0].submit()
HashMap is an implementation of Map so it's quite the same but has "clone()" method as i see in reference guide))
mongo => mongo-db console
mongodb => mongo-db server
If you're on Mac and looking for a easier way to start/stop your mongo-db server, then MongoDB Preference Pane is something that you should look into. With it, you start/stop your mongo-db instance via UI. Hope it helps!
Use the affix
component included with Bootstrap. Start with a 'navbar-static-top' and this will change it to fixed
when the height of your header (content above the navbar) is reached...
$('#nav').affix({
offset: {
top: $('header').height()
}
});
Was looking for same. Well, not exactly. I only wanted to list all DOM Nodes.
var currentNode,
ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
To get elements with a specific class, we can use filter function.
var currentNode,
ni = document.createNodeIterator(
document.documentElement,
NodeFilter.SHOW_ELEMENT,
function(node){
return node.classList.contains('toggleable') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
Found solution on MDN
It is important to define an id in the model
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model => model.Id(p => p.id))
)
I had the same problem and nothing mentioned here worked for me. Here is what worked for me:
main.js
file that is run by electron. (this seemed to be the first important part for me)npm i -D electron-rebuild
to add the electron-rebuild packagenode-modules
folder, as well as the packages-lock.json
file.npm i
to install all modules../node_modules/.bin/electron-rebuild
(.\node_modules\.bin\electron-rebuild.cmd
for Windows) to rebuild everythingIt is very important to run ./node_modules/.bin/electron-rebuild
directly after npm i
otherwise it did not work on my mac.
I hope I could help some frustrated souls.
If you simply place text as a child(ren) of a column, this is the easiest way to have text automatically wrap. Assuming you don't have anything more complicated going on. In those cases, I would think you would create your container sized as you see fit and put another column inside and then your text. This seems to work nicely. Containers want to shrink to the size of its contents, and this seems to naturally conflict with wrapping, which requires more effort.
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('This long text will wrap very nicely if there isn't room beyond the column\'s total width and if you have enough vertical space available to wrap into.',
style: TextStyle(fontSize: 16, color: primaryColor),
textAlign: TextAlign.center,),
],
),
String s1=""; // empty string assigned to s1 , s1 has length 0, it holds a value of no length string
String s2=null; // absolutely nothing, it holds no value, you are not assigning any value to s2
so null is not the same as empty.
hope that helps!!!
function phpconsole($label='var', $x) {
?>
<script type="text/javascript">
console.log('<?php echo ($label)?>');
console.log('<?php echo json_encode($x)?>');
</script>
<?php
}
Using the accepted answer to create an alias
oops = "!f(){ \
git add -A; \
if [ \"$1\" == '' ]; then \
git commit --amend --no-edit; \
else \
git commit --amend \"$@\"; \
fi;\
}; f"
then you can do
git oops
and it will add everything, and amend using the same message
or
git oops -m "new message"
to amend replacing the message
You may also have a look on Runtyper - a tool that performs type checking of operands in ===
(and other operations).
For your example, if you have strict comparison x === y
and x = 123, y = "123"
, it will automatically check typeof x, typeof y
and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
Use git stash push
, like this:
git stash push [--] [<pathspec>...]
For example:
git stash push -- my/file.sh
This is available since Git 2.13, released in spring 2017.
Just a tip!--make sure you up the z-index on the element you want to be over the embedded video. I added the wmode querystring, and it still didn't work...until I upped the z-index of the other element. :)
I made this code snippet to reflectively instantiate a class which is passed for a simple automated test utility.
Object attributeValue = null;
try {
if(clazz.isArray()){
Class<?> arrayType = clazz.getComponentType();
attributeValue = Array.newInstance(arrayType, 0);
}
else if(!clazz.isInterface()){
attributeValue = BeanUtils.instantiateClass(clazz);
}
} catch (Exception e) {
logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}
Note this segment:
if(clazz.isArray()){
Class<?> arrayType = clazz.getComponentType();
attributeValue = Array.newInstance(arrayType, 0);
}
for array initiating where Array.newInstance(class of array, size of array). Class can be both primitive (int.class) and object (Integer.class).
BeanUtils is part of Spring.
When you typed in sudo sendmailconfig
, you should have been prompted to configure sendmail.
For reference, the files that are updated during configuration are located at the following (in case you want to update them manually):
/etc/mail/sendmail.conf
/etc/cron.d/sendmail
/etc/mail/sendmail.mc
You can test sendmail to see if it is properly configured and setup by typing the following into the command line:
$ echo "My test email being sent from sendmail" | /usr/sbin/sendmail [email protected]
The following will allow you to add smtp relay to sendmail:
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
Add the following lines to sendmail.mc, but before the MAILERDEFINITIONS
. Make sure you update your smtp server.
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash -o /etc/mail/auth/client-info.db')dnl
Invoke creation sendmail.cf (alternatively run make -C /etc/mail
):
m4 sendmail.mc > sendmail.cf
Restart the sendmail daemon:
service sendmail restart
you can use the views *_DEPENDENCIES
, for example:
SELECT owner, NAME
FROM dba_dependencies
WHERE referenced_owner = :table_owner
AND referenced_name = :table_name
AND TYPE IN ('PACKAGE', 'PACKAGE BODY')
Robust C89 strtol
-based solution
With:
atoi
family)strtol
(e.g. no leading whitespace nor trailing trash chars)#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum {
STR2INT_SUCCESS,
STR2INT_OVERFLOW,
STR2INT_UNDERFLOW,
STR2INT_INCONVERTIBLE
} str2int_errno;
/* Convert string s to int out.
*
* @param[out] out The converted int. Cannot be NULL.
*
* @param[in] s Input string to be converted.
*
* The format is the same as strtol,
* except that the following are inconvertible:
*
* - empty string
* - leading whitespace
* - any trailing characters that are not part of the number
*
* Cannot be NULL.
*
* @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
*
* @return Indicates if the operation succeeded, or why it failed.
*/
str2int_errno str2int(int *out, char *s, int base) {
char *end;
if (s[0] == '\0' || isspace(s[0]))
return STR2INT_INCONVERTIBLE;
errno = 0;
long l = strtol(s, &end, base);
/* Both checks are needed because INT_MAX == LONG_MAX is possible. */
if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
return STR2INT_OVERFLOW;
if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
return STR2INT_UNDERFLOW;
if (*end != '\0')
return STR2INT_INCONVERTIBLE;
*out = l;
return STR2INT_SUCCESS;
}
int main(void) {
int i;
/* Lazy to calculate this size properly. */
char s[256];
/* Simple case. */
assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
assert(i == 11);
/* Negative number . */
assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
assert(i == -11);
/* Different base. */
assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
assert(i == 17);
/* 0 */
assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
assert(i == 0);
/* INT_MAX. */
sprintf(s, "%d", INT_MAX);
assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
assert(i == INT_MAX);
/* INT_MIN. */
sprintf(s, "%d", INT_MIN);
assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
assert(i == INT_MIN);
/* Leading and trailing space. */
assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);
/* Trash characters. */
assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);
/* int overflow.
*
* `if` needed to avoid undefined behaviour
* on `INT_MAX + 1` if INT_MAX == LONG_MAX.
*/
if (INT_MAX < LONG_MAX) {
sprintf(s, "%ld", (long int)INT_MAX + 1L);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
}
/* int underflow */
if (LONG_MIN < INT_MIN) {
sprintf(s, "%ld", (long int)INT_MIN - 1L);
assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
}
/* long overflow */
sprintf(s, "%ld0", LONG_MAX);
assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
/* long underflow */
sprintf(s, "%ld0", LONG_MIN);
assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
return EXIT_SUCCESS;
}
Use DataFrameWriter.saveAsTable
. (df.write.saveAsTable(...)
) See Spark SQL and DataFrame Guide.
In my case changing firebase library version from 2.6.0 to 2.4.2 fixed the issue
Ok, since my attempt to post my solution in a comment failed, here's what I was trying to say. I could do exactly what I wanted from native Python (on Windows, not anywhere else though) with the following code:
import msvcrt
def kbfunc():
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
else:
ret = 0
return ret
You can as well do:
git checkout --theirs /path/to/file
to keep the remote file, and:
git checkout --ours /path/to/file
to keep local file.
Then git add
them and everything is done.
Edition:
Keep in mind that this is for a merge
scenario. During a rebase
--theirs
refers to the branch where you've been working.
You want to use the built-in browser HTML strip for that instead of applying yourself a regexp. It is more secure since the ever green browser does the work for you.
angular.module('myApp.filters', []).
filter('htmlToPlaintext', function() {
return function(text) {
return stripHtml(text);
};
}
);
var stripHtml = (function () {
var tmpEl = $document[0].createElement("DIV");
function strip(html) {
if (!html) {
return "";
}
tmpEl.innerHTML = html;
return tmpEl.textContent || tmpEl.innerText || "";
}
return strip;
}());
The reason for wrapping it in an self-executing function is for reusing the element creation.
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
It seems you want to save your class instances across sessions, and using pickle
is a decent way to do this. However, there's a package called klepto
that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto
is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.
Note that It works for dynamically added class attributes, which pickle cannot do...
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>>
>>> db['banana'] = banana
>>> db.dump()
>>>
Then we restart…
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>>
>>> db['banana'].color
'yellow'
>>>
Klepto
works on python2 and python3.
Get the code here: https://github.com/uqfoundation
First of all, there are still browsers out there that don't support those pseudo-elements (ie. :first-child, :last-child), so you have to 'deal' with this issue.
There is a good example how to make that work without using pseudo-elements:
-- see the divider pipe example.
I hope that was useful.
Let's say I have a (fake) directory structure like:
.../root/
/app
bootstrap.php
/scripts
something/
somescript.php
/public
index.php
Now assume that bootstrap.php
has some code included for setting up database connections or some other kind of boostrapping stuff.
Assume you want to include a file in boostrap.php
's folder called init.php
. Now, to avoid scanning the entire include path with include 'init.php'
, you could use include './init.php'
.
There's a problem though. That ./
will be relative to the script that included bootstrap.php
, not bootstrap.php
. (Technically speaking, it will be relative to the working directory.)
dirname(__FILE__)
allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php
resides.
(Note: since PHP 5.3, you can use __DIR__
in place of dirname(__FILE__)
.)
Now, why not just use include 'init.php';
?
As odd as it is at first though, .
is not guaranteed to be in the include path. Sometimes to avoid useless stat()
's people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).
Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?
Disabling tracking will also cause your result sets to be streamed into memory. This is more efficient when you're working with large sets of data and don't need the entire set of data all at once.
References:
Unless there is a single row in the ASSIGNMENT
table and ASSIGNMENT_20081120
is a local PL/SQL variable of type ASSIGNMENT%ROWTYPE
, this is not what you want.
Assuming you are trying to create a new table and copy the existing data to that new table
CREATE TABLE assignment_20081120
AS
SELECT *
FROM assignment
This is a possible implementation of the required Bash function:
# Print the newest file, if any, matching the given pattern
# Example usage:
# newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
# Use ${1-} instead of $1 in case 'nounset' is set
local -r glob_pattern=${1-}
if (( $# != 1 )) ; then
echo 'usage: newest_matching_file GLOB_PATTERN' >&2
return 1
fi
# To avoid printing garbage if no files match the pattern, set
# 'nullglob' if necessary
local -i need_to_unset_nullglob=0
if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
shopt -s nullglob
need_to_unset_nullglob=1
fi
newest_file=
for file in $glob_pattern ; do
[[ -z $newest_file || $file -nt $newest_file ]] \
&& newest_file=$file
done
# To avoid unexpected behaviour elsewhere, unset nullglob if it was
# set by this function
(( need_to_unset_nullglob )) && shopt -u nullglob
# Use printf instead of echo in case the file name begins with '-'
[[ -n $newest_file ]] && printf '%s\n' "$newest_file"
return 0
}
It uses only Bash builtins, and should handle files whose names contain newlines or other unusual characters.
In most browsers, you can use a javascript variable instead of using document.getElementById
. Say your html body content is like this:
<section id="mySection"> Hello </section>
Then you can just refer to mySection
as a variable in javascript:
mySection.innerText += ', world'
// same as: document.getElementById('mySection').innerText += ', world'
See this snippet:
mySection.innerText += ', world!'
_x000D_
<section id="mySection"> Hello </section>
_x000D_
If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:
Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")
https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes
Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:
https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/
Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.
NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.
In Class1:
Class2 inst = new Class2();
inst.UpdateEmployee();
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
There's another reason that this can be thrown, even if you're not using dynamic/ExpandoObject. If you are doing a loop, like this:
@foreach (var folder in ViewBag.RootFolder.ChildFolders.ToList())
{
@Html.Partial("ContentFolderTreeViewItems", folder)
}
In that case, the "var" instead of the type declaration will throw the same error, despite the fact that RootFolder is of type "Folder. By changing the var to the actual type, the problem goes away.
@foreach (ContentFolder folder in ViewBag.RootFolder.ChildFolders.ToList())
{
@Html.Partial("ContentFolderTreeViewItems", folder)
}
You should use setTimestamp instead, if you hardcode it:
$start_date = new DateTime();
$start_date->setTimestamp(1372622987);
in your case
$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);
I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
In the real world, scenario its not about calling a simple function but a function with a proper value. So let's dive in. This is the scenario A user has a requirement to fire an event from his own component and also at the end he wants to call a function of another component as well. Let's say the service file is the same for both the components
componentOne.html
<button (click)="savePreviousWorkDetail()" data-dismiss="modal" class="btn submit-but" type="button">
Submit
</button>
When the user clicks on the submit button he needs to call savePreviousWorkDetail() in its own component componentOne.ts and in the end he needs to call a function of another component as well. So to do that a function in a service class can be called from componentOne.ts and when that called, the function from componentTwo will be fired.
componentOne.ts
constructor(private httpservice: CommonServiceClass) {
}
savePreviousWorkDetail() {
// Things to be Executed in this function
this.httpservice.callMyMethod("Niroshan");
}
commontServiceClass.ts
import {Injectable,EventEmitter} from '@angular/core';
@Injectable()
export class CommonServiceClass{
invokeMyMethod = new EventEmitter();
constructor(private http: HttpClient) {
}
callMyMethod(params: any = 'Niroshan') {
this.invokeMyMethod.emit(params);
}
}
And Below is the componentTwo which has the function that needed to be called from componentOne. And in ngOnInit() we have to subscribe for the invoked method so when it triggers methodToBeCalled() will be called
componentTwo.ts
import {Observable,Subscription} from 'rxjs';
export class ComponentTwo implements OnInit {
constructor(private httpservice: CommonServiceClass) {
}
myMethodSubs: Subscription;
ngOnInit() {
this.myMethodSubs = this.httpservice.invokeMyMethod.subscribe(res => {
console.log(res);
this.methodToBeCalled();
});
methodToBeCalled(){
//what needs to done
}
}
}
You don't want to do this. It is invalid HTML to have more than one element with the same id
. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.
You should be using a class, or just iterating through the inputs and keeping track of an index.
Try something like this:
var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
if(div2.childNodes[i].nodeName == 'INPUT'){
j++;
var input = div2.childNodes[i];
alert('This is edit'+j+': '+input);
}
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
Generally the cast operator is preferred to the Class#cast method as it's more concise and can be analyzed by the compiler to spit out blatant issues with the code.
Class#cast takes responsibility for type checking at run-time rather than during compilation.
There are certainly use-cases for Class#cast, particularly when it comes to reflective operations.
Since lambda's came to java I personally like using Class#cast with the collections/stream API if I'm working with abstract types, for example.
Dog findMyDog(String name, Breed breed) {
return lostAnimals.stream()
.filter(Dog.class::isInstance)
.map(Dog.class::cast)
.filter(dog -> dog.getName().equalsIgnoreCase(name))
.filter(dog -> dog.getBreed() == breed)
.findFirst()
.orElse(null);
}
You can write complete apps for almost any smartphone platform (Android, iOS,...) using Phonegap. (http://www.phonegap.com)
It is an open source framework that exposes native capabilities to a web view, so that you can do anything a native app can do.
This is very suitable for cross platform development if you're not building something that has to be pixel perfect in every way, or is very hardware intensive.
If you are looking for UI Frameworks that can be used to build such apps, there is a wide range of different libraries. (Like Sencha, jQuery mobile, ...)
And to be a little biased, there is something I built as well: http://www.m-gwt.com
Borrowing directly from Gordon's very comprehensive answer, I note that your question mentions being page-specific in forcing HTTPS/SSL connections.
function forceHTTPS(){
$httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if( count( $_POST )>0 )
die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
if( !headers_sent() ){
header( "Status: 301 Moved Permanently" );
header( "Location: $httpsURL" );
exit();
}else{
die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
}
}
}
Then, as close to the top of these pages which you want to force to connect via PHP, you can require()
a centralised file containing this (and any other) custom functions, and then simply run the forceHTTPS()
function.
I have not implemented this kind of solution personally (I have tended to use the PHP solution, like the one above, for it's simplicity), but the following may be, at least, a good start.
RewriteEngine on
# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$
# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)
Checking for __iter__
works on sequence types, but it would fail on e.g. strings in Python 2. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too):
from __future__ import print_function
try:
some_object_iterator = iter(some_object)
except TypeError as te:
print(some_object, 'is not iterable')
The iter
built-in checks for the __iter__
method or in the case of strings the __getitem__
method.
Another general pythonic approach is to assume an iterable, then fail gracefully if it does not work on the given object. The Python glossary:
Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.
...
try: _ = (e for e in my_object) except TypeError: print my_object, 'is not iterable'
The collections
module provides some abstract base classes, which allow to ask classes or instances if they provide particular functionality, for example:
from collections.abc import Iterable
if isinstance(e, Iterable):
# e is iterable
However, this does not check for classes that are iterable through __getitem__
.
This would be the correct implementation, although I don't see anything you need to dispose in the code you posted. You only need to implement IDisposable
when:
Nothing in the code you posted needs to be disposed.
public class User : IDisposable
{
public int id { get; protected set; }
public string name { get; protected set; }
public string pass { get; protected set; }
public User(int userID)
{
id = userID;
}
public User(string Username, string Password)
{
name = Username;
pass = Password;
}
// Other functions go here...
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
}
// free native resources if there are any.
}
}
You'll need to install numpy, scipy and matplotlib to get pylab. In ubuntu you can install them with this command:
sudo apt-get install python-numpy python-scipy python-matplotlib
If you installed python from source you will need to install these packages through pip. Note that you may have to install other dependencies to do this, as well as install numpy before the other two.
That said, I would recommend using the version of python in the repositories as I think it is up to date with the current version of python (2.7.3).
private static final DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
private static Date NOW = new Date();
static {
try {
NOW = df1.parse(df1.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
}
I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.
In this code we add multiple styles in an element:
let_x000D_
element = document.querySelector('span')_x000D_
, cssStyle = (el, styles) => {_x000D_
for (var property in styles) {_x000D_
el.style[property] = styles[property];_x000D_
}_x000D_
}_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
I used this not elegant but FAST,EASY and WORKING system. I do not see why can not work because the only way for the system to allow create a big size array and access parts is without cutting it in parts:
#define DIM 3
#define WORMS 50000 //gusanos
void halla_centros_V000(double CENW[][DIM])
{
CENW[i][j]=...
...
}
int main()
{
double *CENW_MEM=new double[WORMS*DIM];
double (*CENW)[DIM];
CENW=(double (*)[3]) &CENW_MEM[0];
halla_centros_V000(CENW);
delete[] CENW_MEM;
}
Have <option value="">- Please select a name -</option>
as the first option and use JavaScript (and backend validation) to ensure the user has selected something other than an empty value.
I think init_js should use declare instead of local!
function scan3() {
declare -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
In addition to @Elltz answer, we can use both fill and image for background:
someNode.setBackground(
new Background(
Collections.singletonList(new BackgroundFill(
Color.WHITE,
new CornerRadii(500),
new Insets(10))),
Collections.singletonList(new BackgroundImage(
new Image("image/logo.png", 100, 100, false, true),
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.CENTER,
BackgroundSize.DEFAULT))));
Use
setBackground(
new Background(
Collections.singletonList(new BackgroundFill(
Color.WHITE,
new CornerRadii(0),
new Insets(0))),
Collections.singletonList(new BackgroundImage(
new Image("file:clouds.jpg", 100, 100, false, true),
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
new BackgroundSize(1.0, 1.0, true, true, false, false)
))));
(different last argument) to make the image full-window size.
public LatLang getLatLangFromAddress(String strAddress){
Geocoder coder = new Geocoder(this, Locale.getDefault());
List<Address> address;
try {
address = coder.getFromLocationName(strAddress,5);
if (address == null) {
return new LatLang(-10000, -10000);
}
Address location = address.get(0);
return new LatLang(location.getLatitude(), location.getLongitude());
} catch (IOException e) {
return new LatLang(-10000, -10000);
}
}
LatLang
is a pojo class in this case.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
permission is not required.
Try this in your constructor
MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);
For any reason in Firefox even though I have return false;
and myform.preventDefault();
in the function, it refreshes the page after function runs. And I don't know if this is a good practice, but it works for me, I insert javascript:this.preventDefault();
in the action attribute .
As I said, I tried all the other suggestions and they work fine in all browsers but Firefox, if you have the same issue, try adding the prevent event in the action attribute either javascript:return false;
or javascript:this.preventDefault();
. Do not try with javascript:void(0);
which will break your code. Don't ask me why :-).
I don't think this is an elegant way to do it, but in my case I had no other choice.
Update:
If you received an error... after ajax is processed, then remove the attribute action and in the onsubmit
attribute, execute your function followed by the false return:
onsubmit="functionToRun(); return false;"
I don't know why all this trouble with Firefox, but hope this works.
Excerpt from PostgreSQL documentation:
Restricting and cascading deletes are the two most common options. [...]
CASCADE
specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.
This means that if you delete a category – referenced by books – the referencing book will also be deleted by ON DELETE CASCADE
.
Example:
CREATE SCHEMA shire;
CREATE TABLE shire.clans (
id serial PRIMARY KEY,
clan varchar
);
CREATE TABLE shire.hobbits (
id serial PRIMARY KEY,
hobbit varchar,
clan_id integer REFERENCES shire.clans (id) ON DELETE CASCADE
);
DELETE FROM
clans will CASCADE
to hobbits by REFERENCES
.
sauron@mordor> psql
sauron=# SELECT * FROM shire.clans;
id | clan
----+------------
1 | Baggins
2 | Gamgi
(2 rows)
sauron=# SELECT * FROM shire.hobbits;
id | hobbit | clan_id
----+----------+---------
1 | Bilbo | 1
2 | Frodo | 1
3 | Samwise | 2
(3 rows)
sauron=# DELETE FROM shire.clans WHERE id = 1 RETURNING *;
id | clan
----+---------
1 | Baggins
(1 row)
DELETE 1
sauron=# SELECT * FROM shire.hobbits;
id | hobbit | clan_id
----+----------+---------
3 | Samwise | 2
(1 row)
If you really need the opposite (checked by the database), you will have to write a trigger!
Try this (demo):
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
text-align: left;
background-color: #ffffff;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
}
.ui-autocomplete > li > div {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333333;
white-space: nowrap;
}
.ui-state-hover,
.ui-state-active,
.ui-state-focus {
text-decoration: none;
color: #262626;
background-color: #f5f5f5;
cursor: pointer;
}
.ui-helper-hidden-accessible {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
you can simply use your own code but add name for the select tag
<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select name="agent_id">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
then you can access it like this
String agent=request.getparameter("agent_id");
If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.
$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
10.0.1, x86_64: "Java SE 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_171, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
Then, in your .bash_profile add the following.
# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
Now if you try java -version again, you should see the version you want.
$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
No you can't; datetime will be stored in default format only while creating table and then you can change the display format in you select
query the way you want using the Mysql Date Time Functions
You can also use the ternary conditional-operator:
var a = "hallo world";_x000D_
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
_x000D_
//var a = "hallo world";_x000D_
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
_x000D_
Visual Studio Code : May 2020 (version 1.46) Shift + UpArrow/DownArrow : To Duplicate the line of code
It looks like you can simply do:
SELECT * FROM your_table WHERE some_column IS NULL OR some_column = '';
Test case:
CREATE TABLE your_table (id int, some_column varchar(10));
INSERT INTO your_table VALUES (1, NULL);
INSERT INTO your_table VALUES (2, '');
INSERT INTO your_table VALUES (3, 'test');
INSERT INTO your_table VALUES (4, 'another test');
INSERT INTO your_table VALUES (5, NULL);
Result:
SELECT id FROM your_table WHERE some_column IS NULL OR some_column = '';
id
----------
1
2
5
Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer
C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks()
method to it, in particular, to do exactly what you require).
On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer
, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).
For my Raspberry Pi 3B model it was
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
This gets a dictionary in JSON format from a webpage with Python 2.X and Python 3.X:
#!/usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
import json
def get_jsonparsed_data(url):
"""
Receive the content of ``url``, parse it as JSON and return the object.
Parameters
----------
url : str
Returns
-------
dict
"""
response = urlopen(url)
data = response.read().decode("utf-8")
return json.loads(data)
url = ("http://maps.googleapis.com/maps/api/geocode/json?"
"address=googleplex&sensor=false")
print(get_jsonparsed_data(url))
See also: Read and write example for JSON
Validate it against FedEx's api. They have an API to generate labels from XML code. The process involves a step to validate the address.
I liked grdevphl's Javascript answer best, but in my own use case, I found that using height()
in the calculation still left a little overlap since it didn't take padding into account. If you run into the same issue, try outerHeight()
instead to compensate for padding and border.
$(document).ready(function() {
var contentPlacement = $('#header').position().top + $('#header').outerHeight();
$('#content').css('margin-top',contentPlacement);
});
Most likely the remote repository doesn't exist or you have added the wrong one.
You have to first remove the origin and re-add it:
git remote remove origin
git remote add origin https://github.com/username/repository
To implement that, it seems that you have to:
org.springframework.security.authentication.ProviderManager
and configure it (set its providers) to a custom org.springframework.security.authentication.AuthenticationProvider
.
This last one should return on its authenticate method a Authentication, which should be setted with the org.springframework.security.core.GrantedAuthority
, in your case, all the permissions for the given user.The trick in that article is to have roles assigned to users, but, to set the permissions for those roles in the Authentication.authorities
object.
For that I advise you to read the API, and see if you can extend some basic ProviderManager and AuthenticationProvider instead of implementing everything. I've done that with org.springframework.security.ldap.authentication.LdapAuthenticationProvider
setting a custom LdapAuthoritiesPopulator, that would retrieve the correct roles for the user.
Hope this time I got what you are looking for. Good luck.
I tried @Jack's answer above, the logo did appear however the image occupied the whole Navigation Bar. I wanted it to fit.
Swift 4, Xcode 9.2
1.Assign value to navigation controller, UIImage. Adjust size by dividing frame and Image size.
func addNavBarImage() {
let navController = navigationController!
let image = UIImage(named: "logo-signIn6.png") //Your logo url here
let imageView = UIImageView(image: image)
let bannerWidth = navController.navigationBar.frame.size.width
let bannerHeight = navController.navigationBar.frame.size.height
let bannerX = bannerWidth / 2 - (image?.size.width)! / 2
let bannerY = bannerHeight / 2 - (image?.size.height)! / 2
imageView.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
imageView.contentMode = .scaleAspectFit
navigationItem.titleView = imageView
}
Add the function right under viewDidLoad()
addNavBarImage()
Note on the image asset. Before uploading, I adjusted the logo with extra margins rather than cropped at the edges.
Final result:
Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr's comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.
v$session_longops
If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.
If you are using DbContext
and EF v6+, alternatively you can use:
this.context.Database.CommandTimeout = 180;
To return a 404 header, just use the :status
option for the render method.
def action
# here the code
render :status => 404
end
If you want to render the standard 404 page you can extract the feature in a method.
def render_404
respond_to do |format|
format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found }
format.xml { head :not_found }
format.any { head :not_found }
end
end
and call it in your action
def action
# here the code
render_404
end
If you want the action to render the error page and stop, simply use a return statement.
def action
render_404 and return if params[:something].blank?
# here the code that will never be executed
end
Also remember that Rails rescues some ActiveRecord errors, such as the ActiveRecord::RecordNotFound
displaying the 404 error page.
It means you don't need to rescue this action yourself
def show
user = User.find(params[:id])
end
User.find
raises an ActiveRecord::RecordNotFound
when the user doesn't exist. This is a very powerful feature. Look at the following code
def show
user = User.find_by_email(params[:email]) or raise("not found")
# ...
end
You can simplify it by delegating to Rails the check. Simply use the bang version.
def show
user = User.find_by_email!(params[:email])
# ...
end
You can use %in%
data[data$Code %in% selected,]
Code Value
1 A 1
2 B 2
7 A 3
8 A 4
Try:
DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate)
this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015
devtop += Math.pow(x[i] - mean, 2);
adds Math.pow(x[i] - mean, 2)
to devtop
.
You can use this javascript function to do this sort of templating. No need to include an entire library.
function createStringFromTemplate(template, variables) {
return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
return variables[varName];
});
}
createStringFromTemplate(
"I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
{
list_name : "this store",
var1 : "FOO",
var2 : "BAR",
var3 : "BAZ"
}
);
Output: "I would like to receive email updates from this store FOO BAR BAZ."
Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.
Displaying a video is much the same as displaying an image. The minor differences are to do with onload events and the fact that you need to render the video every frame or you will only see one frame not the animated frames.
The demo below has some minor differences to the example. A mute function (under the video click mute/sound on to toggle sound) and some error checking to catch IE9+ and Edge if they don't have the correct drivers.
Keeping answers current.The previous answers by user372551 is out of date (December 2010) and has a flaw in the rendering technique used. It uses the setTimeout
and a rate of 33.333..ms which setTimeout will round down to 33ms this will cause the frames to be dropped every two seconds and may drop many more if the video frame rate is any higher than 30. Using setTimeout
will also introduce video shearing created because setTimeout can not be synced to the display hardware.
There is currently no reliable method that can determine a videos frame rate unless you know the video frame rate in advance you should display it at the maximum display refresh rate possible on browsers. 60fps
The given top answer was for the time (6 years ago) the best solution as requestAnimationFrame
was not widely supported (if at all) but requestAnimationFrame
is now standard across the Major browsers and should be used instead of setTimeout to reduce or remove dropped frames, and to prevent shearing.
Loads a video and set it to loop. The video will not play until the you click on it. Clicking again will pause. There is a mute/sound on button under the video. The video is muted by default.
Note users of IE9+ and Edge. You may not be able to play the video format WebM as it needs additional drivers to play the videos. They can be found at tools.google.com Download IE9+ WebM support
// This code is from the example document on stackoverflow documentation. See HTML for link to the example._x000D_
// This code is almost identical to the example. Mute has been added and a media source. Also added some error handling in case the media load fails and a link to fix IE9+ and Edge support._x000D_
// Code by Blindman67._x000D_
_x000D_
_x000D_
// Original source has returns 404_x000D_
// var mediaSource = "http://video.webmfiles.org/big-buck-bunny_trailer.webm";_x000D_
// New source from wiki commons. Attribution in the leading credits._x000D_
var mediaSource = "http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv"_x000D_
_x000D_
var muted = true;_x000D_
var canvas = document.getElementById("myCanvas"); // get the canvas from the page_x000D_
var ctx = canvas.getContext("2d");_x000D_
var videoContainer; // object to hold video and associated info_x000D_
var video = document.createElement("video"); // create a video element_x000D_
video.src = mediaSource;_x000D_
// the video will now begin to load._x000D_
// As some additional info is needed we will place the video in a_x000D_
// containing object for convenience_x000D_
video.autoPlay = false; // ensure that the video does not auto play_x000D_
video.loop = true; // set the video to loop._x000D_
video.muted = muted;_x000D_
videoContainer = { // we will add properties as needed_x000D_
video : video,_x000D_
ready : false, _x000D_
};_x000D_
// To handle errors. This is not part of the example at the moment. Just fixing for Edge that did not like the ogv format video_x000D_
video.onerror = function(e){_x000D_
document.body.removeChild(canvas);_x000D_
document.body.innerHTML += "<h2>There is a problem loading the video</h2><br>";_x000D_
document.body.innerHTML += "Users of IE9+ , the browser does not support WebM videos used by this demo";_x000D_
document.body.innerHTML += "<br><a href='https://tools.google.com/dlpage/webmmf/'> Download IE9+ WebM support</a> from tools.google.com<br> this includes Edge and Windows 10";_x000D_
_x000D_
}_x000D_
video.oncanplay = readyToPlayVideo; // set the event to the play function that _x000D_
// can be found below_x000D_
function readyToPlayVideo(event){ // this is a referance to the video_x000D_
// the video may not match the canvas size so find a scale to fit_x000D_
videoContainer.scale = Math.min(_x000D_
canvas.width / this.videoWidth, _x000D_
canvas.height / this.videoHeight); _x000D_
videoContainer.ready = true;_x000D_
// the video can be played so hand it off to the display function_x000D_
requestAnimationFrame(updateCanvas);_x000D_
// add instruction_x000D_
document.getElementById("playPause").textContent = "Click video to play/pause.";_x000D_
document.querySelector(".mute").textContent = "Mute";_x000D_
}_x000D_
_x000D_
function updateCanvas(){_x000D_
ctx.clearRect(0,0,canvas.width,canvas.height); _x000D_
// only draw if loaded and ready_x000D_
if(videoContainer !== undefined && videoContainer.ready){ _x000D_
// find the top left of the video on the canvas_x000D_
video.muted = muted;_x000D_
var scale = videoContainer.scale;_x000D_
var vidH = videoContainer.video.videoHeight;_x000D_
var vidW = videoContainer.video.videoWidth;_x000D_
var top = canvas.height / 2 - (vidH /2 ) * scale;_x000D_
var left = canvas.width / 2 - (vidW /2 ) * scale;_x000D_
// now just draw the video the correct size_x000D_
ctx.drawImage(videoContainer.video, left, top, vidW * scale, vidH * scale);_x000D_
if(videoContainer.video.paused){ // if not playing show the paused screen _x000D_
drawPayIcon();_x000D_
}_x000D_
}_x000D_
// all done for display _x000D_
// request the next frame in 1/60th of a second_x000D_
requestAnimationFrame(updateCanvas);_x000D_
}_x000D_
_x000D_
function drawPayIcon(){_x000D_
ctx.fillStyle = "black"; // darken display_x000D_
ctx.globalAlpha = 0.5;_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = "#DDD"; // colour of play icon_x000D_
ctx.globalAlpha = 0.75; // partly transparent_x000D_
ctx.beginPath(); // create the path for the icon_x000D_
var size = (canvas.height / 2) * 0.5; // the size of the icon_x000D_
ctx.moveTo(canvas.width/2 + size/2, canvas.height / 2); // start at the pointy end_x000D_
ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 + size);_x000D_
ctx.lineTo(canvas.width/2 - size/2, canvas.height / 2 - size);_x000D_
ctx.closePath();_x000D_
ctx.fill();_x000D_
ctx.globalAlpha = 1; // restore alpha_x000D_
} _x000D_
_x000D_
function playPauseClick(){_x000D_
if(videoContainer !== undefined && videoContainer.ready){_x000D_
if(videoContainer.video.paused){ _x000D_
videoContainer.video.play();_x000D_
}else{_x000D_
videoContainer.video.pause();_x000D_
}_x000D_
}_x000D_
}_x000D_
function videoMute(){_x000D_
muted = !muted;_x000D_
if(muted){_x000D_
document.querySelector(".mute").textContent = "Mute";_x000D_
}else{_x000D_
document.querySelector(".mute").textContent= "Sound on";_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
// register the event_x000D_
canvas.addEventListener("click",playPauseClick);_x000D_
document.querySelector(".mute").addEventListener("click",videoMute)
_x000D_
body {_x000D_
font :14px arial;_x000D_
text-align : center;_x000D_
background : #36A;_x000D_
}_x000D_
h2 {_x000D_
color : white;_x000D_
}_x000D_
canvas {_x000D_
border : 10px white solid;_x000D_
cursor : pointer;_x000D_
}_x000D_
a {_x000D_
color : #F93;_x000D_
}_x000D_
.mute {_x000D_
cursor : pointer;_x000D_
display: initial; _x000D_
}
_x000D_
<h2>Basic Video & canvas example</h2>_x000D_
<p>Code example from Stackoverflow Documentation HTML5-Canvas<br>_x000D_
<a href="https://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14974/basic-loading-and-playing-a-video-on-the-canvas#t=201607271638099201116">Basic loading and playing a video on the canvas</a></p>_x000D_
<canvas id="myCanvas" width = "532" height ="300" ></canvas><br>_x000D_
<h3><div id = "playPause">Loading content.</div></h3>_x000D_
<div class="mute"></div><br>_x000D_
<div style="font-size:small">Attribution in the leading credits.</div><br>
_x000D_
Using the canvas to render video gives you additional options in regard to displaying and mixing in fx. The following image shows some of the FX you can get using the canvas. Using the 2D API gives a huge range of creative possibilities.
Image relating to answer Fade canvas video from greyscale to color
See video title in above demo for attribution of content in above inmage.
Or use my solution here www.my-mo.co.uk/device/deviceinfo.php will let you access UDID and email it to whoever you choose too.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
This will give the output:
2017-07-14 08:10:00
you can redirect stderr.
more explanation here, but having a command like:
MyCommand >log.txt 2>errors.txt
should grab the data you are looking for.
Also, as a trick, Windows bypasses that limitation if the path is prefixed with \\?\
(msdn)
Another trick if you have a root or destination that starts with a long path, perhaps SUBST
will help:
SUBST Q: "C:\Documents and Settings\MyLoginName\My Documents\MyStuffToBeCopied"
Xcopy Q:\ "d:\Where it needs to go" /s /e
SUBST Q: /D
Both .done()
and .success()
are callback functions and they essentially function the same way.
Here's the documentation. The difference is that .success()
is deprecated as of jQuery 1.8. You should use .done()
instead.
In case you don't want to click the link:
Deprecation Notice
The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
Also possible by looking for substring with index() function:
awk '(index($3, "snow") != 0) {print}' dummy_file
Shorter version:
awk 'index($3, "snow")' dummy_file
getContentResolver()
is method of class android.content.Context
, so to call it you definitely need an instance
of Context ( Activity or Service for example).
From Python v2.7.14 documentation - 18.1.11. email: Examples:
Here’s an example of how to create an HTML message with an alternative plain text version:
#! /usr/bin/python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "[email protected]"
you = "[email protected]"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
sounds silly but font-size:0; might just work. It did for me. And you can easily override this with the child element you need to show.
According to Microsoft:
The CultureInfo.InvariantCulture property is neither a neutral nor a specific culture. It is the third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region.
(from http://msdn.microsoft.com/en-us/library/4c5zdc6a(vs.71).aspx)
So InvariantCulture is similair to culture "en-US" but not exactly the same. If you write:
var d = DateTime.Now;
var s1 = d.ToString(CultureInfo.InvariantCulture); // "05/21/2014 22:09:28"
var s2 = d.ToString(new CultureInfo("en-US")); // "5/21/2014 10:09:28 PM"
then s1 and s2 will have a similar format but InvariantCulture adds leading zeroes and "en-US" uses AM or PM.
So InvariantCulture is better for internal usage when you e.g save a date to a text-file or parses data. And a specified CultureInfo is better when you present data (date, currency...) to the end-user.
Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.
yes | execute_command
This will use yes as the answer to all yes/no prompts.
Windows -> Preferences -> General -> Startup and Shutdown
Is Refresh workspace on startup
checked?
cd to sessions directory and then:
1) View sessions older than 40 min:
find . -amin +40 -exec stat -c "%n %y" {} \;
2) Remove sessions older than 40 min:
find . -amin +40 -exec rm {} \;
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
Just need to move the map below this box. Work to me.
From Google
Local Explorer - File Manager on web browser extention can solve for chrome
but still some encoding problems
There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...
FOR
is essentially iterating over the "lines" in the data set. In this case, there is one line that contains the path. The "delims=;"
is just telling it to separate on semi-colons. If you change the body to echo %%g,%%h,%%i,%%j,%%k
you'll see that it is treating the input as a single line and breaking it into multiple tokens.
I figured it out. json_encode handles objects differently than strings. I cast the object to a string and it works now.
foreach($xml->children() as $state)
{
$states[]= array('state' => (string)$state->name);
}
echo json_encode($states);
if you still could be able to send mail after setting all configs right and get forbidden or timeout errors you could set the allow less secure apps to access your account
in gmail. you can follow how to here
c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).
I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST)
puts label number X in LIST
with the line corresponding to the Xth time plot
was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:
...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
plotHandles.append(x)
labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)
I use an ::after element in the cell where I want to set a minimal width regardless of the text present, like this:
.cell::after {
content: "";
width: 20px;
display: block;
}
I don't have to set width on the table parent nor use table-layout.
it depends on your php settings...
use phpinfo()
and take a look at the session chapter. There are values like session.gc_maxlifetime
and session.cache_expire
and session.cookie_lifetime
which affects the sessions lifetime
EDIT: it's like Martin write before
Given an OnTouchListener
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
set on some view:
myView.setOnTouchListener(handleTouch);
This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0)
. If you move your finger above the view, then y
will be negative. If you move your finger left of the view, then x
will be negative.
int x = (int)event.getX();
int y = (int)event.getY();
If you want the coordinates relative to the top left corner of the device screen, then use the raw values.
int x = (int)event.getRawX();
int y = (int)event.getRawY();
I have encountered a specific case from my side with 10^11 rows in my dataframe, and in this case none of the proposed solution is appropriate. I have used categories, and this should work fine in all cases when the number of unique string is not too large. This is easily done in the R software with XxY with factors but I could not find any other way to do it in python (I'm new to python). If anyone knows a place where this is implemented I'd be glad to know.
def Create_Interaction_var(df,Varnames):
'''
:df data frame
:list of 2 column names, say "X" and "Y".
The two columns should be strings or categories
convert strings columns to categories
Add a column with the "interaction of X and Y" : X x Y, with name
"Interaction-X_Y"
'''
df.loc[:, Varnames[0]] = df.loc[:, Varnames[0]].astype("category")
df.loc[:, Varnames[1]] = df.loc[:, Varnames[1]].astype("category")
CatVar = "Interaction-" + "-".join(Varnames)
Var0Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[0]].cat.categories)).rename(columns={0 : "code0",1 : "name0"})
Var1Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[1]].cat.categories)).rename(columns={0 : "code1",1 : "name1"})
NbLevels=len(Var0Levels)
names = pd.DataFrame(list(itertools.product(dict(enumerate(df.loc[:,Varnames[0]].cat.categories)),
dict(enumerate(df.loc[:,Varnames[1]].cat.categories)))),
columns=['code0', 'code1']).merge(Var0Levels,on="code0").merge(Var1Levels,on="code1")
names=names.assign(Interaction=[str(x) + '_' + y for x, y in zip(names["name0"], names["name1"])])
names["code01"]=names["code0"] + NbLevels*names["code1"]
df.loc[:,CatVar]=df.loc[:,Varnames[0]].cat.codes+NbLevels*df.loc[:,Varnames[1]].cat.codes
df.loc[:, CatVar]= df[[CatVar]].replace(names.set_index("code01")[["Interaction"]].to_dict()['Interaction'])[CatVar]
df.loc[:, CatVar] = df.loc[:, CatVar].astype("category")
return df
This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.
You can find more on MSXML2.DOMDocument at the following sites:
var_dump(extension_loaded('curl'));
This works if the dll is .net or Win32. Reflection methods only work if the dll is .net. Also, if you use reflection, you have the overhead of loading the whole dll into memory. The below method does not load the assembly into memory.
// Get the file version.
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\MyAssembly.dll");
// Print the file name and version number.
Console.WriteLine("File: " + myFileVersionInfo.FileDescription + '\n' +
"Version number: " + myFileVersionInfo.FileVersion);
From: http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.fileversion.aspx
Try this:
git commit --amend
Then copy and paste the Change-Id: I55862204ef71f69bc88c79fe2259f7cb8365699a
at the end of the file.
Save it and push it again!
If the dir to search is srch_dir
then either
$ find srch_dir -cmin -60 # change time
or
$ find srch_dir -mmin -60 # modification time
or
$ find srch_dir -amin -60 # access time
shows files created, modified or accessed in the last hour.
correction :ctime is for change node time (unsure though, please correct me )
A little more robust version of what you're attempting:
str = str.replaceAll("(\r\n|\n\r|\r|\n)", "<br />");
If you have a Linux-Machine you could use the free command-line tool SAXCount. I found this very usefull.
SAXCount -f -s -n my.xml
It validates against dtd and xsd. 5s for a 50MB file.
In debian squeeze it is located in the package "libxerces-c-samples".
The definition of the dtd and xsd has to be in the xml! You can't config them separately.
Here's an alternative solution using javascipt:
document.querySelector('.slick-prev').innerHTML = '<img src="path/to/chevron-left-image.svg">'>;
document.querySelector('.slick-next').innerHTML = '<img src="path/to/chevron-right-image.svg">'>;
Change the img to text or what ever you require.
you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with
entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();
Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080
npm set https-proxy http://username:password@companyProxy:8080
npm config set strict-ssl false -g
NOTES: No special characters in password except @ allowed.
Assertion throws error message if first attribute is false, and the second attribute is the message to be thrown.
console.assert(condition,message);
There are many comments saying assertion does not exist in JavaScript but console.assert()
is the assert function in JavaScript
The idea of assertion is to find why/where the bug occurs.
console.assert(document.getElementById("title"), "You have no element with ID 'title'");
console.assert(document.getElementById("image"), "You have no element with ID 'image'");
Here depending on the message you can find what the bug is.
These error messages will be displayed to console in red color as if we called console.error();
You can use assertions to test your functions eg:
console.assert(myAddFunction(5,8)===(5+8),"Failed on 5 and 8");
Note the condition can be anything like !=
<
>
etc
This is commonly used to test if the newly created function works as expected by providing some test cases and is not meant for production.
To see more functions in console execute console.log(console);
os.stat
does include the creation time. There's just no definition of st_anything for the element of os.stat()
that contains the time.
So try this:
os.stat('feedparser.py')[8]
Compare that with your create date on the file in ls -lah
They should be the same.
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
You can do it by following way.
ALTER TABLE tableName drop column if exists columnName;
ALTER TABLE tableName ADD COLUMN columnName character varying(8);
So it will drop the column if it is already exists. And then add the column to particular table.
I'm answering this question for the second time, because the solution I've tried that didn't work at first now works, and I can recreate the steps to make it work :)
I also had a feeling that lack of Google Play Store is a culprit here, so I've tried to install Google Play Store to the emulator by advice on this link and this link combined. I've had some difficulties, but at the end I've succeeded in installing Google Play Store and tested it by downloading some random app. But the maps activity kept displaying the message with the "Update" button. That button would take me to the store, but there I would get a message about "item not found" and maps still didn't work. At that point I gave up.
Yesterday, I've fired up the same test app by accident and it worked! I was very confused, but quickly I've made a diff from the emulator where it's working and new clean one and I've determined two apps on the working one in /data/app/ directory: com.android.vending-1.apk and com.google.android.gms-1.apk. This is strange since, when I were installing Google Play Store by instructions from those sites, I was pushing Phonesky.apk, GoogleServicesFramework.apk and GoogleLoginService.apk and to a different folder /system/app.
Anyway, now the Android Google Maps API v2 is working on my emulator. These are the steps to do this:
Create a new emulator
These are the settings that are working for me. I don't know for different ones.
Start the emulator
install com.android.vending-1.apk and com.google.android.gms-1.apk via ADB install command
Google Maps should work now in your emulator.
import os
path = 'C:/Users/Shashank/Desktop/'
os.chdir(path)
for p,n,f in os.walk(os.getcwd()):
for a in f:
a = str(a)
if a.endswith('.csv'):
print(a)
print(p)
This will help to identify path also of these csv files
You need set image type :small_image or image
echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);
I think there is not similar function like data.shape
in Spark. But I will use len(data.columns)
rather than len(data.dtypes)
Here's an example of posting to a web service using the HttpWebRequest and HttpWebResponse objects.
StringBuilder sb = new StringBuilder();
string query = "?q=" + latitude + "%2C" + longitude + "&format=xml&key=xxxxxxxxxxxxxxxxxxxxxxxx";
string weatherservice = "http://api.worldweatheronline.com/free/v1/marine.ashx" + query;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherservice);
request.Referer = "http://www.yourdomain.com";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Char[] readBuffer = new Char[256];
int count = reader.Read(readBuffer, 0, 256);
while (count > 0)
{
String output = new String(readBuffer, 0, count);
sb.Append(output);
count = reader.Read(readBuffer, 0, 256);
}
string xml = sb.ToString();
const inpT = document.getElementById("text-box");_x000D_
const inpC = document.getElementById("text-box-content");_x000D_
// swch gets inputs ._x000D_
var swch;_x000D_
// swch if corsur is active in inputs defaulte is false ._x000D_
var isSelect = false;_x000D_
_x000D_
var crnselect;_x000D_
// on focus_x000D_
function setSwitch(e) {_x000D_
swch = e;_x000D_
isSelect = true;_x000D_
console.log("set Switch: " + isSelect);_x000D_
}_x000D_
// on click ev_x000D_
function setEmoji() {_x000D_
if (isSelect) {_x000D_
console.log("emoji added :)");_x000D_
swch.value += ":)";_x000D_
swch.setSelectionRange(2,2 );_x000D_
isSelect = true;_x000D_
}_x000D_
_x000D_
}_x000D_
// on not selected on input . _x000D_
function onout() {_x000D_
// ?????? ??? ?? ?? _x000D_
crnselect = inpC.selectionStart;_x000D_
_x000D_
// return input select not active after 200 ms ._x000D_
var len = swch.value.length;_x000D_
setTimeout(() => {_x000D_
(len == swch.value.length)? isSelect = false:isSelect = true;_x000D_
}, 200);_x000D_
}
_x000D_
<h1> Try it !</h1>_x000D_
_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">_x000D_
<button onclick="setEmoji()">emogi :) </button>
_x000D_
Some answers already - but I would like to point you to YUI3 and its on-demand module loading. It works on both server (node.js) and client, too - I have a demo website using the exact same JS code running on either client or server to build the pages, but that's another topic.
YUI3: http://developer.yahoo.com/yui/3/
Videos: http://developer.yahoo.com/yui/theater/
Example:
(precondition: the basic YUI3 functions in 7k yui.js have been loaded)
YUI({
//configuration for the loader
}).use('node','io','own-app-module1', function (Y) {
//sandboxed application code
//...
//If you already have a "Y" instance you can use that instead
//of creating a new (sandbox) Y:
// Y.use('moduleX','moduleY', function (Y) {
// });
//difference to YUI().use(): uses the existing "Y"-sandbox
}
This code loads the YUI3 modules "node" and "io", and the module "own-app-module1", and then the callback function is run. A new sandbox "Y" with all the YUI3 and own-app-module1 functions is created. Nothing appears in the global namespace. The loading of the modules (.js files) is handled by the YUI3 loader. It also uses (optional, not show here) configuration to select a -debug or -min(ified) version of the modules to load.
This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:
// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;
// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;
Both alternatives are functionally identical. The reason for introducing the as
-syntax is that the original syntax conflicted with JSX, see the design discussion here.
If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as
-syntax as it feels more fluent to read and write.
Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.
You will need to do this for the 'Subreports' nodes as well.
FYI, you can also do individual tables by selecting each individually, then choosing Update.
I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete
I was referencing a mapped drive and I found that the mapped drives are not always available to the user account that is running the scheduled task so I used \\IPADDRESS
instead of MAPDRIVELETTER:
and I am up and running.
Make sure you use latest rvm:
rvm get stable
Then you can do two things:
Update certificates:
rvm osx-ssl-certs update all
Update rubygems:
rvm rubygems latest
Find path for certificate:
cert_file=$(ruby -ropenssl -e 'puts OpenSSL::X509::DEFAULT_CERT_FILE')
Generate certificate:
security find-certificate -a -p /Library/Keychains/System.keychain > "$cert_file"
security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> "$cert_file"
The whole code: https://github.com/wayneeseguin/rvm/blob/master/scripts/functions/osx-ssl-certs
Make sure to update package ca-certificates
. (on old systems it might not be available - do not use an old system which does not receive security updates any more)
The Ruby Installer builds for windows are prepared by Luis Lavena and the path to certificates will be showing something like C:/Users/Luis/...
check https://github.com/oneclick/rubyinstaller/issues/249 for more details and this answer https://stackoverflow.com/a/27298259/497756 for fix.
Simply add a title
to your button
.
<button title="Hello World!">Sample Button</button>
_x000D_
static
data members in class?The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a
is allowed to be initialized while others are not.
Reference:
C++03 9.4.2 Static data members
§4
If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
What are integral types?
C++03 3.9.1 Fundamental types
§7
Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.
Footnote:
43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.
You could use the enum trick to initialize an array inside your class definition.
class A
{
static const int a = 3;
enum { arrsize = 2 };
static const int c[arrsize] = { 1, 2 };
};
Bjarne explains this aptly here:
A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.
static const
integral types & enums allowed In-class Initialization?The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."
Note that only static const
integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.
It is noteworthy to note here that even if static const
integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.
enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above
C++11 relaxes the restriction to certain extent.
C++11 9.4.2 Static data members
§3
If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the
constexpr specifier;
if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.
Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}
, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.
This is helpful when your equals method call throws some exception e.g. NullPointerException
;
boolean isMatch = false;
try{
isMatch = email1.equals (email2);
}catch(NullPointerException npe){
.....
}
System.out.print("Match=="+isMatch);
if(isMatch){
......
}
When creating a new project - Maven - Java application in Netbeans the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Hope this works for others as well.
The "manual bootstrap" case can gain access to Angular services by manually creating an injector before bootstrap. This initial injector will stand alone (not be attached to any elements) and include only a subset of the modules that are loaded. If all you need is core Angular services, it's sufficient to just load ng
, like this:
angular.element(document).ready(
function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/config.json').then(
function (response) {
var config = response.data;
// Add additional services/constants/variables to your app,
// and then finally bootstrap it:
angular.bootstrap(document, ['myApp']);
}
);
}
);
You can, for example, use the module.constant
mechanism to make data available to your app:
myApp.constant('myAppConfig', data);
This myAppConfig
can now be injected just like any other service, and in particular it's available during the configuration phase:
myApp.config(
function (myAppConfig, someService) {
someService.config(myAppConfig.someServiceConfig);
}
);
or, for a smaller app, you could just inject the global config directly into your service, at the expense of spreading knowledge about the configuration format throughout the application.
Of course, since the async operations here will block the bootstrap of the application, and thus block the compilation/linking of the template, it's wise to use the ng-cloak
directive to prevent the unparsed template from showing up during the work. You could also provide some sort of loading indication in the DOM , by providing some HTML that gets shown only until AngularJS initializes:
<div ng-if="initialLoad">
<!-- initialLoad never gets set, so this div vanishes as soon as Angular is done compiling -->
<p>Loading the app.....</p>
</div>
<div ng-cloak>
<!-- ng-cloak attribute is removed once the app is done bootstrapping -->
<p>Done loading the app!</p>
</div>
I created a complete, working example of this approach on Plunker, loading the configuration from a static JSON file as an example.
Try this
if(!a || a.length === 0)
There is packaging package available, which will allow you to compare versions as per PEP-440, as well as legacy versions.
>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True
Legacy version support:
>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>
Comparing legacy version with PEP-440 version.
>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True
I know this post is old, sorry for that.
You can also type 10x
for cols and x2
for rows, if you want to have only one attribute.
[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->