I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
As you can see, $rootScope.$broadcast
hits a lot more listeners than $scope.$emit
.
Also, $scope.$emit
's bubbling effect can be cancelled, whereas $rootScope.$broadcast
cannot.
If you're using PHP 5.5 you can use a generator. This will NOT work in any version of PHP before 5.5 though. From php.net:
"Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface."
// This function implements a generator to load individual lines of a large file
function getLines($file) {
$f = fopen($file, 'r');
// read each line of the file without loading the whole file to memory
while ($line = fgets($f)) {
yield $line;
}
}
// Since generators implement simple iterators, I can quickly count the number
// of lines using the iterator_count() function.
$file = '/path/to/file.txt';
$lineCount = iterator_count(getLines($file)); // the number of lines in the file
This worked me for UNICODE (UTF8) sentences too:
function myUTF8truncate($string, $width){
if (mb_str_word_count($string) > $width) {
$string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
}
return $string;
}
Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)
See here: Git doesn't clone all branches on subsequent clones?
If you really want this by pulling branches instead of push --mirror
, you can have a look here:
"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones
This answer provides detailed steps on how to achieve that relatively easily:
You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:
<a href="your_page.php?var1=value1&var2=value2">
You separate each of those values with the &
sign.
Or you can create this on a button click like this:
<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">
Process Hacker has numerous ways of killing a process.
(Right-click the process, then go to Miscellaneous->Terminator.)
I would modify the example above as follows:
import java.math.BigDecimal;
BigDecimal premium = new BigDecimal("1586.6");
BigDecimal netToCompany = new BigDecimal("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
This way you avoid the pitfalls of using string to begin with. Another alternative:
import java.math.BigDecimal;
BigDecimal premium = BigDecimal.valueOf(158660, 2);
BigDecimal netToCompany = BigDecimal.valueOf(70875, 2);
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
I think these options are better than using doubles. In webapps numbers start out as strings anyways.
Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.
I also thought of the SELECT DISTINCT...
thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.
So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY
clause.
Imagine you have the table customer_pets
like this:
+-----------------------+
| customer | pets |
+------------+----------+
| customer1 | 2 |
| customer2 | 3 |
| customer3 | 2 |
| customer4 | 2 |
| customer5 | 3 |
| customer6 | 4 |
+------------+----------+
then
SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets
would return:
+----------------------------+
| num_customers | pets |
+-----------------+----------+
| 3 | 2 |
| 2 | 3 |
| 1 | 4 |
+-----------------+----------+
as you need.
Be Careful, Follow these steps and save your time
Right Click on your Project Explorer.
Select New-> Project -> Android Application Project from Existing Code
Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"
Be careful brose only upto - google_play_services and not upto google_play_services_lib
And this way you are able to import the google play service lib.
Let me know if you have any queries regarding the same.
Thanks
I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default]
? Replace by space:
You can perform bulk insert using mongoose, as the highest score answer. But the example cannot work, it should be:
/* a humongous amount of potatos */
var potatoBag = [{name:'potato1'}, {name:'potato2'}];
var Potato = mongoose.model('Potato', PotatoSchema);
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
Don't use a schema instance for the bulk insert, you should use a plain map object.
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'"
) or you can escape it inside single quotes ('\''
).
To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:
>>> "didn't".replace("'", "")
'didnt'
For encoding/decoding numbers to/from byte sequences, there's the encoding/binary package. There are examples in the documentation: see the Examples section in the table of contents.
These encoding functions operate on io.Writer interfaces. The net.TCPConn type implements io.Writer, so you can write/read directly to network connections.
If you've got a Go program on either side of the connection, you may want to look at using encoding/gob. See the article "Gobs of data" for a walkthrough of using gob (skip to the bottom to see a self-contained example).
Download and run the latest MSI. The MSI will update your installed node and npm.
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
If using JDBC driver you may use function escape sequence like this:
select {fn MOD(5, 2)}
#Result 1
select mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.
Give a Format String value of C2 for the value's properties as shown in figure below.
I tried all the steps described above but failed.
Like, connect to the internet with Data connection
, Turning off the MIUI optimization and reboot
, Turning on Install via USB
from Security settings etc.
Then I found a solution.
Steps:
China-Shanghai
serverInstall via USB
from Developer option.That's all.
I created it in a more similar way to the SQL, I think it is easier to understand
var list = (from a in listA.AsEnumerable()
join b in listB.AsEnumerable() on a.id equals b.id into ab
from c in ab.DefaultIfEmpty()
where c != null
select new { id = c.id, name = c.nome }).ToList();
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
Here is the Latest solution of the problem:
In your CSS file write the following class called .clearfix along with the pseudo selector :after
.clearfix:after {
content: "";
display: table;
clear: both;
}
Then, in your HTML, add the .clearfix class to your parent Div. For example:
<div class="clearfix">
<div></div>
<div></div>
</div>
It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "".
Source: http://css-snippets.com/page/2/
The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.
For example, in your case where an int
is the key or index:
public int this[int index]
{
get => GetValue(index);
}
You can also add a set accessor so that the indexer becomes read and write rather than just read-only.
public int this[int index]
{
get => GetValue(index);
set => SetValue(index, value);
}
If you want to index using a different type, you just change the signature of the indexer.
public int this[string index]
...
You can use this formula regardless of DATEFIRST
setting :
((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - [first day that you need] ) % 7) + 1;
for monday = 1
((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 1 ) % 7) + 1;
and for sunday = 1
((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 7 ) % 7) + 1;
and for friday = 1
((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 5 ) % 7) + 1;
I prefer to use nvidia-smi to monitor GPU usage. if it goes up significantly when you start you program, it's a strong sign that your tensorflow is using GPU.
Just in case you have pandas (import pandas as pd
) or are ok with using it:
test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)],
[random.gauss(4,2) for _ in range(400)]])
plt.hist(test.values.T)
plt.show()
If you don't declare a function and it only appears after being called, it is automatically assumed to be int
, so in your case, you didn't declare
void my_print (char *);
void my_print2 (char *);
before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *);
and int my_print2 (char *);
and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types
.
As Brian suggested, declare those two methods before main.
This works:
<div>
<input type="text"
style="margin: 5px; padding: 4px; border: 1px solid;
width: 200px; width: calc(100% - 20px);">
</div>
The first 'width' is a fallback rule for older browsers.
This is the Docker Hub page for Ubuntu and this is how it is created. It only has (somewhat) bare minimum packages installed, thus if you need anything extra you need to install it yourself.
apt-get update && apt-get install -y iputils-ping
However usually you'd create a "Dockerfile" and build it:
mkdir ubuntu_with_ping
cat >ubuntu_with_ping/Dockerfile <<'EOF'
FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
CMD bash
EOF
docker build -t ubuntu_with_ping ubuntu_with_ping
docker run -it ubuntu_with_ping
Please use Google to find tutorials and browse existing Dockerfiles to see how they usually do things :) For example image size should be minimized by running apt-get clean && rm -rf /var/lib/apt/lists/*
after apt-get install
commands.
As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.
foreach (var tempClass in macroClasses)
{
// using reflection I will be able to run the method as:
tempClass.GetMethod("Run").Invoke(null, null);
}
As the comment points out, you may want to ensure the method is static when calling GetMethod
:
tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
This is quite simple the way I resolved this problem:
your problem is resolved .
TL;DR: rails g scaffold_controller <name>
Even though you already have a model, you can still generate the necessary controller and migration files by using the rails generate
option. If you run rails generate -h
you can see all of the options available to you.
Rails:
controller
generator
helper
integration_test
mailer
migration
model
observer
performance_test
plugin
resource
scaffold
scaffold_controller
session_migration
stylesheets
If you'd like to generate a controller scaffold for your model, see scaffold_controller
. Just for clarity, here's the description on that:
Stubs out a scaffolded controller and its views. Pass the model name, either CamelCased or under_scored, and a list of views as arguments. The controller name is retrieved as a pluralized version of the model name.
To create a controller within a module, specify the model name as a path like 'parent_module/controller_name'.
This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.
To create your resource, you'd use the resource
generator, and to create a migration, you can also see the migration
generator (see, there's a pattern to all of this madness). These provide options to create the missing files to build a resource. Alternatively you can just run rails generate scaffold
with the --skip
option to skip any files which exist :)
I recommend spending some time looking at the options inside of the generators. They're something I don't feel are documented extremely well in books and such, but they're very handy.
index = 2
//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]
console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));
console.log("----after-----");
console.log(arr1);
console.log(arr2);
let log = console.log;_x000D_
_x000D_
//splice & will modify the origin array_x000D_
const arr1 = [1,2,3,4,5];_x000D_
_x000D_
//slice & won't modify the origin array_x000D_
const arr2 = [1,2,3,4,5]_x000D_
_x000D_
log("----before-----");_x000D_
log(arr1.splice(2, 1));_x000D_
log(arr2.slice(2, 1));_x000D_
_x000D_
log("----after-----");_x000D_
log(arr1);_x000D_
log(arr2);
_x000D_
If the row contains some leading (or trailing) th
tags before the td
you should use the :first-of-type
and the :last-of-type
selectors. Otherwise the first td
won't be selected if it's not the first element of the row.
This gives:
td:first-of-type, td:last-of-type {
/* styles */
}
Why don't you use a List<People>
instead of a List<List<string>>
?
Add rows:
<html>_x000D_
<script>_x000D_
function addRow() {_x000D_
var table = document.getElementById('myTable');_x000D_
//var row = document.getElementById("myTable");_x000D_
var x = table.insertRow(0);_x000D_
var e = table.rows.length-1;_x000D_
var l = table.rows[e].cells.length;_x000D_
//x.innerHTML = " ";_x000D_
_x000D_
for (var c=0, m=l; c < m; c++) {_x000D_
table.rows[0].insertCell(c);_x000D_
table.rows[0].cells[c].innerHTML = " ";_x000D_
}_x000D_
}_x000D_
_x000D_
function addColumn() {_x000D_
var table = document.getElementById('myTable');_x000D_
for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
table.rows[r].insertCell(0);_x000D_
table.rows[r].cells[0].innerHTML = " ";_x000D_
}_x000D_
}_x000D_
_x000D_
function deleteRow() {_x000D_
document.getElementById("myTable").deleteRow(0);_x000D_
}_x000D_
_x000D_
function deleteColumn() {_x000D_
// var row = document.getElementById("myRow");_x000D_
var table = document.getElementById('myTable');_x000D_
for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
table.rows[r].deleteCell(0); // var table handle_x000D_
}_x000D_
}_x000D_
</script>_x000D_
_x000D_
<body>_x000D_
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>_x000D_
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>_x000D_
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>_x000D_
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>_x000D_
_x000D_
<table id='myTable' border=1 cellpadding=0 cellspacing=0>_x000D_
<tr id='myRow'>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
<td> </td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
And cells.
You may want to comment out the DL is deprecated, please use Fiddle
warning at
C:\Ruby200\lib\ruby\2.0.0\dl.rb
since it’s annoying and you are not the irb/pry or some other gems code owner
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
Perhaps a contrived "real world" example would help.
At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish>
and Bin<RecylcableRubbish>
. The type system needs to make sure I can't put my HalfEatenSandwichRubbish
into either of these types, but it can go into a general rubbish bin Bin<Rubbish>
. If I wanted to talk about a Bin
of Rubbish
which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>
.
(Note: ? extends
does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)
Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.
This should work.
$foo = someFunction 2>$null
Also you can, call by tags names, like this: form_name.input_name.value;
So you will have the specific value of determined input in a specific form.
You can't cause a .Net application to elevate its own rights. It's simply not allowed. The best you can do is to specify elevated rights when you spawn another process. In this case you would have a two-stage application launch.
Stage 1 does nothing but prepare an elevated spawn using the System.Diagnostics.ProcessStartInfo object and the Start() call.
Stage 2 is the application running in an elevated state.
As mentioned above, though, you very rarely want to do this. And you certainly don't want to do it just so you can write temporary files into %programfiles%. Use this method only when you need to perform administrative actions like service start/stop, etc. Write your temporary files into a better place, as indicated in other answers here.
split($pattern,$string)
split strings within a given pattern or regex (it's deprecated since 5.3.0)
preg_split($pattern,$string)
split strings within a given regex pattern
explode($pattern,$string)
split strings within a given pattern
end($arr)
get last array element
So:
end(split('-',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
$lastElement = end($strArray)
Will return the last element of a -
separated string.
And there's a hardcore way to do this:
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
// | '--- get the last position of '-' and add 1(if don't substr will get '-' too)
// '----- get the last piece of string after the last occurrence of '-'
Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');
}
</script>
It's running every minute of the hour 22 I guess. Try the following to run it every first minute of the hour 22:
0 22 * * * ....
Simply put your RecyclerView inside a NestedScrollView. Works perfectly
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="25dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/kliste"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.NestedScrollView>
Something like this?:
INSERT INTO destTable
SELECT s.* FROM srcTable s
LEFT JOIN destTable d ON d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...
WHERE d.Key1 IS NULL
Let's say you have these lines of code:
test line one
test line two
test line three
test line four
Using Search and Replace Ctrl+H with Regex let's find this: ^
and replace it with "
, we'll have this:
"test line one
"test line two
"test line three
"test line four
Now let's search this: $
and replace it with "
, now we'll have this:
"test line one"
"test line two"
"test line three"
"test line four"
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
other than using this.form.submit()
you also submiting by id or name.
example i have form like this : <form action="" name="PostName" id="IdName">
By Name : <select onchange="PostName.submit()">
By Id : <select onchange="IdName.submit()">
I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.
I found that if I ran cat /tmp/list.txt
the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1;
just before the cat /tmp/list.txt
it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.
My final code:
while [ ! -f /tmp/list.txt ];
do
sleep 1;
done;
sleep 1;
cat /tmp/list.txt;
Hope this helps save someone a frustrating half hour!
Use !=
or <>
. Both stands for not equal.
The comparison operators <>
and !=
are alternate spellings of the same operator. !=
is the preferred spelling; <>
is obsolescent. [Reference: Python language reference]
One doesn't always know the type into which to deserialize. So it would be handy to be able to take any JSON (that contains some array) and dynamically produce a table from that.
An issue can arise however, where the deserializer doesn't know where to look for the array to tabulate. When this happens, we get an error message similar to the following:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
Even if we give it come encouragement or prepare our json accordingly, then "object" types within the array can still prevent tabulation from occurring, where the deserializer doesn't know how to represent the objects in terms of rows, etc. In this case, errors similar to the following occur:
Unexpected JSON token when reading DataTable: StartObject. Path '[0].__metadata', line 3, position 19.
The below example JSON includes both of these problematic features:
{
"results":
[
{
"Enabled": true,
"Id": 106,
"Name": "item 1",
},
{
"Enabled": false,
"Id": 107,
"Name": "item 2",
"__metadata": { "Id": 4013 }
}
]
}
So how can we resolve this, and still maintain the flexibility of not knowing the type into which to derialize?
Well here is a simple approach I came up with (assuming you are happy to ignore the object-type properties, such as __metadata in the above example):
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Linq;
...
public static DataTable Tabulate(string json)
{
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
}
I know this could be more "LINQy" and has absolutely zero exception handling, but hopefully the concept is conveyed.
We're starting to use more and more services at my work that spit back JSON, so freeing ourselves of strongly-typing everything, is my obvious preference because I'm lazy!
If you want some element to contain a value that is HTML, take a look at ngBindHtmlUnsafe.
If you want to style options in a native select, no it is not possible.
In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:
LDFLAGS='-lpthread'
Hope it'll help somebody too...
Even though OutputDebugString
indeed prints a string of characters to the debugger console, it's not exactly like printf
with regard to the latter being able to format arguments using the %
notation and a variable number of arguments, something OutputDebugString
does not do.
I would make the case that the _RPTFN
macro, with _CRT_WARN
argument at least, is a better suitor in this case -- it formats the principal string much like printf
, writing the result to debugger console.
A minor (and strange, in my opinion) caveat with it is that it requires at least one argument following the format string (the one with all the %
for substitution), a limitation printf
does not suffer from.
For cases where you need a puts
like functionality -- no formatting, just writing the string as-is -- there is its sibling _RPTF0
(which ignores arguments following the format string, another strange caveat). Or OutputDebugString
of course.
And by the way, there is also everything from _RPT1
to _RPT5
but I haven't tried them. Honestly, I don't understand why provide so many procedures all doing essentially the same thing.
From python 3.4.4, you can use multiprocessing.get_context() to obtain a context object to use multiple start methods:
import multiprocessing as mp
def foo(q, h, w):
q.put(h + ' ' + w)
print(h + ' ' + w)
if __name__ == '__main__':
ctx = mp.get_context('spawn')
q = ctx.Queue()
p = ctx.Process(target=foo, args=(q,'hello', 'world'))
p.start()
print(q.get())
p.join()
Or you just simply replace
pool.map(harvester(text,case),case, 1)
by:
pool.apply_async(harvester(text,case),case, 1)
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
Try to just use isNotNull function.
df.filter(df.dt_mvmt.isNotNull()).count()
You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example
angular.module('myModule', [])
.filter('split', function() {
return function(input, splitChar, splitIndex) {
// do some bounds checking here to ensure it has that index
return input.split(splitChar)[splitIndex];
}
});
From here, you can use a filter as you originally intended
{{test | split:',':0}}
{{test | split:',':0}}
More info at http://docs.angularjs.org/guide/filter (thanks ross)
Plunkr @ http://plnkr.co/edit/NA4UeL
This is a modern approach and it utilizes the CSS Flexbox functionality.
You can now vertically align the content within your parent container by just adding these styles to the .main
container
.main {
display: flex;
flex-direction: column;
justify-content: center;
}
And you are good to go!
I encountered the same issue. This worked:
>>> import pkg_resources
>>> pkg_resources.require("google-api-python-client")
[google-api-python-client 1.5.3 (c:\python27), uritemplate 0.6 (c:\python27\lib\site-packages\uritemplate-0.6-py2.7.egg), six 1.10.0 (c:\python27\lib\site-packages\six-1.10.0-py2.7.egg), oauth2client 3.0.0 (c:\python27\lib\site-packages\oauth2client-3.0.0-py2.7.egg), httplib2 0.9.2 (c:\python27\lib\site-packages\httplib2-0.9.2-py2.7.egg), simplejson 3.8.2 (c:\python27\lib\site-packages\simplejson-3.8.2-py2.7-win32.egg), six 1.10.0 (c:\python27\lib\site-packages\six-1.10.0-py2.7.egg), rsa 3.4.2 (c:\python27\lib\site-packages\rsa-3.4.2-py2.7.egg), pyasn1-modules 0.0.8 (c:\python27\lib\site-packages\pyasn1_modules-0.0.8-py2.7.egg), pyasn1 0.1.9 (c:\python27\lib\site-packages\pyasn1-0.1.9-py2.7.egg)]
>>> from apiclient.discovery import build
>>>
ul>li
selects all li
that are a direct child of ul
whereas ul li
selects all li
that are anywhere within (descending as deep as you like) a ul
For HTML:
<ul>
<li><span><a href='#'>Something</a></span></li>
<li><a href='#'>or Other</a></li>
</ul>
And CSS:
li a{ color: green; }
li>a{ color: red; }
The colour of Something
will remain green but or Other
will be red
Part 2, you should write the rule to be appropriate to the situation, I think the speed difference would be incredibly small, and probably overshadowed by the extra characters involved in writing more code, and definitely overshadowed by the time taken by the developer to think about it.
However, as a rule of thumb, the more specific you are with your rules, the faster the CSS engines can locate the DOM elements you want to apply it to, so I expect li>a
is faster than li a
as the DOM search can be cut short earlier. It also means that nested anchors are not styled with that rule, is that what you want? <~~ much more pertinent question.
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
You can achieve your goal by using php date() & explode() functions:
$date = date("2068-06-15");
$date_arr = explode("-", $date);
$yr = $date_arr[0];
echo $yr;
That is it. Happy coding :)
Set Body as raw and form the array as follows:
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = @"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)
You can get div content using .text()
in jquery
var divContent = $('#field-function_purpose').text();
console.log(divContent);
I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):
>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'
Doing it in a Django template's more finicky, since the time
filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:
>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
... tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))
u'03:25:45'
Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.
I find it important to note that python 3 defines the opening modes differently to the answers here that were correct for Python 2.
The Pyhton 3 opening modes are:
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
----
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (for backwards compatibility; should not be used in new code)
The modes r
, w
, x
, a
are combined with the mode modifiers b
or t
. +
is optionally added, U
should be avoided.
As I found out the hard way, it is a good idea to always specify t
when opening a file in text mode since r
is an alias for rt
in the standard open()
function but an alias for rb
in the open()
functions of all compression modules (when e.g. reading a *.bz2
file).
Thus the modes for opening a file should be:
rt
/ wt
/ xt
/ at
for reading / writing / creating / appending to a file in text mode and
rb
/ wb
/ xb
/ ab
for reading / writing / creating / appending to a file in binary mode.
Use +
as before.
This eclipse documentation has details on the markups in .project
file: The project description file
It describes the .project
file as:
When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"
You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode
Edit: in case something happens to kill the msdn link, here is the content:
Specifying Document Compatibility Modes
You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.
<html> <head> <!-- Enable IE9 Standards mode --> <meta http-equiv="X-UA-Compatible" content="IE=9" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.
The following example specifies EmulateIE7 mode.
<html> <head> <!-- Mimic Internet Explorer 7 --> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" > <title>My webpage</title> </head> <body> <p>Content goes here.</p> </body> </html>
In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.
You have to define public String toString()
method in your Student
class. For example:
public String toString() {
return "Student: " + studentName + ", " + studentNo;
}
AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously. Unfortunately I don't remember in what version exactly they changed that.
UPDATE:
Here is what current (2012-01-27) API says on this:
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. After HONEYCOMB, it is planned to change this back to a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use.
DONUT is Android 1.6, HONEYCOMB is Android 3.0.
UPDATE: 2
See the comment by kabuko
from Mar 7 2012 at 1:27
.
It turns out that for APIs where "a pool of threads allowing multiple tasks to operate in parallel" is used (starting from 1.6 and ending on 3.0) the number of simultaneously running AsyncTasks depends on how many tasks have been passed for execution already, but have not finished their doInBackground()
yet.
This is tested/confirmed by me on 2.2. Suppose you have a custom AsyncTask that just sleeps a second in doInBackground()
. AsyncTasks use a fixed size queue internally for storing delayed tasks. Queue size is 10 by default. If you start 15 your custom tasks in a row, then first 5 will enter their doInBackground()
, but the rest will wait in a queue for a free worker thread. As soon as any of the first 5 finishes, and thus releases a worker thread, a task from the queue will start execution. So in this case at most 5 tasks will run simultaneously. However if you start 16 your custom tasks in a row, then first 5 will enter their doInBackground()
, the rest 10 will get into the queue, but for the 16th a new worker thread will be created so it'll start execution immediately. So in this case at most 6 tasks will run simultaneously.
There is a limit of how many tasks can be run simultaneously. Since AsyncTask
uses a thread pool executor with limited max number of worker threads (128) and the delayed tasks queue has fixed size 10, if you try to execute more than 138 your custom tasks the app will crash with java.util.concurrent.RejectedExecutionException
.
Starting from 3.0 the API allows to use your custom thread pool executor via AsyncTask.executeOnExecutor(Executor exec, Params... params)
method. This allows, for instance, to configure the size of the delayed tasks queue if default 10 is not what you need.
As @Knossos mentions, there is an option to use AsyncTaskCompat.executeParallel(task, params);
from support v.4 library to run tasks in parallel without bothering with API level. This method became deprecated in API level 26.0.0.
UPDATE: 3
Here is a simple test app to play with number of tasks, serial vs. parallel execution: https://github.com/vitkhudenko/test_asynctask
UPDATE: 4 (thanks @penkzhou for pointing this out)
Starting from Android 4.4 AsyncTask
behaves differently from what was described in UPDATE: 2 section. There is a fix to prevent AsyncTask
from creating too many threads.
Before Android 4.4 (API 19) AsyncTask
had the following fields:
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(10);
In Android 4.4 (API 19) the above fields are changed to this:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
This change increases the size of the queue to 128 items and reduces the maximum number of threads to the number of CPU cores * 2 + 1. Apps can still submit the same number of tasks.
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. v = (float)s / t;
2. v = (float)s / (float)t;
Checked exceptions are checked at compile time by the JVM and its related to resources(files/db/stream/socket etc). The motive of checked exception is that at compile time if the resources are not available the application should define an alternative behaviour to handle this in the catch/finally block.
Unchecked exceptions are purely programmatic errors, wrong calculation, null data or even failures in business logic can lead to runtime exceptions. Its absolutely fine to handle/catch unchecked exceptions in code.
Explanation taken from http://coder2design.com/java-interview-questions/
If you are Struggling with addToBackStack() & popBackStack() then simply use
FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "Home");
ft.commit();`
In your Activity In OnBackPressed() find out fargment by tag and then do your stuff
Fragment home = getSupportFragmentManager().findFragmentByTag("Home");
if (home instanceof HomeFragment && home.isVisible()) {
// do you stuff
}
For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string s1="split on whitespace";
istringstream iss(s1);
vector<string> result;
for(string s;iss>>s;)
result.push_back(s);
int n=result.size();
for(int i=0;i<n;i++)
cout<<result[i]<<endl;
return 0;
}
Output:-
split
on
whitespace
Nesting Text components is not possible now, but you can wrap your text in a View like this:
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Text>
{'Hello '}
</Text>
<Text style={{fontWeight: 'bold'}}>
{'this is a bold text '}
</Text>
<Text>
and this is not
</Text>
</View>
I used the strings inside the brackets to force the space between words, but you can also achieve it with marginRight or marginLeft. Hope it helps.
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
As @NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
Try to fill only the HTTP schema
There is a python package for this Autopy
The bitmap module can to screen grabbing (bitmap.capture_screen) It is multiplateform (Windows, Linux, Osx).
I don't think location.LatLng
is working, however this works:
results[0].geometry.location.lat(), results[0].geometry.location.lng()
Found it while exploring Get Lat Lon source code.
To select the node's contents call:
window.getSelection().selectAllChildren(
document.getElementById(id)
);
This works on all modern browsers including IE9+ (in standards mode).
function select(id) {_x000D_
window.getSelection()_x000D_
.selectAllChildren(_x000D_
document.getElementById("target-div") _x000D_
);_x000D_
}
_x000D_
#outer-div { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button { margin: 1rem; }
_x000D_
<div id="outer-div">_x000D_
<div id="target-div">_x000D_
Some content for the _x000D_
<br>Target DIV_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
_x000D_
The original answer below is obsolete since window.getSelection().addRange(range);
has been deprecated
All of the examples above use:
var range = document.createRange();
range.selectNode( ... );
but the problem with that is that it selects the Node itself including the DIV tag etc.
To select the Node's text as per the OP question you need to call instead:
range.selectNodeContents( ... )
So the full snippet would be:
function selectText( containerid ) {
var node = document.getElementById( containerid );
if ( document.selection ) {
var range = document.body.createTextRange();
range.moveToElementText( node );
range.select();
} else if ( window.getSelection ) {
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
}
}
Open notepad and paste this code:
@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c %*'"
@echo on
Then, save the file as sudo.cmd
. Copy this file and paste it at C:\Windows\System32
or add the path where sudo.cmd
is to your PATH Environment Variable.
When you open command prompt, you can now run something like sudo start .
.
If you want the terminal window to stay open when you run the command, change the code in notepad to this:
@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k %*'"
@echo on
Explanation:
powershell -Command
runs a powershell command.
Start-Process
is a powershell command that starts a process, in this case, command prompt.
-Verb RunAs
runs the command as admin.
-Argument-List
runs the command with arguments.
Our arguments are '/c %*'
. %*
means all arguments, so if you did sudo foo bar
, it would run in command prompt foo bar
because the parameters are foo and bar, and %*
returns foo bar
.
The /c
is a cmd parameter for closing the window after the command is finished, and the /k
is a cmd parameter for keeping the window open.
Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.
I use the same code doing that all the time, so added a simple jquery plugin doing it. 480 bytes long, and fast. Only bound elements analyzed in runtime.
https://www.npmjs.com/package/jquery-on-scrolled-to
It will be
$('#scroll-to').onScrolledTo(0, function() {
alert('you have scrolled to the h1!');
});
or use 0.5 instead of 0 if need to alert when half of the h1 shown.
Start Visual Studio. Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.
You should see:
$(WindowsSdkDir)\include
If this is missing, you found a problem. If not, search for a file. It should be located in
32 bit systems:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include
64 bit systems:
C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\Include
if VS was installed in the default directory.
Neither Project/Properties/Javadoc Location nor Project/Properties/Java Build Path/Libraries had not helped me until I picked and moved up in "Order and Export" tab of "Java Build Path" "Android Dependencies" and added-in-library.jar. I hope it will be useful.
I would like to show you the way I access IISExpress Web APIs from my Android Emulator. I'm using Visual Studio 2015. And I call the Android Emulator from Android Studio.
All of what I need to do is adding the following line to the binding configuration in my applicationhost.config file
<binding protocol="http" bindingInformation="*:<your-port>:" />
Then I check and use the IP4 Address to access my API from Android emulator
Requirement: you must run Visual Studio as Administrator. This post gives a perfect way to do this.
For more details, please visit my post on github
Hope this helps.
I agree with previous opinions. It is good to say, that if you are going to share DbContext in single thread app, you'll need more memory. For example my web application on Azure (one extra small instance) needs another 150 MB of memory and I have about 30 users per hour.
Here is real example image: application have been deployed in 12PM
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
Try -webkit-font-smoothing: subpixel-antialiased;
If speed and low memory usage are important, do something like this:
var sb = new StringBuilder(s.Length);
foreach (char i in s)
if (i != '\n' && i != '\r' && i != '\t')
sb.Append(i);
s = sb.ToString();
Finally below works for me
$("#priceSlider").slider('option',{min: 5, max: 20,value:[6,19]}); $("#priceSlider").slider("refresh");
@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).
In my case I needed to force content-type: text/plain to be parsed as json.
If you cannot change the content-type of the request, try using the following code:
app.use(express.json({type: '*/*'}));
Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:
app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
// echo json
res.json(req.body);
});
You can stop the 2-line separation in the output by using
with open('t.ini') as f:
for line in f:
print line.strip()
if 'str' in line:
break
You can also use this
document.querySelector('yourId').innerHTML = 'Content';
First Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create a pointer that points to random memory address
*ptr = 20; //Dereference that pointer,
// and assign a value to random memory address.
//Depending on external (not inside your program) state
// this will either crash or SILENTLY CORRUPT another
// data structure in your program.
printf("%d", *ptr); //Print contents of same random memory address
// May or may not crash, depending on who owns this address
return 0;
}
Second Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create pointer to random memory address
int q = 50; //Create local variable with contents int 50
ptr = &q; //Update address targeted by above created pointer to point
// to local variable your program properly created
printf("%d", *ptr); //Happily print the contents of said local variable (q)
return 0;
}
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.
public enum MyEvents
{
Event1
}
public class CustomEventArgs : EventArgs
{
public MyEvents MyEvents { get; set; }
}
private EventHandler<CustomEventArgs> onTrigger;
public event EventHandler<CustomEventArgs> Trigger
{
add
{
onTrigger += value;
}
remove
{
onTrigger -= value;
}
}
protected void OnTrigger(CustomEventArgs e)
{
if (onTrigger != null)
{
onTrigger(this, e);
}
}
It's about your way of reading it. not
operator is dynamic, that's why you are able to apply it in
if not x == 'val':
But !=
could be read in a better context as an operator which does the opposite of what ==
does.
Another workaround for those who don't need the entire shebang: use the switch
-DBOOST_ERROR_CODE_HEADER_ONLY
.
If you use CMake, it's add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)
.
I've come cross an issue with the implementation of this solution.
If you have a custom component you want to iterate through and you want to share the state it will not be available as the .map() scope does not recognize the general state() scope. I've come to this solution:
`
class RootComponent extends Component() {
constructor(props) {
....
this.customFunction.bind(this);
this.state = {thisWorks: false}
this.that = this;
}
componentDidMount() {
....
}
render() {
let array = this.thatstate.map(() => {
<CustomComponent that={this.that} customFunction={this.customFunction}/>
});
}
customFunction() {
this.that.setState({thisWorks: true})
}
}
class CustomComponent extend Component {
render() {
return <Button onClick={() => {this.props.customFunction()}}
}
}
In constructor bind without this.that
Every use of any function/method inside the root component should be used with this.that
You don't need to convert NumPy
array to Mat
because OpenCV cv2
module can accept NumPy
array.
The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy
array is equal to 255. So you should divide by 255 in your code, as shown below.
img = numpy.zeros([5,5,3])
img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0
cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()
An activity populates the ActionBar in its onCreateOptionsMenu()
method.
Instead of using setcustomview()
, just override onCreateOptionsMenu
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected()
method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
Just to throw my hat in the race, here's my proposal:
function getCookie(name) {
const cookieDict = document.cookie.split(';')
.map((x)=>x.split('='))
.reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
return cookieDict[name];
}
The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict
), and afterwards accesses the property name
to retrieve the cookie.
This could effectively be expressed as a one-liner, but this is only for the brave:
document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]
The absolute best approach would be to generate cookieDict
at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename']
.
A very simple example of a swing component to draw lines. It keeps internally a list with the lines that have been added with the method addLine. Each time a new line is added, repaint is invoked to inform the graphical subsytem that a new paint is required.
The class also includes some example of usage.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LinesComponent extends JComponent{
private static class Line{
final int x1;
final int y1;
final int x2;
final int y2;
final Color color;
public Line(int x1, int y1, int x2, int y2, Color color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}
}
private final LinkedList<Line> lines = new LinkedList<Line>();
public void addLine(int x1, int x2, int x3, int x4) {
addLine(x1, x2, x3, x4, Color.black);
}
public void addLine(int x1, int x2, int x3, int x4, Color color) {
lines.add(new Line(x1,x2,x3,x4, color));
repaint();
}
public void clearLines() {
lines.clear();
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
g.setColor(line.color);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
}
public static void main(String[] args) {
JFrame testFrame = new JFrame();
testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final LinesComponent comp = new LinesComponent();
comp.setPreferredSize(new Dimension(320, 200));
testFrame.getContentPane().add(comp, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
JButton newLineButton = new JButton("New Line");
JButton clearButton = new JButton("Clear");
buttonsPanel.add(newLineButton);
buttonsPanel.add(clearButton);
testFrame.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
newLineButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int x1 = (int) (Math.random()*320);
int x2 = (int) (Math.random()*320);
int y1 = (int) (Math.random()*200);
int y2 = (int) (Math.random()*200);
Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
comp.addLine(x1, y1, x2, y2, randomColor);
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
comp.clearLines();
}
});
testFrame.pack();
testFrame.setVisible(true);
}
}
var DepartmentFactory = function(data) {
this.id = data.Id;
this.name = data.DepartmentName;
this.active = data.Active;
}
var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));
console.log(objArray.sort(function(a, b) { return a.name > b.name}));
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
It is possible to have hierarchical branch names (branch names with slash). For example in my repository I have such branch(es). One caveat is that you can't have both branch 'foo' and branch 'foo/bar' in repository.
Your problem is not with creating branch with slash in name.
$ git branch foo/bar error: unable to resolve reference refs/heads/labs/feature: Not a directory fatal: Failed to lock ref for update: Not a directory
The above error message talks about 'labs/feature' branch, not 'foo/bar' (unless it is a mistake in copy'n'paste, i.e you edited parts of session). What is the result of git branch
or git rev-parse --symbolic-full-name HEAD
?
In my case, the server had been disabled in the domain controller. I went into the COMPUTERS OU in Active directory, right-clicked on the server,enabled it, then did a gpupdate /force from the SQL server. It took a moment, but it finally worked.
It's not working because the entire for
loop (from the for
to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count%
is replaced with its value 1
before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using !
instead of %
will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal
actually limit scope of things changed inside so that they don't leak out. If you want to use count
after the endlocal
, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count
has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count
to it's original value. But, since the setting of count
to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate
. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:
componentDidUpdate() {_x000D_
let panel, node;_x000D_
if (this.refs.selectedSection && this.refs.selectedItem) {_x000D_
// This is the container you want to scroll. _x000D_
panel = this.refs.listPanel;_x000D_
// This is the element you want to make visible w/i the container_x000D_
// Note: You can nest refs here if you want an item w/i the selected item _x000D_
node = ReactDOM.findDOMNode(this.refs.selectedItem);_x000D_
}_x000D_
_x000D_
if (panel && node &&_x000D_
(node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {_x000D_
panel.scrollTop = node.offsetTop - panel.offsetTop;_x000D_
}_x000D_
}
_x000D_
For those who are using Eclipse IDE.
After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,
You will need to tell Eclipse IDE about the following
Here is how you go about it.
To Add mysql.h
1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql
To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.
2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient
3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.
Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql
I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.
So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.
In short: what you are looking for cannot be done legally within the structure of the syntax.
Source: W3 Validator
Simple way to do it for html5 in css:
td img{
display: block;
margin-left: auto;
margin-right: auto;
}
Worked for me perfectly.
If you have Excel 2007 or later use COUNTIFS
with an "S" on the end, i.e.
=COUNTIFS(B2:B292,">10",B2:B292,"<10000")
You may need to change commas , to semi-colons ;
In earlier versions of excel use SUMPRODUCT
like this
=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))
Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=
Both std::string
and std::vector<T>
have constructors initializing the object to be empty. You could use std::vector<unsigned char>()
but I'd remove the initializer.
One disadvantage is that you will be designing around an unpredictable variable, and you will probably ignore instead of take advantage of the internal SQL Server data structure, progressively made up of Row(s), Page(s), and Extent(s).
Which makes me think about data structure alignment in C, and that being aware of the alignment is generally considered to be a Good Thing (TM). Similar idea, different context.
MSDN page for Pages and Extents
MSDN page for Row-Overflow Data
In Embedded Jetty I managed to achieve something similar by adding a mapping for the "css" directory in web.xml. Explicitly telling it to use DefaultServlet:
<servlet>
<servlet-name>DefaultServlet</servlet-name>
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DefaultServlet</servlet-name>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>
This is a method that uses a FileUpload control in asp.net:
byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.
Add
PRINT 'Hardcoded table name -' + CAST(@@RowCount as varchar(10))
immediately after the query.
Go with the mouse to the Windows Icon (lower left) and start typing "Anaconda". There should show up some matching entries. Select "Anaconda Prompt". A new command window, named "Anaconda Prompt" will open. Now, you can work from there with Python, conda and other tools.
If you actually have a database, this is the most-simple way:
var lsPetOwners = ( from person in context.People
from pets in context.Pets
.Where(mypet => mypet.Owner == person.ID)
.DefaultIfEmpty()
select new { OwnerName = person.Name, Pet = pets.Name }
).ToList();
Why not using indexOf
from array like bellow?
if ([foo, bar].indexOf(foobar) !== -1) {
// do something
}
Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.
The command select username from all_users;
requires less privileges
Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node.js.
Frameworks built on Express.
Several popular Node.js frameworks are built on Express:
LoopBack: Highly-extensible, open-source Node.js framework for quickly creating dynamic end-to-end REST APIs.
Sails: MVC framework for Node.js for building practical, production-ready apps.
Kraken: Secure and scalable layer that extends Express by providing structure and convention.
MEAN: Opinionated fullstack JavaScript framework that simplifies and accelerates web application development.
Express adds dead simple routing and support for Connect middleware, allowing many extensions and useful features.
For example,
public async Task<List<TimeAndAttendanceShift>> FindEntitiesByExpression(Expression<Func<TimeAndAttendanceShift, bool>> predicate)
{
IList<TimeAndAttendanceShift> result = await _dbContext.Set<TimeAndAttendanceShift>().Where(predicate).ToListAsync<TimeAndAttendanceShift>();
return result.ToList<TimeAndAttendanceShift>();
}
Ok now I've done my research, here is the deal:
In TDS protocol, SET NOCOUNT ON
only saves 9-bytes per query while the text "SET NOCOUNT ON" itself is a whopping 14 bytes. I used to think that 123 row(s) affected
was returned from server in plain text in a separate network packet but that's not the case. It's in fact a small structure called DONE_IN_PROC
embedded in the response. It's not a separate network packet so no roundtrips are wasted.
I think you can stick to default counting behavior almost always without worrying about the performance. There are some cases though, where calculating the number of rows beforehand would impact the performance, such as a forward-only cursor. In that case NOCOUNT might be a necessity. Other than that, there is absolutely no need to follow "use NOCOUNT wherever possible" motto.
Here is a very detailed analysis about insignificance of SET NOCOUNT
setting: http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = prestListView.getItemAtPosition(position);
prestationEco str = (prestationEco)o; //As you are using Default String Adapter
Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
}
});
Type the following command to import sql data file:
$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
In this example, import 'data.sql' file into 'blog' database using vivek as username:
$ mysql -u vivek -p -h localhost blog < data.sql
If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:
$ mysql -u username -p -h 202.54.1.10 databasename < data.sql
To export a database, use the following:
mysqldump -u username -p databasename > filename.sql
Note the <
and >
symbols in each case.
In the end I solved it by using JSONObject.get
rather than JSONObject.getString
and then cast test
to a String
.
private void saveData(String result) {
try {
JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
JSONObject json2 = json.getJSONObject("results");
test = (String) json2.get("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
From the MySQL-manual:
This is equivalent to the expression (min <= expr AND expr <= max)
Hi I found the easiest way to do this.
Done!
you just provide one <folder>
argument to npm install
, argument should point toward the local folder instead of the package name:
npm install /path
Escape it. The pipe symbol is one that has been handled differently over time and between browsers. For instance, Chrome and Firefox convert a URL with pipe differently when copy/paste them. However, the most compatible, and necessary with Tomcat 8.5 it seems, is to escape it:
If you want to pass in an array of Doctrine entities, try something like this (Symfony 3.0+):
protected $entities;
protected $selectedEntities;
public function __construct($entities = null, $selectedEntities = null)
{
$this->entities = $entities;
$this->selectedEntities = $selectedEntities;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('entities', 'entity', [
'class' => 'MyBundle:MyEntity',
'choices' => $this->entities,
'property' => 'id',
'multiple' => true,
'expanded' => true,
'data' => $this->selectedEntities,
]);
}
If you are on the same timezone
Convert GPS to UTM
http://www.ibm.com/developerworks/java/library/j-coordconvert/ http://stackoverflow.com/questions/176137/java-convert-lat-lon-to-utm
UTM coordinates get you a simples X Y 2D
Calculate the angle between both UTM locations
http://forums.groundspeak.com/GC/index.php?showtopic=146917
This gives the direction as if you were looking north
So whatever you rotate related do North just subtract this angle
If both point have a UTM 45º degree angle and you are 5º east of north, your arrow will point to 40º of north
Set up a virtualenv:
% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py
% sudo python /tmp/get-pip.py
These commands install pip into the global site-packages directory.
% sudo pip install virtualenv
and ditto for virtualenv:
% mkdir -p ~/.virtualenvs
I like my virtualenvs under one tree in my home directory called .virtualenvs
% virtualenv ~/.virtualenvs/lxmltest
Creates a virtualenv.
% . ~/.virtualenvs/lxmltest/bin/activate
Removes the need to specify the full path to pip/python in this virtualenv.
% pip install lxml
Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml
if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest
and start again from a new virtualenv.
The same error here. I fixed this, using "module": "ES6" in tsconfig.
This awnser solved my problem. Below is a copy of it:
Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM defaults to the operating system charset
This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.
In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.
1.Added these codes to your app/build.gradle:
configurations.all {
resolutionStrategy.force 'com.android.support:support-v4:26.1.0' // the lib is old dependencies version;
}
2.Modified sdk and tools version to 28:
compileSdkVersion 28
buildToolsVersion '28.0.3'
targetSdkVersion 28
2.In your AndroidManifest.xml file, you should add two line:
<application
android:name=".YourApplication"
android:appComponentFactory="anystrings be placeholder"
tools:replace="android:appComponentFactory"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:largeHeap="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
Thanks for the answer @Carlos Santiago : Android design support library for API 28 (P) not working
There are a bunch of different ways depending on how far along you are and which branch(es) you want them on.
Let's take a classic mistake:
$ git checkout master
... pause for coffee, etc ...
... return, edit a bunch of stuff, then: oops, wanted to be on develop
So now you want these changes, which you have not yet committed to master
, to be on develop
.
If you don't have a develop
yet, the method is trivial:
$ git checkout -b develop
This creates a new develop
branch starting from wherever you are
now. Now you can commit and the new stuff is all on develop
.
You do have a develop
. See if Git will let you switch without
doing anything:
$ git checkout develop
This will either succeed, or complain. If it succeeds, great! Just
commit. If not (error: Your local changes to the following files would be overwritten ...
), you still have lots of options.
The easiest is probably git stash
(as all the other answer-ers
that beat me to clicking post said). Run git stash save
or git stash push
,1 or just plain git stash
which is short for save
/ push
:
$ git stash
This commits your code (yes, it really does make some commits) using a weird non-branch-y method. The commits it makes are not "on" any branch but are now safely stored in the repository, so you can now switch branches, then "apply" the stash:
$ git checkout develop
Switched to branch 'develop'
$ git stash apply
If all goes well, and you like the results, you should then git stash drop
the stash. This deletes the reference to the weird non-branch-y commits. (They're still in the repository, and can sometimes be retrieved in an emergency, but for most purposes, you should consider them gone at that point.)
The apply
step does a merge of the stashed changes, using Git's powerful underlying merge machinery, the same kind of thing it uses when you do branch merges. This means you can get "merge conflicts" if the branch you were working on by mistake, is sufficiently different from the branch you meant to be working on. So it's a good idea to inspect the results carefully before you assume that the stash applied cleanly, even if Git itself did not detect any merge conflicts.
Many people use git stash pop
, which is short-hand for git stash apply && git stash drop
. That's fine as far as it goes, but it means that if the application results in a mess, and you decide you don't want to proceed down this path, you can't get the stash back easily. That's why I recommend separate apply
, inspect results, drop
only if/when satisfied. (This does of course introduce another point where you can take another coffee break and forget what you were doing, come back, and do the wrong thing, so it's not a perfect cure.)
1The save
in git stash save
is the old verb for creating a new stash. Git version 2.13 introduced the new verb to make things more consistent with pop
and to add more options to the creation command. Git version 2.16 formally deprecated the old verb (though it still works in Git 2.23, which is the latest release at the time I am editing this).
I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.
https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886
@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo Zeichenfolge die zu suchende Zeichenfolge wird mit FIND bestimmt
echo ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^
^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1
:Eingabe temporär speichern
>"%intemp%" find /n /v ""
:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr
:end
del "%intemp%"
exit /b %xcode%
:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^
^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
setlocal enabledelayedexpansion
for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
set "Lineout=!LineStr:~0,%%n!!string!"
echo(!Lineout:*]=!
exit /b
)
) )
exit /b
:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout% exit /b
set "Line=%%i"
setlocal enabledelayedexpansion
echo(!Line:*]=!
endlocal
)
exit /b
@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo Zeichenfolge String zum Durchsuchen
echo B Zeichen Wonach am Anfang gesucht wird
echo n Auszulassende Zeichenanzahl
echo E Zeichen was das Ende der Zeichen Bestimmt
echo /i Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set "Original=%~1"
set "Begin=%~2"
set /a Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set "CaseInt=%~5"
:: end Setting Input Param
set "out="
set "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
if defined out exit /b 0
for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
set "out=1"
setlocal enabledelayedexpansion
set "In= !Original!"
set "In=!In:~,%%a!"
echo !In:^~2!
endlocal
) )
if not defined out exit /b 1
exit /b
::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)
$('#runnerquery').typeahead({
source: function (query, result) {
$.ajax({
url: "db.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
},
updater: function (item) {
//selectedState = map[item].stateCode;
// Here u can obtain the selected suggestion from the list
alert(item);
}
});
//Db.php file
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'TableName');
$sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$Resut[] = $row["name"];
}
echo json_encode($Result);
}
$conn->close();
?>
I know this has already been answered. But I would like to add my solution as it may helpful for others in the future..
A common key error is: Permission denied (publickey)
. You can fix this by using keys:add
to notify Heroku of your new key.
In short follow these steps: https://devcenter.heroku.com/articles/keys
First you have to create a key if you don't have one:
ssh-keygen -t rsa
Second you have to add the key to Heroku:
heroku keys:add
I have Wondows 7 64 bit (MacBook Pro), installed both Java JDK x86 and x64 with JAVA_HOME
pointing at x32 during installation of Android SDK, later after installation JAVA_HOME
pointing at x64.
My problem was that Android SDK manager didn't launch, cmd window just flashes for a second and that's it. Like many others looked around and tried many suggestions with no juice!
My solution was in adding bin the JAVA_HOME
path:
C:\Program Files\Java\jdk1.7.0_09\bin
instead of what I entered for the start:
C:\Program Files\Java\jdk1.7.0_09
Hope this helps others.... good luck!
I just had this problem. This is what worked for me:
pip install botocore==1.13.20
you could use this
curl_setopt($curl->curl, CURLOPT_SSL_VERIFYPEER, false);
To build further upon the ajax part which you may or may not use (from the comments)
a simple way to load another page and replace it with your current one is:
<script>
$(document).ready( function() {
$.ajax({
type: 'get',
url: 'http://pageToLoad.from',
success: function(response) {
// response = data which has been received and passed on to the 'success' function.
$('body').html(response);
}
});
});
<script>
You need to use the LAST_INSERT_ID() function with transaction:
START TRANSACTION;
INSERT INTO dog (name, created_by, updated_by) VALUES ('name', 'migration', 'migration');
SELECT LAST_INSERT_ID();
COMMIT;
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
This function will be return last inserted primary key in table.
You should use:
[UIApplication sharedApplication].window.rootViewController;
When there is a uiactionsheet on [UIApplication sharedApplication].keyWindow
, it is not right to use keyWindow as mentioned in this answer.
As stated by Maxim Dounin in the comments above:
When nginx returns 400 (Bad Request) it will log the reason into error log, at "info" level. Hence an obvious way to find out what's going on is to configure error_log to log messages at "info" level and take a look into error log when testing.
The most portable solution is just to read the file in chunks, and then write the data out to the socket, in a loop (and likewise, the other way around when receiving the file). You allocate a buffer, read
into that buffer, and write
from that buffer into your socket (you could also use send
and recv
, which are socket-specific ways of writing and reading data). The outline would look something like this:
while (1) {
// Read data into buffer. We may not have enough to fill up buffer, so we
// store how many bytes were actually read in bytes_read.
int bytes_read = read(input_file, buffer, sizeof(buffer));
if (bytes_read == 0) // We're done reading from the file
break;
if (bytes_read < 0) {
// handle errors
}
// You need a loop for the write, because not all of the data may be written
// in one call; write will return how many bytes were written. p keeps
// track of where in the buffer we are, while we decrement bytes_read
// to keep track of how many bytes are left to write.
void *p = buffer;
while (bytes_read > 0) {
int bytes_written = write(output_socket, p, bytes_read);
if (bytes_written <= 0) {
// handle errors
}
bytes_read -= bytes_written;
p += bytes_written;
}
}
Make sure to read the documentation for read
and write
carefully, especially when handling errors. Some of the error codes mean that you should just try again, for instance just looping again with a continue
statement, while others mean something is broken and you need to stop.
For sending the file to a socket, there is a system call, sendfile
that does just what you want. It tells the kernel to send a file from one file descriptor to another, and then the kernel can take care of the rest. There is a caveat that the source file descriptor must support mmap
(as in, be an actual file, not a socket), and the destination must be a socket (so you can't use it to copy files, or send data directly from one socket to another); it is designed to support the usage you describe, of sending a file to a socket. It doesn't help with receiving the file, however; you would need to do the loop yourself for that. I cannot tell you why there is a sendfile
call but no analogous recvfile
.
Beware that sendfile
is Linux specific; it is not portable to other systems. Other systems frequently have their own version of sendfile
, but the exact interface may vary (FreeBSD, Mac OS X, Solaris).
In Linux 2.6.17, the splice
system call was introduced, and as of 2.6.23 is used internally to implement sendfile
. splice
is a more general purpose API than sendfile
. For a good description of splice
and tee
, see the rather good explanation from Linus himself. He points out how using splice
is basically just like the loop above, using read
and write
, except that the buffer is in the kernel, so the data doesn't have to transferred between the kernel and user space, or may not even ever pass through the CPU (known as "zero-copy I/O").
DB Browser for SQLite allows you to add or drop columns.
In the main view, tab Database Structure, click on the table name. A button Modify Table gets enabled, which opens a new window where you can select the column/field and remove it.
What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/
Although an elegant and very pythonic answer has been selected I would present my solution just for the review:
def flat(l):
ret = []
for i in l:
if isinstance(i, list) or isinstance(i, tuple):
ret.extend(flat(i))
else:
ret.append(i)
return ret
Please tell how good or bad this code is?
First, double check that the branch has been actually pushed remotely, by using the command git ls-remote origin
. If the new branch appears in the output, try and give the command git fetch
: it should download the branch references from the remote repository.
If your remote branch still does not appear, double check (in the ls-remote
output) what is the branch name on the remote and, specifically, if it begins with refs/heads/
. This is because, by default, the value of remote.<name>.fetch
is:
+refs/heads/*:refs/remotes/origin/*
so that only the remote references whose name starts with refs/heads/
will be mapped locally as remote-tracking references under refs/remotes/origin/
(i.e., they will become remote-tracking branches)
One easy solution is to use delayed expansion, as this doesn't change any special characters.
set "line=<?xml version="1.0" encoding="utf-8" ?>"
setlocal EnableDelayedExpansion
(
echo !line!
) > myfile.xml
EDIT : Another solution is to use a disappearing quote.
This technic uses a quotation mark to quote the special characters
@echo off
setlocal EnableDelayedExpansion
set ""="
echo !"!<?xml version="1.0" encoding="utf-8" ?>
The trick works, as in the special characters phase the leading quotation mark in !"!
will preserve the rest of the line (if there aren't other quotes).
And in the delayed expansion phase the !"!
will replaced with the content of the variable "
(a single quote is a legal name!).
If you are working with disabled delayed expansion, you could use a FOR /F
loop instead.
for /f %%^" in ("""") do echo(%%~" <?xml version="1.0" encoding="utf-8" ?>
But as the seems to be a bit annoying you could also build a macro.
set "print=for /f %%^" in ("""") do echo(%%~""
%print%<?xml version="1.0" encoding="utf-8" ?>
%print% Special characters like &|<>^ works now without escaping
You can run using the following command. Here I want to run using spring profile local
:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"
If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?
import copy
x = SimpleClass()
for count in range(0,4):
y = copy.deepcopy(x)
(...)
y.attr1= '*Bob* '* count
A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation: https://docs.python.org/2/library/copy.html
I've used this solution to get what you need.
Let'say that in my .aspx code there's a select list runat="server":
<select id="testSelect" runat="server" ClientIDMode="Static" required>
<option value="1">One</option>
<option value="2">Two</option>
</select>
In my C# code I used the code below to retrieve the text and also value of the options:
testSelect.SelectedIndex == 0 ? "uninformed" :
testSelect.Items[testSelect.SelectedIndex].Text);
In this case I check if the user selected any of the options. If there's nothing selected I show the text as "uninformed".
Use something like this to update your tomcat users.
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>
Tomcat users file is located inside conf
folder of tomcat installation.
To find the path of catalina_base you can use the command:
ps aux | grep catalina
You can find one of the values -Dcatalina.base=/usr/local/Cellar/tomcat/9.0.37/libexec
Don't forget to remove the comment lines from the tomcat-users.xml just before the start of the roles. <!-- -->
To the latest setup and information if you have installed the Android Studio (i.e. 1.5) and trying to target SDK 4.0 then you may not be able to locate and setup the and AVD Emulator with SDK-vX.XX (with Google API's).
See following steps in order to download the required library and start with that. AVD Emulator setup -setting up Emulator for SDK4.0 with GoogleAPI so Map application can work- In Android Studio
But unfortunately above method did not work well on my side. And was not able to created Emulator with API Level 17 (SDK 4.2). So I followed this post that worked on my side well. The reason seems that the Android Studio Emulator creation window has limited options/features.
Google Play Services in emulator, implementing Google Plus login button etc
Simply replacing .bin with .tar.bz2 is not enough, for NDK releases older than 10b. For example, https://dl.google.com/android/ndk/android-ndk-r10b-linux-x86_64.tar.bz2 is not a valid link.
Turned out that the correct link for 10b was: https://dl.google.com/android/ndk/android-ndk32-r10b-linux-x86_64.tar.bz2 (note the additional '32'). However, this doesn't seem to apply to e.g. 10a, as this link doesn't work: https://dl.google.com/android/ndk/android-ndk32-r10a-linux-x86_64.tar.bz2 .
Bottom line: use http://web.archive.org until Google fixes this, if ever...
Let's say you have a string:
var string = "potatoes + carrots"
And you want to replace the word "potatoes" in that string with "tomatoes"
string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)
If you print your string, it will now be: "tomatoes + carrots"
If you want to remove the word potatoes from the sting altogether, you can use:
string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)
If you want to use some other characters in your sting, use:
- Null Character (\0)
- Backslash (\)
- Horizontal Tab (\t)
- Line Feed (\n)
- Carriage Return (\r)
- Double Quote (\")
- Single Quote (\')
Example:
string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)
Output: "dog's toys + carrots"
Run
npm i @types/jquery
npm install -D @types/bootstrap
in the project to add the jquery types in your Angular Project. After that include
import * as $ from "jquery";
import * as bootstrap from "bootstrap";
in your app.module.ts
Add
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your index.html just before the body closing tag.
And if you are running Angular 2-7 include "jquery" in the types field of tsconfig.app.json file.
This will remove all error of 'modal' and '$' in your Angular project.
This one was helpful to me because I wanted to see the build targets required (and their dependencies) by the make target. I know that make targets cannot begin with a "." character. I don't know what languages are supported, so I went with egrep's bracket expressions.
cat Makefile | egrep "^[[:alnum:][:punct:]]{0,}:[[:space:]]{0,}[[:alnum:][:punct:][:space:]]{0,}$"
Considere use DataBindingComplete event for update the style. The next code change the style of the cell:
private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
}
Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:
SELECT * FROM
(SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'
Simple Right Click and go to Properties Option of any project on your Existing application and see the Application option on Left menu and then click on Application option see target Framework to see current Framework version .
If you set both left and right to zero, and left and right margins to auto you can center an absolutely positioned element.
position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;
The following are the 5 steps required:
You can find the step by step VC++ IDE screen shot at http://www.softwareandfinance.com/Visual_CPP/DLLDynamicBinding.html
Here is the code snippet:
int main()
{
/***
__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len); // used for static binding
***/
typedef bool (*GW)(char *buf, int len);
HMODULE hModule = LoadLibrary(TEXT("TestServer.DLL"));
GW GetWelcomeMessage = (GW) GetProcAddress(hModule, "GetWelcomeMessage");
char buf[128];
if(GetWelcomeMessage(buf, 128) == true)
std::cout << buf;
return 0;
}
If you are simply trying to stop people clicking and are not horrifically worried about security - I have found an absolute placed div with a z-index of 99999 sorts it fine. You can't click or access any of the content because the div is placed over it. Might be a bit simpler and is a CSS only solution until you need to remove it.
Width: 100% will break it when you view on a wider are.
Following is Bootstrap's img-responsive
max-width: 100%;
display:block;
height: auto;
You can use Symbol
var say = Symbol()
function Cat(){
this[say]() // call private methos
}
Cat.prototype[say] = function(){ alert('im a private') }
P.S. alexpods is not correct. he get protect rather than private, since inheritance is a name conflict
Actually you can use var say = String(Math.random())
instead Symbol
IN ES6:
var say = Symbol()
class Cat {
constructor(){
this[say]() // call private
}
[say](){
alert('im private')
}
}
ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(cPath, "\\", "HHTCtrlp.exe"));
startInfo.Arguments =cParams;
startInfo.UseShellExecute = false;
System.Diagnostics.Process.Start(startInfo);
I open a text editor, in my case I used Atom. Paste this code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
and save as
helloworld.js
in
c:\xampp\htdocs\myproject
directory. Next I open node.js commamd prompt enter
cd c:\xampp\htdocs\myproject
next
node helloworld.js
next I open my chrome browser and I type
http://localhost:1337
and there it is.
You need to install the Windows 10 SDK.
Visual Studio 2015 setup will start. Select "Modify".
In Visual Studio components list find "Universal Windows App Development Tools", open the list of sub-items and select "Windows 10 SDK (10.0.10240)".
Windows 10 SDK in VS 2015 Update 1 Setup
As josant already wrote - when the installation finishes you will find the SignTool.exe in the folders:
Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings
. If the file doesn't exist, create it and put on something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies>
<proxy>
<id>myproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>192.168.1.100</host>
<port>6666</port>
<username></username>
<password></password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
<profiles/>
<activeProfiles/>
</settings>
After editing the file, it's just a matter of clicking on Update Settings
button and it's done. I've just done it and it worked :)
I used it as singleton like:
public static void showSoftKeyboard(final Context context, final EditText editText) {
try {
editText.requestFocus();
editText.postDelayed(
new Runnable() {
@Override
public void run() {
InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editText, 0);
}
}
, 200);
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Use it in your activity like:
showSoftKeyboard(this, yourEditTextToFocus);
Thisd was a perfect solution for me, looking it for years:
http://css-tricks.com/forums/topic/two-column-unordered-list/
Your file .idea/workspace.xml
is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)
You can verify it using following git command, that lists all ignored files:
git ls-files --others -i --exclude-standard
The first case is done using the insert()
method:
_sb.insert(0, "Hello ");
The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:
String s2 = "Hello " + _s;
I find the following easier to reason about than other proposed solutions:
find build -not \( -path build/external -prune \) -name \*.js
# you can also exclude multiple paths
find build -not \( -path build/external -prune \) -not \( -path build/blog -prune \) -name \*.js
Important Note: the paths you type after -path
must exactly match what find
would print without the exclusion. If this sentence confuses you just make sure to use full paths through out the whole command like this: find /full/path/ -not \( -path /full/path/exclude/this -prune \) ...
. See note [1] if you'd like a better understanding.
Inside \(
and \)
is an expression that will match exactly build/external
(see important note above), and will, on success, avoid traversing anything below. This is then grouped as a single expression with the escaped parenthesis, and prefixed with -not
which will make find
skip anything that was matched by that expression.
One might ask if adding -not
will not make all other files hidden by -prune
reappear, and the answer is no. The way -prune
works is that anything that, once it is reached, the files below that directory are permanently ignored.
This comes from an actual use case, where I needed to call yui-compressor on some files generated by wintersmith, but leave out other files that need to be sent as-is.
Note [1]: If you want to exclude /tmp/foo/bar
and you run find like this "find /tmp \(...
" then you must specify -path /tmp/foo/bar
. If on the other hand you run find like this cd /tmp; find . \(...
then you must specify -path ./foo/bar
.
If your project is not AndroidX (mean Appcompat) and got this error, try to downgrade dependencies versions that triggers this error, in my case play-services-location ("implementation 'com.google.android.gms:play-services-location:17.0.0'") , I solved the problem by downgrading to com.google.android.gms:play-services-location:16.0.0'
The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy
:
static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);
This uses memcpy
under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros
concurrently, which doesn't hurt anything.
You could also use Arrays.fill
as some others have mentioned. Arrays.fill
could use memcpy
in a smart JVM, but is probably just a Java loop and the bounds checking that entails.
Benchmark your optimizations, of course.
start
did not work for me.
I used:
firefox http://www.stackoverflow.com
or
chrome http://www.stackoverflow.com
Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.