What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
What is the difference between them?
Image: the generic Linux kernel binary image file.
zImage: a compressed version of the Linux kernel image that is self-extracting.
uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.
Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:
Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.
(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)
Which type of kernel image do I have to use?
You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.
ADDENDUM
I know that u-boot needs a kernel in uImage format.
That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.
Check if you have the window var in the AppDelegate.
var window: UIWindow?
And also check the storyboard of your Info.plist file.
<key>UIMainStoryboardFile</key>
<string>Main</string>
Programmatically setting the rootViewController in the AppDelegate is not going to fix the warning. You should choose whether to let to the storyboard set the view controller or do it programmatically.
Check your folder's permission where the image is saved Right cLick on folder then go :
Properties > Security > Edit > Add-- select "everyone" and check Allow "Full Control"
For those who are trying to get an X Window application working from Windows from Linux:
What worked for me was to setup xming server on my windows machine, set X11 forwarding option in putty when I connect to the linux host and put in my windows ip address with the display port and then the display variable with my windows IP address:0.0
Dont forget to add the linux hosts IP address to the X0.hosts file to ensure that the xming server accepts traffic from that host. Took me a while to figure that out.
This assumes Eclipse and an appropriate JDK are installed on your system
array_values does the job :
$myArray = array_values($myArray);
Also some other php function do not preserve the keys, i.e. reset the index.
You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser
(man runuser
). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.
I provide a detailed answer how to use cron in this stackoverflow post.
How to write a cron that will run a script every day at midnight?
Here's a slightly more concise version of @vbem's solution:
from datetime import datetime as dt
dt.utcnow().astimezone().tzinfo
The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc)
with datetime.datetime.utcnow()
. For brevity, I also aliased datetime.datetime
as dt
.
For my purposes, I want the UTC offset in seconds. Here's what that looks like:
dt.utcnow().astimezone().utcoffset().total_seconds()
The reason why we have stdClass is because in PHP there is no way to distinguish a normal array from an associate array (like in Javascript you have {}
for object and []
for array to distinguish them).
So this creates a problem for empty objects. Take this for example.
PHP:
$a = [1, 2, 3]; // this is an array
$b = ['one' => 1, 'two' => 2]; // this is an associate array (aka hash)
$c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)
Let's assume you want to JSON encode the variable $c
echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': {one: 1, two: 2}}
Now let's say you deleted all the keys from $b
making it empty. Since $b
is now empty (you deleted all the keys remember?), it looks like []
which can be either an array or object if you look at it.
So if you do a json_encode again, the output will be different
echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': []}
This is a problem because we know b
that was supposed to be an associate array but PHP (or any function like json_encode) doesn't.
So stdClass comes to rescue. Taking the same example again
$a = [1, 2, 3]; // this is an array
$b = (object) ['one' => 1, 'two' => 2]; // this makes it an stdClass
$c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)
So now even if you delete all keys from $b
and make it empty, since it is an stdClass it won't matter and when you json_encode it you will get this:
echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': {}}
This is also the reason why json_encode
and json_decode
by default return stdClass.
$c = json_decode('{"a": [1,2,3], "b": {}}', true); //true to deocde as array
// $c is now ['a' => [1,2,3], 'b' => []] in PHP
// if you json_encode($c) again your data is now corrupted
Given a list:
var list = new List<Child>()
{
new Child()
{School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "John"},
new Child()
{School = "School2", FavoriteColor = "blue", Friend = "Bob", Name = "Pete"},
new Child()
{School = "School1", FavoriteColor = "blue", Friend = "Bob", Name = "Fred"},
new Child()
{School = "School2", FavoriteColor = "blue", Friend = "Fred", Name = "Bob"},
};
The query would look like:
var newList = list
.GroupBy(x => new {x.School, x.Friend, x.FavoriteColor})
.Select(y => new ConsolidatedChild()
{
FavoriteColor = y.Key.FavoriteColor,
Friend = y.Key.Friend,
School = y.Key.School,
Children = y.ToList()
}
);
Test code:
foreach(var item in newList)
{
Console.WriteLine("School: {0} FavouriteColor: {1} Friend: {2}", item.School,item.FavoriteColor,item.Friend);
foreach(var child in item.Children)
{
Console.WriteLine("\t Name: {0}", child.Name);
}
}
Result:
School: School1 FavouriteColor: blue Friend: Bob
Name: John
Name: Fred
School: School2 FavouriteColor: blue Friend: Bob
Name: Pete
School: School2 FavouriteColor: blue Friend: Fred
Name: Bob
Here is my modification of the currently accepted answer, which I believe it's a little faster and shorter:
private static Random random = new Random();
private string RandomString(int size) {
StringBuilder builder = new StringBuilder(size);
for (int i = 0; i < size; i++)
builder.Append((char)random.Next(0x41, 0x5A));
return builder.ToString();
}
Notice I didn't use all the multiplication, Math.floor()
, Convert
etc.
EDIT: random.Next(0x41, 0x5A)
can be changed to any range of Unicode characters.
You have to install a ProxyHandler
urllib2.install_opener(
urllib2.build_opener(
urllib2.ProxyHandler({'http': '127.0.0.1'})
)
)
urllib2.urlopen('http://www.google.com')
Format your string like so:
[# ] 1%\r
Note the \r
character. It is the so-called carriage return that will move the cursor back to the beginning of the line.
Finally, make sure you use
System.out.print()
and not
System.out.println()
There are many anwers in this question, probably all will give you the answer you are looking for. But as @TallGreenTree mentions, there is a function for this.
But the problem of the answer of @TallGreenTree is that it doesn't round up, it rounds to the nearest 10. To solve this, add +5
to your number in order to round up. If you want to round down, do -5
.
So in code:
round($num + 5, -1);
You can't use the round mode
for rounding up, because that only rounds up fractions and not whole numbers.
If you want to round up to the nearest 100
, you shoud use +50
.
The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.
e.g. Given the following assignment:
$scope.cards = {
"card2": {
values: {
opt1: 9,
opt2: 12
}
},
"card1": {
values: {
opt1: 9,
opt2: 11
}
}
};
and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">
, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.
To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.
myApp.filter('orderByValue', function () {
// custom value function for sorting
function myValueFunction(card) {
return card.values.opt1 + card.values.opt2;
}
return function (obj) {
var array = [];
Object.keys(obj).forEach(function (key) {
// inject key into each object so we can refer to it from the template
obj[key].name = key;
array.push(obj[key]);
});
// apply a custom sorting function
array.sort(function (a, b) {
return myValueFunction(b) - myValueFunction(a);
});
return array;
};
});
We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.
<ul ng-repeat="card in cards | orderByValue">
<li>{{card.name}} {{value(card)}}</li>
</ul>
Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/
Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332
This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.
When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.
As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.
Caching example:
102 [C:\Users\leeholm]
>> $r1 = [Console]::Out
103 [C:\Users\leeholm]
>> $r1
Encoding FormatProvider
-------- --------------
System.Text.SBCSCodePageEncoding en-US
104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
105 [C:\Users\leeholm]
>> $r1
Encoding FormatProvider
-------- --------------
System.Text.SBCSCodePageEncoding en-US
Just add position: fixed;
in your div style.
I have checked and Its working fine in my code.
Another way to solve this problem (it's not so good practice but looks beauty):
static class Helper
{
public static object AsSingleParam(this object[] arg)
{
return (object)arg;
}
}
Usage:
f(new object[] { 1, 2, 3 }.AsSingleParam());
In the model, write the below code;
public $timestamps = false;
This would work.
Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.
Couldn't you just pass the a name attribute and wrap it in a form?
<form id="form" action="do_stuff.php" method="post">
<select id="select_catalog" name="select_catalog_query">
<?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
</select>
</form>
And then look for $_POST['select_catalog_query']
?
This code works perfectly well:
Actions builder = new Actions(driver);
WebElement element = driver.findElement(By.linkText("Put your text here"));
builder.moveToElement(element).build().perform();
After the mouse over, you can then go on to perform the next action you want on the revealed information
This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.
When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.
By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790
So the solution is:
class UserVerification extends Model
{
protected $primaryKey = 'your_key_name'; // or null
public $incrementing = false;
// In Laravel 6.0+ make sure to also set $keyType
protected $keyType = 'string';
}
This is for using a single directory for multiple projects. I use this technique for some closely related projects where I often need to pull changes from one project into another. It's similar to the orphaned branches idea but the branches don't need to be orphaned. Simply start all the projects from the same empty directory state.
Don't expect wonders from this solution. As I see it, you are always going to have annoyances with untracked files. Git doesn't really have a clue what to do with them and so if there are intermediate files generated by a compiler and ignored by your .gitignore file, it is likely that they will be left hanging some of the time if you try rapidly swapping between - for example - your software project and a PH.D thesis project.
However here is the plan. Start as you ought to start any git projects, by committing the empty repository, and then start all your projects from the same empty directory state. That way you are certain that the two lots of files are fairly independent. Also, give your branches a proper name and don't lazily just use "master". Your projects need to be separate so give them appropriate names.
Git commits (and hence tags and branches) basically store the state of a directory and its subdirectories and Git has no idea whether these are parts of the same or different projects so really there is no problem for git storing different projects in the same repository. The problem is then for you clearing up the untracked files from one project when using another, or separating the projects later.
cd some_empty_directory
git init
touch .gitignore
git add .gitignore
git commit -m empty
git tag EMPTY
Start your projects from empty.
git branch software EMPTY
git checkout software
echo "array board[8,8] of piece" > chess.prog
git add chess.prog
git commit -m "chess program"
whenever you like.
git branch thesis EMPTY
git checkout thesis
echo "the meaning of meaning" > philosophy_doctorate.txt
git add philosophy_doctorate.txt
git commit -m "Ph.D"
Go back and forwards between projects whenever you like. This example goes back to the chess software project.
git checkout software
echo "while not end_of_game do make_move()" >> chess.prog
git add chess.prog
git commit -m "improved chess program"
You will however be annoyed by untracked files when swapping between projects/branches.
touch untracked_software_file.prog
git checkout thesis
ls
philosophy_doctorate.txt untracked_software_file.prog
Sort of by definition, git doesn't really know what to do with untracked files and it's up to you to deal with them. You can stop untracked files from being carried around from one branch to another as follows.
git checkout EMPTY
ls
untracked_software_file.prog
rm -r *
(directory is now really empty, apart from the repository stuff!)
git checkout thesis
ls
philosophy_doctorate.txt
By ensuring that the directory was empty before checking out our new project we made sure there were no hanging untracked files from another project.
$ GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01T01:01:01' git commit -m empty
If the same dates are specified whenever committing an empty repository, then independently created empty repository commits can have the same SHA1 code. This allows two repositories to be created independently and then merged together into a single tree with a common root in one repository later.
# Create thesis repository.
# Merge existing chess repository branch into it
mkdir single_repo_for_thesis_and_chess
cd single_repo_for_thesis_and_chess
git init
touch .gitignore
git add .gitignore
GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01:T01:01:01' git commit -m empty
git tag EMPTY
echo "the meaning of meaning" > thesis.txt
git add thesis.txt
git commit -m "Wrote my PH.D"
git branch -m master thesis
# It's as simple as this ...
git remote add chess ../chessrepository/.git
git fetch chess chess:chess
It may also help if you keep your projects in subdirectories where possible, e.g. instead of having files
chess.prog
philosophy_doctorate.txt
have
chess/chess.prog
thesis/philosophy_doctorate.txt
In this case your untracked software file will be chess/untracked_software_file.prog
. When working in the thesis
directory you should not be disturbed by untracked chess program files, and you may find occasions when you can work happily without deleting untracked files from other projects.
Also, if you want to remove untracked files from other projects, it will be quicker (and less prone to error) to dump an unwanted directory than to remove unwanted files by selecting each of them.
So you might want to name your branches something like
project1/master
project1/featureABC
project2/master
project2/featureXYZ
The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.
Also maybe have a look at
I just modified hhafez's test to include StringBuilder. StringBuilder is 33 times faster than String.format using jdk 1.6.0_10 client on XP. Using the -server switch lowers the factor to 20.
public class StringTest {
public static void main( String[] args ) {
test();
test();
}
private static void test() {
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for ( i = 0; i < 1000000; i++ ) {
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for ( i = 0; i < 1000000; i++ ) {
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for ( i = 0; i < 1000000; i++ ) {
new StringBuilder("Blah").append(i).append("Blah");
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
While this might sound drastic, I consider it to be relevant only in rare cases, because the absolute numbers are pretty low: 4 s for 1 million simple String.format calls is sort of ok - as long as I use them for logging or the like.
Update: As pointed out by sjbotha in the comments, the StringBuilder test is invalid, since it is missing a final .toString()
.
The correct speed-up factor from String.format(.)
to StringBuilder
is 23 on my machine (16 with the -server
switch).
I had the same error on OSX Sierra, but in my case the ~/.android folder was owned by root (from a previous install) I changed the ownership to my User and now it works.
Go to project properties -> configurations properties -> C/C++ -> treats warning as error -> No (/WX-)
.
If on another occasion you're synchronising a Collection rather than a String, perhaps you're be iterating over the collection and are worried about it mutating, Java 5 offers:
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
using std::string;
string string_replace( string src, string const& target, string const& repl)
{
// handle error situations/trivial cases
if (target.length() == 0) {
// searching for a match to the empty string will result in
// an infinite loop
// it might make sense to throw an exception for this case
return src;
}
if (src.length() == 0) {
return src; // nothing to match against
}
size_t idx = 0;
for (;;) {
idx = src.find( target, idx);
if (idx == string::npos) break;
src.replace( idx, target.length(), repl);
idx += repl.length();
}
return src;
}
Since it's not a member of the string
class, it doesn't allow quite as nice a syntax as in your example, but the following will do the equivalent:
test = string_replace( string_replace( test, "abc", "hij"), "def", "klm")
Remove "track by index" from the ng-repeat and it would refresh the DOM
As documentation says:
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data either because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests -- e.g. no MultipartResolver.
Slight change to the FastArray from above:
'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """"
t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
If i>ub Then
ReDim Preserve a(Int((ub+10)*1.1))
ub = UBound(a)
End If
a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
MsgBox s
There is no point in checking UBound(a)
in every cycle of the for if we know exactly when it changes.
I've changed it so that it checks does UBound(a)
just before the for starts and then only every time the ReDim
is called
On my computer the old method took 7.52 seconds for an imax of 10 millions.
The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)
You can do this
@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem()
{
Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" } , new
{
onchange = @"form.submit();"
}
})
Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64
or float64
objects, then you can create a dict of the column data types and then use the values to create your list of columns.
So for example, in a dataframe where I have columns of type float64
, int64
and object
firstly you can look at the data types as so:
DF.dtypes
and if they conform to the standard whereby the non-numeric columns of data are all object
types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:
[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]
Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...
Here is a variation of ben blank's answer, if you don't like tuples.
This saves you a few characters.
var keys = [];
for (var key in sortme) {
keys.push(key);
}
keys.sort(function(k0, k1) {
var a = sortme[k0];
var b = sortme[k1];
return a < b ? -1 : (a > b ? 1 : 0);
});
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = sortme[key];
// Do something with key and value.
}
SQL
SQL is used to communicate with a database, it is the standard language for relational database management systems.
In detail Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS).
Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements.
PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation
Specialities of PL/SQL
T-SQL
Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exceptionhandling and row processing to SQL
The Structured Query Language or SQL is a programming language that focuses on managing relational databases. SQL has its own limitations which spurred the software giant Microsoft to build on top of SQL with their own extensions to enhance the functionality of SQL. Microsoft added code to SQL and called it Transact-SQL or T-SQL. Keep in mind that T-SQL is proprietary and is under the control of Microsoft while SQL, although developed by IBM, is already an open format.
T-SQL adds a number of features that are not available in SQL.
This includes procedural programming elements and a local variable to provide more flexible control of how the application flows. A number of functions were also added to T-SQL to make it more powerful; functions for mathematical operations, string operations, date and time processing, and the like. These additions make T-SQL comply with the Turing completeness test, a test that determines the universality of a computing language. SQL is not Turing complete and is very limited in the scope of what it can do.
Another significant difference between T-SQL and SQL is the changes done to the DELETE and UPDATE commands that are already available in SQL. With T-SQL, the DELETE and UPDATE commands both allow the inclusion of a FROM clause which allows the use of JOINs. This simplifies the filtering of records to easily pick out the entries that match a certain criteria unlike with SQL where it can be a bit more complicated.
Choosing between T-SQL and SQL is all up to the user. Still, using T-SQL is still better when you are dealing with Microsoft SQL Server installations. This is because T-SQL is also from Microsoft, and using the two together maximizes compatibility. SQL is preferred by people who have multiple backends.
References , Wikipedea , Tutorial Points :www.differencebetween.com
I can think of three options:
RFC 2217 covers a com port to TCP/IP standard that allows a client on one system to emulate a serial port to the local programs, while transparently sending and receiving data and control signals to a server on another system which actually has the serial port. Here's a high-level overview.
What you would do is find or implement a client com port driver that would implement the client side of the system on your PC - appearing to be a real serial port but in reality shuttling everything to a server. You might be able to get this driver for free from Digi, Lantronix, etc in support of their real standalone serial port servers.
You would then implement the server side of the connection locally in another program - allowing the client to connect and issuing the data and control commands as needed.
It's probably non trivial, but the RFC is out there, and you might be able to find an open source project that implements one or both sides of the connection.
Alternately, the serial port driver source for Linux is readily available. Take that, gut the hardware control pieces, and have that one driver run two /dev/ttySx ports, as a simple loopback. Then connect your real program to the ttyS2 and your simulator to the other ttySx.
But the easiest thing to do right now? Spend $40 on two serial port USB devices, wire them together (null modem) and actually have two real serial ports - one for the program you're testing, one for your simulator.
-Adam
There are already good answer for this question, but I was curious about performance and today 2020.09.21 I conduct tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.
eval/Function
(A,B,C) approach is fast on Chrome (but for big-deep object N=1000 they crash: "maximum stack call exceed)eval
(A) is fast/medium fast on all browsersJSON.parse
(D,E) are fastest on Safari and FirefoxI perform 4 tests cases:
Object used in above tests came from HERE
let obj_ShallowSmall = {
field0: false,
field1: true,
field2: 1,
field3: 0,
field4: null,
field5: [],
field6: {},
field7: "text7",
field8: "text8",
}
let obj_DeepSmall = {
level0: {
level1: {
level2: {
level3: {
level4: {
level5: {
level6: {
level7: {
level8: {
level9: [[[[[[[[[['abc']]]]]]]]]],
}}}}}}}}},
};
let obj_ShallowBig = Array(1000).fill(0).reduce((a,c,i) => (a['field'+i]=getField(i),a) ,{});
let obj_DeepBig = genDeepObject(1000);
// ------------------
// Show objects
// ------------------
console.log('obj_ShallowSmall:',JSON.stringify(obj_ShallowSmall));
console.log('obj_DeepSmall:',JSON.stringify(obj_DeepSmall));
console.log('obj_ShallowBig:',JSON.stringify(obj_ShallowBig));
console.log('obj_DeepBig:',JSON.stringify(obj_DeepBig));
// ------------------
// HELPERS
// ------------------
function getField(k) {
let i=k%10;
if(i==0) return false;
if(i==1) return true;
if(i==2) return k;
if(i==3) return 0;
if(i==4) return null;
if(i==5) return [];
if(i==6) return {};
if(i>=7) return "text"+k;
}
function genDeepObject(N) {
// generate: {level0:{level1:{...levelN: {end:[[[...N-times...['abc']...]]] }}}...}}}
let obj={};
let o=obj;
let arr = [];
let a=arr;
for(let i=0; i<N; i++) {
o['level'+i]={};
o=o['level'+i];
let aa=[];
a.push(aa);
a=aa;
}
a[0]='abc';
o['end']=arr;
return obj;
}
_x000D_
Below snippet presents chosen solutions
// src: https://stackoverflow.com/q/45015/860099
function A(json) {
return eval("(" + json + ')');
}
// https://stackoverflow.com/a/26377600/860099
function B(json) {
return (new Function('return ('+json+')'))()
}
// improved https://stackoverflow.com/a/26377600/860099
function C(json) {
return Function('return ('+json+')')()
}
// src: https://stackoverflow.com/a/5686237/860099
function D(json) {
return JSON.parse(json);
}
// src: https://stackoverflow.com/a/233630/860099
function E(json) {
return $.parseJSON(json)
}
// --------------------
// TEST
// --------------------
let json = '{"a":"abc","b":"123","d":[1,2,3],"e":{"a":1,"b":2,"c":3}}';
[A,B,C,D,E].map(f=> {
console.log(
f.name + ' ' + JSON.stringify(f(json))
)})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.
You don't need the 'values' clause when using a 'select' as your source.
insert into table1 (col1, col2)
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;
You can use XMLHttpRequest, fetch API, ...
If you want to use XMLHttpRequest you can do the following
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log(data);
};
Or if you want to use fetch API
fetch(url, {
method:"POST",
body: JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
})
})
.then(result => {
// do something with the result
console.log("Completed with result:", result);
});
Based on this answer i write my own loader.
With Loading effect and Appear effect :
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.InputStream;
/**
* Created by Sergey Shustikov ([email protected]) at 2015.
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
public static final int ANIMATION_DURATION = 250;
private final ImageView mDestination, mFakeForError;
private final String mUrl;
private final ProgressBar mProgressBar;
private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
if (isBitmapSet)
mDestination.setVisibility(View.VISIBLE);
else
mFakeForError.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation)
{
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private boolean isBitmapSet;
public DownloadImageTask(Context context, ImageView destination, String url)
{
mDestination = destination;
mUrl = url;
ViewGroup parent = (ViewGroup) destination.getParent();
mFakeForError = new ImageView(context);
destination.setVisibility(View.GONE);
FrameLayout layout = new FrameLayout(context);
mProgressBar = new ProgressBar(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mProgressBar.setLayoutParams(params);
FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
copy.gravity = Gravity.CENTER;
copy.width = dpToPx(48);
copy.height = dpToPx(48);
mFakeForError.setLayoutParams(copy);
mFakeForError.setVisibility(View.GONE);
mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
layout.addView(mProgressBar);
layout.addView(mFakeForError);
mProgressBar.setIndeterminate(true);
parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
protected Bitmap doInBackground(String... urls)
{
String urlDisplay = mUrl;
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result)
{
AlphaAnimation in = new AlphaAnimation(0f, 1f);
AlphaAnimation out = new AlphaAnimation(1f, 0f);
in.setDuration(ANIMATION_DURATION * 2);
out.setDuration(ANIMATION_DURATION);
out.setAnimationListener(mOutAnimationListener);
in.setAnimationListener(mInAnimationListener);
in.setStartOffset(ANIMATION_DURATION);
if (result != null) {
mDestination.setImageBitmap(result);
isBitmapSet = true;
mDestination.startAnimation(in);
} else {
mFakeForError.startAnimation(in);
}
mProgressBar.startAnimation(out);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
}
Add permission
<uses-permission android:name="android.permission.INTERNET"/>
And execute :
new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();
Note that callback syntax is deprecated:
Deprecation Notice
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Here a modernized solution using the promise
interface
$.ajax({url: "...", cache: false}).done(function( data ) {
// data contains result
}).fail(function(err){
// error
});
The ComboBox
control inherits from the ListControl
control.
The SelectedItem
property is a proper member of the ComboBox
control. The event that is fired on change is ComboBox.SelectionChangeCommitted
ComboBox.SelectionChangeCommitted
Occurs when the selected item has changed and that change is displayed in the ComboBox.
The SelectedValue
property is inherited from the ListControl
control.
As such, this property will fire the ListControl.SelectedValueChanged
event.
ListControl.SelectedValueChanged
Occurs when the SelectedValue property changes.
That said, they won't fire the INotifyPropertyChanged
.PropertyChanged
event the same, but they will anyway. The only difference is in the firing event. SelectedValueChanged
is fired as soon as a new selection is made from the list part of the ComboBox, and SelectedItemChanged
is fired when the item is displayed in the TextBox portion of the ComboBox.
In short, they both represent something in the list part of the ComboBox. So, when binding either property, the result is the same, since the PropertyChanged
event is fired in either case. And since they both represent an element from the list, the they are probably treated the same.
Does this help?
EDIT #1
Assuming that the list part of the ComboBox represents a property (as I can't confirm since I didn't write the control), binding either of SelectedItem
or SelectedValue
affects the same collection inside the control. Then, when this property is changed, the same occurs in the end. The INotifyPropertryPropertyChanged.PropertyChanged
event is fired on the same property.
You can simply use core javascript to get the param's key value as a js object:
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
let obj = {};
var c = url.searchParams.forEach((value, key) => {
obj[key] = value;
});
console.log(obj);
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json)
in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json)
instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
If you haven't installed matplotlib yet just try the command.
> pip install matplotlib
import matplotlib.pyplot as plot
plot.hist(weightList,density=1, bins=20)
plot.axis([50, 110, 0, 0.06])
#axis([xmin,xmax,ymin,ymax])
plot.xlabel('Weight')
plot.ylabel('Probability')
plot.show()
Didn't quite see this variation in the answers yet. I had an additional constraint where I needed, given an initial seed, to select the same set of rows each time.
For MS SQL:
Minimum example:
select top 10 percent *
from table_name
order by rand(checksum(*))
Normalized execution time: 1.00
NewId() example:
select top 10 percent *
from table_name
order by newid()
Normalized execution time: 1.02
NewId()
is insignificantly slower than rand(checksum(*))
, so you may not want to use it against large record sets.
Selection with Initial Seed:
declare @seed int
set @seed = Year(getdate()) * month(getdate()) /* any other initial seed here */
select top 10 percent *
from table_name
order by rand(checksum(*) % @seed) /* any other math function here */
If you need to select the same set given a seed, this seems to work.
//This code worked for me
class CountOfLettersOfString
{
static void Main()
{
Console.WriteLine("Enter string to check count of letters");
string name = Console.ReadLine();
//Method1
char[] testedalphabets = new char[26];
int[] letterCount = new int[26];
int countTestesd = 0;
Console.WriteLine($"Given String is:{name}");
for (int i = 0; i < name.Length - 1; i++)
{
int countChar = 1;
bool isCharTested = false;
for (int j = 0; j < testedalphabets.Length - 1; j++)
{
if (name[i] == testedalphabets[j])
{
isCharTested = true;
break;
}
}
if (!isCharTested)
{
testedalphabets[countTestesd] = name[i];
for (int k = i + 1; k < name.Length - 1; k++)
{
if (name[i] == name[k])
{
countChar++;
}
}
letterCount[countTestesd] = countChar;
countTestesd++;
}
else
{
continue;
}
}
for (int i = 0; i < testedalphabets.Length - 1; i++)
{
if (!char.IsLetter(testedalphabets[i]))
{
continue;
}
Console.WriteLine($"{testedalphabets[i]}-{letterCount[i]}");
}
//Method2
var g = from c in name.ToLower().ToCharArray() // make sure that L and l are the same eg
group c by c into m
select new { Key = m.Key, Count = m.Count() };
foreach (var item in g)
{
Console.WriteLine(string.Format("Character:{0} Appears {1} times", item.Key.ToString(), item.Count));
}
Console.ReadLine();
}
}
The question does not make clear what exactly you want to achieve.
List has the append
method, which appends its argument to the list:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
There's also the extend
method, which appends items from the list you pass as an argument:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
And of course, there's the insert
method which acts similarly to append
but allows you to specify the insertion point:
>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]
To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):
>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]
As Answered here
Use below code :
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
In AndroidManifest.xml, give the following permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.
Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!
Suggested Workaround:
Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.
For me I quit Skype, which was occupying port 80, then Apache ran happily on port 80, than I ran Skype and it picked another port this time.
Sure you can:
Option Explicit
'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type
'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType
MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3
Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub
'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer
MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333
For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub
TLDR; Uninstall and re-install using admin account.
I encountered this error after installing Oracle Express 11g 64 bit using a standard account. After looking for a fix on various sites I realized that the issue was most likely caused by an incorrect setting. Different people suggested editing various files which I was not interested in doing. I found one person who claimed that the issue was a registry setting. Since I used a standard account to install I thought that maybe the registry setting could not be altered using a standard account. So I uninstalled and re-installed using an admin account and it just worked.
Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.
Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master
.
(From nvie.com, Vincent Driessen, post "A successful Git branching model")
Incorporating a finished feature on develop
Finished features may be merged into the develop branch to add them to the upcoming release:
$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop
The
--no-ff
flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.
Jakub Narebski also mentions the config merge.ff
:
By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set tofalse
, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the--no-ff
option from the command line).
When set to 'only
', only such fast-forward merges are allowed (equivalent to giving the--ff-only
option from the command line).
The fast-forward is the default because:
But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.
In this case, you can end up setting this kind of config file:
[branch "master"]
# This is the list of cmdline options that should be added to git-merge
# when I merge commits into the master branch.
# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.
# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.
mergeoptions = --no-commit --no-ff
The OP adds in the comments:
I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?
Jefromi answers:
I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.
To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.
More generally, I add:
it really depends on your development workflow:
- if it is linear, one branch makes sense.
- If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.
See "When should you branch?"
Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".
Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.
Your problem comes from the 32/64 bit version of your JDK/JRE... Your shared lib is searched for a 32 bit version.
Your default JDK is a 32 bit version. Try to install a 64 bit one by default and relaunch your `.sh file.
This question actually is not JSP related, it is HTTP related. you can just do:
window.location = window.location;
import cv2 as cv
im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
At this point you have a color and a gray image. We are dealing with 8-bit
, uint8
images here. That means the images can have pixel values in the range of [0, 255]
and the values have to be integers.
Let's do a binary thresholding operation. It creates a black and white masked image. The black regions have value 0
and the white regions 255
_, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
im_thresh_gray = cv.bitwise_and(im_gray, mask)
The mask can be seen below on the left. The image on it's right is the result of applying bitwise_and
operation between the gray image and the mask. What happened is, the spatial locations where the mask had a pixel value zero (black), became pixel value zero in the result image. The locations where the mask had pixel value 255 (white), the resulting image retained it's original gray value.
To apply this mask to our original color image, we need to convert the mask into a 3 channel image as the original color image is a 3 channel image.
mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
Then, we can apply this 3 channel mask to our color image using the same bitwise_and
function.
im_thresh_color = cv.bitwise_and(im_color, mask3)
mask3
from the code is the image below on the left, and im_thresh_color
is on its right.
You can plot the results and see for yourself.
cv.imshow("original image", im_color)
cv.imshow("binary mask", mask)
cv.imshow("3 channel mask", mask3)
cv.imshow("im_thresh_gray", im_thresh_gray)
cv.imshow("im_thresh_color", im_thresh_color)
cv.waitKey(0)
The original image is lenacolor.png
that I found here.
I imagine a simple Replace in Files (Ctrl+Shift+H) will just about do the trick; simply replace namespace DemoApp
with namespace MyApp
. After that, build the solution and look for compile errors for unknown identifiers. Anything that fully qualified DemoApp
will need to be changed to MyApp
.
With Yglu Structural Templating, your example can be written:
foo: !()
!? $.propname:
type: number
default: !? $.default
bar:
!apply .foo:
propname: "some_prop"
default: "some default"
Disclaimer: I am the author or Yglu.
One thing to watch out for in benchmarks (especially phpbench.com), is even though the numbers are sound, the tests are not. Alot of the tests on phpbench.com are doing things at are trivial and abuse PHP's ability to cache array lookups to skew benchmarks or in the case of iterating over an array doesn't actually test it in real world cases (no one writes empty for loops). I've done my own benchmarks that I've found are fairly reflective of the real world results and they always show the language's native iterating syntax foreach
coming out on top (surprise, surprise).
//make a nicely random array
$aHash1 = range( 0, 999999 );
$aHash2 = range( 0, 999999 );
shuffle( $aHash1 );
shuffle( $aHash2 );
$aHash = array_combine( $aHash1, $aHash2 );
$start1 = microtime(true);
foreach($aHash as $key=>$val) $aHash[$key]++;
$end1 = microtime(true);
$start2 = microtime(true);
while(list($key) = each($aHash)) $aHash[$key]++;
$end2 = microtime(true);
$start3 = microtime(true);
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $aHash[$key[$i]]++;
$end3 = microtime(true);
$start4 = microtime(true);
foreach($aHash as &$val) $val++;
$end4 = microtime(true);
echo "foreach ".($end1 - $start1)."\n"; //foreach 0.947947025299
echo "while ".($end2 - $start2)."\n"; //while 0.847212076187
echo "for ".($end3 - $start3)."\n"; //for 0.439476966858
echo "foreach ref ".($end4 - $start4)."\n"; //foreach ref 0.0886030197144
//For these tests we MUST do an array lookup,
//since that is normally the *point* of iteration
//i'm also calling noop on it so that PHP doesn't
//optimize out the loopup.
function noop( $value ) {}
//Create an array of increasing indexes, w/ random values
$bHash = range( 0, 999999 );
shuffle( $bHash );
$bstart1 = microtime(true);
for($i = 0; $i < 1000000; ++$i) noop( $bHash[$i] );
$bend1 = microtime(true);
$bstart2 = microtime(true);
$i = 0; while($i < 1000000) { noop( $bHash[$i] ); ++$i; }
$bend2 = microtime(true);
$bstart3 = microtime(true);
foreach( $bHash as $value ) { noop( $value ); }
$bend3 = microtime(true);
echo "for ".($bend1 - $bstart1)."\n"; //for 0.397135972977
echo "while ".($bend2 - $bstart2)."\n"; //while 0.364789962769
echo "foreach ".($bend3 - $bstart3)."\n"; //foreach 0.346374034882
In code:
editText.setEnabled(false);
Or, in XML:
android:editable="false"
Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).
Setting a cookie:
def view(request):
response = HttpResponse('blah')
response.set_cookie('cookie_name', 'cookie_value')
Retrieving a cookie:
def view(request):
value = request.COOKIES.get('cookie_name')
if value is None:
# Cookie is not set
# OR
try:
value = request.COOKIES['cookie_name']
except KeyError:
# Cookie is not set
If making a call to asp.net, this will return the error message title:
I didn't write all of formatErrorMessage myself but i find it very useful.
function formatErrorMessage(jqXHR, exception) {
if (jqXHR.status === 0) {
return ('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status == 404) {
return ('The requested page not found. [404]');
} else if (jqXHR.status == 500) {
return ('Internal Server Error [500].');
} else if (exception === 'parsererror') {
return ('Requested JSON parse failed.');
} else if (exception === 'timeout') {
return ('Time out error.');
} else if (exception === 'abort') {
return ('Ajax request aborted.');
} else {
return ('Uncaught Error.\n' + jqXHR.responseText);
}
}
var jqxhr = $.post(addresshere, function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function(xhr, err) {
var responseTitle= $(xhr.responseText).filter('title').get(0);
alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) );
})
Following solution will drop specific default constraint of a column from the table
Declare @Const NVARCHAR(256)
SET @Const = (
SELECT TOP 1 'ALTER TABLE' + YOUR TABLE NAME +' DROP CONSTRAINT '+name
FROM Sys.default_constraints A
JOIN sysconstraints B on A.parent_object_id = B.id
WHERE id = OBJECT_ID('YOUR TABLE NAME')
AND COL_NAME(id, colid)='COLUMN NAME'
AND OBJECTPROPERTY(constid,'IsDefaultCnst')=1
)
EXEC (@Const)
Here is a solution that does not require functions to get an accurate count for each table:
select table_schema,
table_name,
(xpath('/row/cnt/text()', xml_count))[1]::text::int as row_count
from (
select table_name, table_schema,
query_to_xml(format('select count(*) as cnt from %I.%I', table_schema, table_name), false, true, '') as xml_count
from information_schema.tables
where table_schema = 'public' --<< change here for the schema you want
) t
query_to_xml
will run the passed SQL query and return an XML with the result (the row count for that table). The outer xpath()
will then extract the count information from that xml and convert it to a number
The derived table is not really necessary, but makes the xpath()
a bit easier to understand - otherwise the whole query_to_xml()
would need to be passed to the xpath()
function.
One possible workaround would be using a "frame-breaker" script as described here
You just need to alter the "if" statement to check for your allowed domains.
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
//your domain check goes here
if(top.location.host != "allowed.domain1.com" && top.location.host == "allowed.domain2.com")
top.location = self.location;
}
This workaround would be safe, I think. because with javascript not enabled you will have no security concern about a malicious website framing your page.
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.
Not really great but a funny hack: You can -- instead of +
{{num_str -- 1 }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
{{'1'--1}}_x000D_
</div>
_x000D_
This works for me: $('#profile1').attr('onclick')
I believe you can use a case statement in a where clause, here is how I do it:
Select
ProductID
OrderNo,
OrderType,
OrderLineNo
From Order_Detail
Where ProductID in (
Select Case when (@Varibale1 != '')
then (Select ProductID from Product P Where .......)
Else (Select ProductID from Product)
End as ProductID
)
This method has worked for me time and again. try it!
In the solutions in previous answers selection is stopped, but the user still thinks you can select text because the cursor still changes. To keep it static, you'll have to set your CSS cursor:
.noselect {_x000D_
cursor: default;_x000D_
-webkit-touch-callout: none;_x000D_
-webkit-user-select: none;_x000D_
-khtml-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
user-select: none;_x000D_
}
_x000D_
<p>_x000D_
Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
Unselectable text._x000D_
</p>
_x000D_
This will make your text totally flat, like it would be in a desktop application.
Please check your Windows system event log for any errors specifically for the "Event Source: Dhcp". It's very likely a networking error related to DHCP. Address lease time expired or so. It shouldn't be a problem related to the SQL Server or the query itself.
Just search the internet for "The semaphore timeout period has expired" and you'll get plenty of suggestions what might be a solution for your problem. Unfortunately there doesn't seem to be the solution for this problem.
Leave your email.php code the same, but replace this JavaScript code:
var name = $("#form_name").val();
var email = $("#form_email").val();
var text = $("#msg_text").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
with this:
$.ajax({
type: "POST",
url: "email.php",
data: $(form).serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
So that your form input names match up.
Setting height to 101% is my solution to the problem. You pages will no longer 'flick' when switching between ones that exceed the viewport height and ones that do not.
The struct b
line doesn't work because it's a syntax error. If you expand it out to include the type it will work just fine
struct MyObj b = a; // Runs fine
What C is doing here is essentially a memcpy
from the source struct to the destination. This is true for both assignment and return of struct
values (and really every other value in C)
... using org.apache.http api. ...
You need to include SOAPAction
as a header in the request. As you have httpPost
and requestWrapper
handles, there are three ways adding the header.
1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );
Only difference is that addHeader
allows multiple values with same header name and setHeader
allows unique header names only. setHeader(...
over writes first header with the same name.
You can go with any of these on your requirement.
This happened to me and I found a solution, see if this works for you:
Once you have built your project with the hammer icon:
Afterwards you should be able to run the project as much as you'd like.
Hopefully this works for you.
Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :
SO_REUSEPORT (since Linux 3.9) Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.
You can set theses two options before calling bind like this :
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
Replace
new Timestamp();
with
new java.util.Date()
because there is no default constructor for Timestamp
, or you can do it with the method:
new Timestamp(System.currentTimeMillis());
This has to do with the browser's box model. Use something like jQuery or another JavaScript abstraction library to normalize the DOM model.
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
Serialize both objects, then calculate Hash Code, then compare.
this is pretty basic stuff, all you need to do is to create a base view model and make sure ALL! and i mean ALL! of your views that will ever use that layout will receive views that use that base model!
public class SomeViewModel : ViewModelBase
{
public bool ImNotEmpty = true;
}
public class EmptyViewModel : ViewModelBase
{
}
public abstract class ViewModelBase
{
}
in the _Layout.cshtml:
@model Models.ViewModelBase
<!DOCTYPE html>
<html>
and so on...
in the the Index (for example) method in the home controller:
public ActionResult Index()
{
var model = new SomeViewModel()
{
};
return View(model);
}
the Index.cshtml:
@model Models.SomeViewModel
@{
ViewBag.Title = "Title";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
i disagree that passing a model to the _layout is an error, some user info can be passed and the data can be populate in the controllers inheritance chain so only one implementation is needed.
obviously for more advanced purpose you should consider creating custom static contaxt using injection and include that model namespace in the _Layout.cshtml.
but for basic users this will do the trick
Resolved this issue by navigating to C:\xampp\mysql\bin and double clicking on mysqld.exe and then allow access in the pop up that comes. My server status on workbench changed to running
I tried this command to display the list of files in the directory.
dir /s /b > List.txt
In the file it displays the list below.
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco
C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll
What is want to do is only to display sub-directory not the full directory path.
Just like this:
Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll
Cisco Jabber\accessories\JabraJabberPlugin.dll
Cisco Jabber\accessories\Logitech
Cisco Jabber\accessories\Plantronics
Cisco Jabber\accessories\SennheiserJabberPlugin.dll
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
BufferedReader
can't wrap an InputStream
directly. It wraps another Reader
. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
Import the root module with importlib.import_module
and load the class by its name using getattr
function:
# Standard import
import importlib
# Load "module.submodule.MyClass"
MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
# Instantiate the class (pass arguments to the constructor, if needed)
instance = MyClass()
You probably don't want to use __import__
to dynamically import a module by name, as it does not allow you to import submodules:
>>> mod = __import__("os.path")
>>> mod.join
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'join'
Here is what the python doc says about __import__
:
Note: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().
Instead, use the standard importlib
module to dynamically import a module by name. With getattr
you can then instantiate a class by its name:
import importlib
my_module = importlib.import_module("module.submodule")
MyClass = getattr(my_module, "MyClass")
instance = MyClass()
You could also write:
import importlib
module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
MyClass = getattr(importlib.import_module(module_name), class_name)
instance = MyClass()
This code is valid in python = 2.7 (including python 3).
You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.
If you like to write CoffeeScript you could do:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript actually IS javascript, but with a much better syntax.
For an overview of CoffeeScript check this beginner's guide.
This is one of the outright idiocies of CSS - I have yet to understand the reasoning (if someone knows, pls. explain).
100% means 100% of the container height - to which any margins, borders and padding are added. So it is effectively impossible to get a container which fills it's parent and which has a margin, border, or padding.
Note also, setting height is notoriously inconsistent between browsers, too.
Another thing I've learned since I posted this is that the percentage is relative the container's length, that is, it's width, making a percentage even more worthless for height.
Nowadays, the vh and vw viewport units are more useful, but still not especially useful for anything other than the top-level containers.
I needed a very simple solution to hide something after sometime and managed to get this to work:
In angular you can do this:
$timeout(self.hideError,2000);
Here is the function that i call when the timeout has been reached
self.hideError = function(){
self.HasError = false;
self.ErrorMessage = '';
};
So now my dialog/ui can use those properties to hide elements.
Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line
java -Djava.library.path=C:\Java\native\libs YourProgram
C:\Java\native\libs should contain sqljdbc_auth.dll
Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.
There are 2 types of multidimensional arrays in C#, called Multidimensional
and Jagged
.
For multidimensional you can by:
string[,] multi = new string[3, 3];
For jagged array you have to write a bit more code:
string[][] jagged = new string[3][];
for (int i = 0; i < jagged.Length; i++)
{
jagged[i] = new string[3];
}
In short jagged array is both faster and has intuitive syntax. For more information see: this Stackoverflow question
The reason you might not be getting any results is because you might not be having the J2EE environment setup in your Eclipse IDE. Follow these steps to solve the problem.
Goto Help -> Install new Software Select relevant dropdown entry {Oxygen - http://download.eclipse.org/releases/<?>} (or Similar option/version) in the "Work with" tab.
Search for Web,XML,Java EE and OSGi Enterprise Development Check the boxes corresponding to,Eclipse Java EE Developer Tools JST Server Adapters JST Server Adapters Extensions Click next and accept the license agreement.
To track installations, you could for example use a UUID as an identifier, and simply create a new one the first time an app runs after installation. Here is a sketch of a class named “Installation” with one static method Installation.id(Context context). You could imagine writing more installation-specific data into the INSTALLATION file.
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
Yon can see more at https://github.com/MShoaibAkram/Android-Unique-Application-ID
In your code:
var obj = {
myProp: string;
};
You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):
var string = 'A string';
var obj = {
property: string
};
However, what you want is that the object literal is typed. This can be achieved in various ways:
Interface:
interface myObj {
property: string;
}
var obj: myObj = { property: "My string" };
Type alias:
type myObjType = {
property: string
};
var obj: myObjType = { property: "My string" };
Object type literal:
var obj: { property: string; } = { property: "Mystring" };
You could try with android:background="@android:drawable/list_selector_background"
to get the same effect as the "Add alarm" in the default "Alarm Clock" (now Desk Clock).
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
Try the following:
<script>
//Functions to open database and to create, insert data into tables
getSelectedRow = function(val)
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
});
};
selectedRowValues = function(transaction,results)
{
for(var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
alert(row['number']);
alert(row['name']);
}
};
</script>
You don't have access to javascript variable names in SQL, you must pass the values to the Database.
If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:
For example, the following will work in Freemarker (since at least version 2.3.19):
<#list map.entrySet() as entry>
<input type="hidden" name="${entry.key}" value="${entry.value}" />
</#list>
In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.
If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.
// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};
// file scope
int arr[4];
// equivalent to
int arr[4] = {0};
Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.
// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
Click the left side dropdown menu "android" and choose "project" to see libs folders
*after choosing project you will see the libs directory
Line breaks are considered as content to elements in FF.
<div>
</div>
<div></div>
Ex:
$("div:empty").text("Empty").css('background', '#ff0000');
In IE both divs are considered empty, in FF an Chrome only the last one is empty.
You can use the solution provided by @qwertymk
if(!/[\S]/.test($('#element').html())) { // for one element
alert('empty');
}
or
$('.elements').each(function(){ // for many elements
if(!/[\S]/.test($(this).html())) {
// is empty
}
})
You can simply do it like this with an object literal:
function makeGamePlayer(name,totalScore,gamesPlayed) {
return {
name: name,
totalscore: totalScore,
gamesPlayed: gamesPlayed
};
}
First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can also use like below code.
<button style="position: absolute; right: 0;">Button</button>
I would like to draw attention to the fact that a simple <meta property="og:image" content="image.png" />
, as suggested somewhere above, does not work for me (this in fact had me in a loop for weeks now). What works is either an absolute URL:
<meta property="og:image" content="https://domainname.com/image.png" />
or starting out with a slash (if the image is in the root directory):
<meta property="og:image" content="/image.png" />
(I would have added this as a comment, but I'm not allowed to yet. Moderators feel free to move this if more appropriate.)
I thought this would work, based on this source.
SELECT
'Currently, '
|| (SELECT COUNT(*) FROM V$SESSION)
|| ' out of '
|| DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX)
|| ' connections are used.' AS USAGE_MESSAGE
FROM
V$LICENSE VL
However, Justin Cave is right. This query gives better results:
SELECT
'Currently, '
|| (SELECT COUNT(*) FROM V$SESSION)
|| ' out of '
|| VP.VALUE
|| ' connections are used.' AS USAGE_MESSAGE
FROM
V$PARAMETER VP
WHERE VP.NAME = 'sessions'
J(2)EE, strictly speaking, is a set of API
s (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.
In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!
J2EE was a marketing construct.
Actually, there is a gem called Jsonable, https://github.com/treeder/jsonable. It's pretty sweet.
Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...
from operator import lt, gt
def ultimate (l,op,c=1,u=0):
try:
if op(l[c],l[u]):
u = c
c += 1
return ultimate(l,op,c,u)
except IndexError:
return l[u]
def minimum (l):
return ultimate(l,lt)
def maximum (l):
return ultimate(l,gt)
The solution is simple. Use this to set yourself apart from obvious choices.
I ended up with a custom extension method. Its worth noting, when trying to place HTML inside of an Anchor object, the link text can be either to the left, or to the right of the inner HTML. For this reason, I opted to provide parameters for left and right inner HTML - the link text is in the middle. Both left and right inner HTML are optional.
Extension Method ActionLinkInnerHtml:
public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
{
// CONSTRUCT THE URL
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);
// CREATE AN ANCHOR TAG BUILDER
var builder = new TagBuilder("a");
builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
builder.MergeAttribute(key: "href", value: url);
// ADD HTML ATTRIBUTES
builder.MergeAttributes(htmlAttributes, replaceExisting: true);
// BUILD THE STRING AND RETURN IT
var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
return mvcHtmlString;
}
Example of Usage:
Here is an example of usage. For this example I only wanted the inner html on the right side of the link text...
@Html.ActionLinkInnerHtml(
linkText: "Hello World"
, actionName: "SomethingOtherThanIndex"
, controllerName: "SomethingOtherThanHome"
, rightInnerHtml: "<span class=\"caret\" />"
)
Results:
this results in the following HTML...
<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>
Wouldn't a simple background image for the textarea suffice?
Whats the value for the SqlException.ErrorCode property? Can you work with that?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".
In my case the sha command was missing from my linux distro; steps were
Why not model a fake stock market with Brownian Motion?
Plenty of resources for doing it. Easy to implement.
I think oracle is smart enough to convert the less efficient one (whichever that is) into the other. So I think the answer should rather depend on the readability of each (where I think that IN
clearly wins)


is the HTML representation in hex of a line feed
character. It represents a new line on Unix and Unix-like (for example) operating systems.
You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html
You can also try using a C#/Perl/Java script get the utilization data using WMI Commands, and below is the steps for it.
We need to execute 2 WMI Select Queries and apply CPU% utilization formula
1. To retrieve the total number of logical process
select NumberOfLogicalProcessors from Win32_ComputerSystem
2. To retrieve the values of PercentProcessorTime, TimeStamp_Sys100NS ( CPU utilization formula has be applied get the actual utilization percentage)and WorkingSetPrivate ( RAM ) minimum of 2 times with a sleep interval of 1 second
select * from Win32_PerfRawData_PerfProc_Process where IDProcess=1234
3. Apply CPU% utilization formula
CPU%= ((p2-p1)/(t2-t1)*100)/NumberOfLogicalProcessors
p2 indicated PercentProcessorTime retrieved for the second time, and p1 indicateds the PercentProcessorTime retrieved for the first time, t2 and t1 is for TimeStamp_Sys100NS.
A sample Perl code for this can be found in the link http://www.craftedforeveryone.com/cpu-and-ram-utilization-of-an-application-using-perl-via-wmi/
This logic applies for all programming language which supports WMI queries
Java converts Integer to int and back automatically (unless you are still with Java 1.4).
I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.
Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.
If for matching identical images - code for L2 distance
// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
// Calculate the L2 relative error between images.
double errorL2 = norm( A, B, CV_L2 );
// Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
double similarity = errorL2 / (double)( A.rows * A.cols );
return similarity;
}
else {
//Images have a different size
return 100000000.0; // Return a bad value
}
Fast. But not robust to changes in lighting/viewpoint etc. Source
You could use POSIX [[:blank:]]
to match a horizontal white-space character.
sed 's/[[:blank:]]\+/\n/g' file
or you may use [[:space:]]
instead of [[:blank:]]
also.
Example:
$ echo 'this is a sentence' | sed 's/[[:blank:]]\+/\n/g'
this
is
a
sentence
In case you want to use the class and pseudo-class:
.simple-control
is your css class
:disabled
is pseudo class
select.simple-control:disabled{
/*For FireFox*/
-webkit-appearance: none;
/*For Chrome*/
-moz-appearance: none;
}
/*For IE10+*/
select:disabled.simple-control::-ms-expand {
display: none;
}
Try with Shadow( Like border ) + Border
border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;
simplest way to center your div element is to use this class with following properties.
.light {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.
// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
// set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
var postEnc, method;
if (post == null)
{
postEnc = '';
method = 'GET';
}
else
{
method = 'POST';
postEnc = new FormData();
for(var i in post)
postEnc.append(i, post[i]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var res = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(res);
reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
}
}
xhr.open(method, url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fname=Henry&lname=Ford');
xhr.responseType = 'blob';
xhr.send(postEnc);
}
I have created much more thorough benchmarks. First of all, as @ChaimG pointed out, early binding makes a big difference (I originally used @eksortso's code above verbatim which uses late binding). Secondly, my original benchmarks only included the time to create the unique object, however, it did not test the efficiency of using the object. My point in doing this is, it doesn't really matter if I can create an object really fast if the object I create is clunky and slows me down moving forward.
Old Remark: It turns out, that looping over a collection object is highly inefficient
It turns out that looping over a collection can be quite efficient if you know how to do it (I didn't). As @ChaimG (yet again), pointed out in the comments, using a For Each
construct is ridiculously superior to simply using a For
loop. To give you an idea, before changing the loop construct, the time for Collection2
for the Test Case Size = 10^6
was over 1400s (i.e. ~23 minutes). It is now a meager 0.195s (over 7000x faster).
For the Collection
method there are two times. The first (my original benchmark Collection1
) show the time to create the unique object. The second part (Collection2
) shows the time to loop over the object (which is very natural) to create a returnable array as the other functions do.
In the chart below, a yellow background indicates that it was the fastest for that test case, and red indicates the slowest ("Not Tested" algorithms are excluded). The total time for the Collection
method is the sum of Collection1
and Collection2
. Turquoise indicates that is was the fastest regardless of original order.
Below is the original algorithm I created (I have modified it slightly e.g. I no longer instantiate my own data type). It returns the unique values of an array with the original order in a very respectable time and it can be modified to take on any data type. Outside of the IndexMethod
, it is the fastest algorithm for very large arrays.
Here are the main ideas behind this algorithm:
Below is an example:
Let myArray = (86, 100, 33, 19, 33, 703, 19, 100, 703, 19)
1. (86, 100, 33, 19, 33, 703, 19, 100, 703, 19)
(1 , 2, 3, 4, 5, 6, 7, 8, 9, 10) <<-- Indexing
2. (19, 19, 19, 33, 33, 86, 100, 100, 703, 703) <<-- sort by values
(4, 7, 10, 3, 5, 1, 2, 8, 6, 9)
3. (19, 33, 86, 100, 703) <<-- remove duplicates
(4, 3, 1, 2, 6)
4. (86, 100, 33, 19, 703)
( 1, 2, 3, 4, 6) <<-- sort by index
Here is the code:
Function SortingUniqueTest(ByRef myArray() As Long, bOrigIndex As Boolean) As Variant
Dim MyUniqueArr() As Long, i As Long, intInd As Integer
Dim StrtTime As Double, Endtime As Double, HighB As Long, LowB As Long
LowB = LBound(myArray): HighB = UBound(myArray)
ReDim MyUniqueArr(1 To 2, LowB To HighB)
intInd = 1 - LowB 'Guarantees the indices span 1 to Lim
For i = LowB To HighB
MyUniqueArr(1, i) = myArray(i)
MyUniqueArr(2, i) = i + intInd
Next i
QSLong2D MyUniqueArr, 1, LBound(MyUniqueArr, 2), UBound(MyUniqueArr, 2), 2
Call UniqueArray2D(MyUniqueArr)
If bOrigIndex Then QSLong2D MyUniqueArr, 2, LBound(MyUniqueArr, 2), UBound(MyUniqueArr, 2), 2
SortingUniqueTest = MyUniqueArr()
End Function
Public Sub UniqueArray2D(ByRef myArray() As Long)
Dim i As Long, j As Long, Count As Long, Count1 As Long, DuplicateArr() As Long
Dim lngTemp As Long, HighB As Long, LowB As Long
LowB = LBound(myArray, 2): Count = LowB: i = LowB: HighB = UBound(myArray, 2)
Do While i < HighB
j = i + 1
If myArray(1, i) = myArray(1, j) Then
Do While myArray(1, i) = myArray(1, j)
ReDim Preserve DuplicateArr(1 To Count)
DuplicateArr(Count) = j
Count = Count + 1
j = j + 1
If j > HighB Then Exit Do
Loop
QSLong2D myArray, 2, i, j - 1, 2
End If
i = j
Loop
Count1 = HighB
If Count > 1 Then
For i = UBound(DuplicateArr) To LBound(DuplicateArr) Step -1
myArray(1, DuplicateArr(i)) = myArray(1, Count1)
myArray(2, DuplicateArr(i)) = myArray(2, Count1)
Count1 = Count1 - 1
ReDim Preserve myArray(1 To 2, LowB To Count1)
Next i
End If
End Sub
Here is the sorting algorithm I use (more about this algo here).
Sub QSLong2D(ByRef saArray() As Long, bytDim As Byte, lLow1 As Long, lHigh1 As Long, bytNum As Byte)
Dim lLow2 As Long, lHigh2 As Long
Dim sKey As Long, sSwap As Long, i As Byte
On Error GoTo ErrorExit
If IsMissing(lLow1) Then lLow1 = LBound(saArray, bytDim)
If IsMissing(lHigh1) Then lHigh1 = UBound(saArray, bytDim)
lLow2 = lLow1
lHigh2 = lHigh1
sKey = saArray(bytDim, (lLow1 + lHigh1) \ 2)
Do While lLow2 < lHigh2
Do While saArray(bytDim, lLow2) < sKey And lLow2 < lHigh1: lLow2 = lLow2 + 1: Loop
Do While saArray(bytDim, lHigh2) > sKey And lHigh2 > lLow1: lHigh2 = lHigh2 - 1: Loop
If lLow2 < lHigh2 Then
For i = 1 To bytNum
sSwap = saArray(i, lLow2)
saArray(i, lLow2) = saArray(i, lHigh2)
saArray(i, lHigh2) = sSwap
Next i
End If
If lLow2 <= lHigh2 Then
lLow2 = lLow2 + 1
lHigh2 = lHigh2 - 1
End If
Loop
If lHigh2 > lLow1 Then QSLong2D saArray(), bytDim, lLow1, lHigh2, bytNum
If lLow2 < lHigh1 Then QSLong2D saArray(), bytDim, lLow2, lHigh1, bytNum
ErrorExit:
End Sub
Below is a special algorithm that is blazing fast if your data contains integers. It makes use of indexing and the Boolean data type.
Function IndexSort(ByRef myArray() As Long, bOrigIndex As Boolean) As Variant
'' Modified to take both positive and negative integers
Dim arrVals() As Long, arrSort() As Long, arrBool() As Boolean
Dim i As Long, HighB As Long, myMax As Long, myMin As Long, OffSet As Long
Dim LowB As Long, myIndex As Long, count As Long, myRange As Long
HighB = UBound(myArray)
LowB = LBound(myArray)
For i = LowB To HighB
If myArray(i) > myMax Then myMax = myArray(i)
If myArray(i) < myMin Then myMin = myArray(i)
Next i
OffSet = Abs(myMin) '' Number that will be added to every element
'' to guarantee every index is non-negative
If myMax > 0 Then
myRange = myMax + OffSet '' E.g. if myMax = 10 & myMin = -2, then myRange = 12
Else
myRange = OffSet
End If
If bOrigIndex Then
ReDim arrSort(1 To 2, 1 To HighB)
ReDim arrVals(1 To 2, 0 To myRange)
ReDim arrBool(0 To myRange)
For i = LowB To HighB
myIndex = myArray(i) + OffSet
arrBool(myIndex) = True
arrVals(1, myIndex) = myArray(i)
If arrVals(2, myIndex) = 0 Then arrVals(2, myIndex) = i
Next i
For i = 0 To myRange
If arrBool(i) Then
count = count + 1
arrSort(1, count) = arrVals(1, i)
arrSort(2, count) = arrVals(2, i)
End If
Next i
QSLong2D arrSort, 2, 1, count, 2
ReDim Preserve arrSort(1 To 2, 1 To count)
Else
ReDim arrSort(1 To HighB)
ReDim arrVals(0 To myRange)
ReDim arrBool(0 To myRange)
For i = LowB To HighB
myIndex = myArray(i) + OffSet
arrBool(myIndex) = True
arrVals(myIndex) = myArray(i)
Next i
For i = 0 To myRange
If arrBool(i) Then
count = count + 1
arrSort(count) = arrVals(i)
End If
Next i
ReDim Preserve arrSort(1 To count)
End If
ReDim arrVals(0)
ReDim arrBool(0)
IndexSort = arrSort
End Function
Here are the Collection (by @DocBrown) and Dictionary (by @eksortso) Functions.
Function CollectionTest(ByRef arrIn() As Long, Lim As Long) As Variant
Dim arr As New Collection, a, i As Long, arrOut() As Variant, aFirstArray As Variant
Dim StrtTime As Double, EndTime1 As Double, EndTime2 As Double, count As Long
On Error Resume Next
ReDim arrOut(1 To UBound(arrIn))
ReDim aFirstArray(1 To UBound(arrIn))
StrtTime = Timer
For i = 1 To UBound(arrIn): aFirstArray(i) = CStr(arrIn(i)): Next i '' Convert to string
For Each a In aFirstArray ''' This part is actually creating the unique set
arr.Add a, a
Next
EndTime1 = Timer - StrtTime
StrtTime = Timer ''' This part is writing back to an array for return
For Each a In arr: count = count + 1: arrOut(count) = a: Next a
EndTime2 = Timer - StrtTime
CollectionTest = Array(arrOut, EndTime1, EndTime2)
End Function
Function DictionaryTest(ByRef myArray() As Long, Lim As Long) As Variant
Dim StrtTime As Double, Endtime As Double
Dim d As Scripting.Dictionary, i As Long '' Early Binding
Set d = New Scripting.Dictionary
For i = LBound(myArray) To UBound(myArray): d(myArray(i)) = 1: Next i
DictionaryTest = d.Keys()
End Function
Here is the Direct approach provided by @IsraelHoletz.
Function ArrayUnique(ByRef aArrayIn() As Long) As Variant
Dim aArrayOut() As Variant, bFlag As Boolean, vIn As Variant, vOut As Variant
Dim i As Long, j As Long, k As Long
ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
i = LBound(aArrayIn)
j = i
For Each vIn In aArrayIn
For k = j To i - 1
If vIn = aArrayOut(k) Then bFlag = True: Exit For
Next
If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
bFlag = False
Next
If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
ArrayUnique = aArrayOut
End Function
Function DirectTest(ByRef aArray() As Long, Lim As Long) As Variant
Dim aReturn() As Variant
Dim StrtTime As Long, Endtime As Long, i As Long
aReturn = ArrayUnique(aArray)
DirectTest = aReturn
End Function
Here is the benchmark function that compares all of the functions. You should note that the last two cases are handled a little bit different because of memory issues. Also note, that I didn't test the Collection
method for the Test Case Size = 10,000,000
. For some reason, it was returning incorrect results and behaving unusual (I'm guessing the collection object has a limit on how many things you can put in it. I searched and I couldn't find any literature on this).
Function UltimateTest(Lim As Long, bTestDirect As Boolean, bTestDictionary, bytCase As Byte) As Variant
Dim dictionTest, collectTest, sortingTest1, indexTest1, directT '' all variants
Dim arrTest() As Long, i As Long, bEquality As Boolean, SizeUnique As Long
Dim myArray() As Long, StrtTime As Double, EndTime1 As Variant
Dim EndTime2 As Double, EndTime3 As Variant, EndTime4 As Double
Dim EndTime5 As Double, EndTime6 As Double, sortingTest2, indexTest2
ReDim myArray(1 To Lim): Rnd (-2) '' If you want to test negative numbers,
'' insert this to the left of CLng(Int(Lim... : (-1) ^ (Int(2 * Rnd())) *
For i = LBound(myArray) To UBound(myArray): myArray(i) = CLng(Int(Lim * Rnd() + 1)): Next i
arrTest = myArray
If bytCase = 1 Then
If bTestDictionary Then
StrtTime = Timer: dictionTest = DictionaryTest(arrTest, Lim): EndTime1 = Timer - StrtTime
Else
EndTime1 = "Not Tested"
End If
arrTest = myArray
collectTest = CollectionTest(arrTest, Lim)
arrTest = myArray
StrtTime = Timer: sortingTest1 = SortingUniqueTest(arrTest, True): EndTime2 = Timer - StrtTime
SizeUnique = UBound(sortingTest1, 2)
If bTestDirect Then
arrTest = myArray: StrtTime = Timer: directT = DirectTest(arrTest, Lim): EndTime3 = Timer - StrtTime
Else
EndTime3 = "Not Tested"
End If
arrTest = myArray
StrtTime = Timer: indexTest1 = IndexSort(arrTest, True): EndTime4 = Timer - StrtTime
arrTest = myArray
StrtTime = Timer: sortingTest2 = SortingUniqueTest(arrTest, False): EndTime5 = Timer - StrtTime
arrTest = myArray
StrtTime = Timer: indexTest2 = IndexSort(arrTest, False): EndTime6 = Timer - StrtTime
bEquality = True
For i = LBound(sortingTest1, 2) To UBound(sortingTest1, 2)
If Not CLng(collectTest(0)(i)) = sortingTest1(1, i) Then
bEquality = False
Exit For
End If
Next i
For i = LBound(dictionTest) To UBound(dictionTest)
If Not dictionTest(i) = sortingTest1(1, i + 1) Then
bEquality = False
Exit For
End If
Next i
For i = LBound(dictionTest) To UBound(dictionTest)
If Not dictionTest(i) = indexTest1(1, i + 1) Then
bEquality = False
Exit For
End If
Next i
If bTestDirect Then
For i = LBound(dictionTest) To UBound(dictionTest)
If Not dictionTest(i) = directT(i + 1) Then
bEquality = False
Exit For
End If
Next i
End If
UltimateTest = Array(bEquality, EndTime1, EndTime2, EndTime3, EndTime4, _
EndTime5, EndTime6, collectTest(1), collectTest(2), SizeUnique)
ElseIf bytCase = 2 Then
arrTest = myArray
collectTest = CollectionTest(arrTest, Lim)
UltimateTest = Array(collectTest(1), collectTest(2))
ElseIf bytCase = 3 Then
arrTest = myArray
StrtTime = Timer: sortingTest1 = SortingUniqueTest(arrTest, True): EndTime2 = Timer - StrtTime
SizeUnique = UBound(sortingTest1, 2)
UltimateTest = Array(EndTime2, SizeUnique)
ElseIf bytCase = 4 Then
arrTest = myArray
StrtTime = Timer: indexTest1 = IndexSort(arrTest, True): EndTime4 = Timer - StrtTime
UltimateTest = EndTime4
ElseIf bytCase = 5 Then
arrTest = myArray
StrtTime = Timer: sortingTest2 = SortingUniqueTest(arrTest, False): EndTime5 = Timer - StrtTime
UltimateTest = EndTime5
ElseIf bytCase = 6 Then
arrTest = myArray
StrtTime = Timer: indexTest2 = IndexSort(arrTest, False): EndTime6 = Timer - StrtTime
UltimateTest = EndTime6
End If
End Function
And finally, here is the sub that produces the table above.
Sub GetBenchmarks()
Dim myVar, i As Long, TestCases As Variant, j As Long, temp
TestCases = Array(1000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000)
For j = 0 To 11
If j < 6 Then
myVar = UltimateTest(CLng(TestCases(j)), True, True, 1)
ElseIf j < 10 Then
myVar = UltimateTest(CLng(TestCases(j)), False, True, 1)
ElseIf j < 11 Then
myVar = Array("Not Tested", "Not Tested", 0.1, "Not Tested", 0.1, 0.1, 0.1, 0, 0, 0)
temp = UltimateTest(CLng(TestCases(j)), False, False, 2)
myVar(7) = temp(0): myVar(8) = temp(1)
temp = UltimateTest(CLng(TestCases(j)), False, False, 3)
myVar(2) = temp(0): myVar(9) = temp(1)
myVar(4) = UltimateTest(CLng(TestCases(j)), False, False, 4)
myVar(5) = UltimateTest(CLng(TestCases(j)), False, False, 5)
myVar(6) = UltimateTest(CLng(TestCases(j)), False, False, 6)
Else
myVar = Array("Not Tested", "Not Tested", 0.1, "Not Tested", 0.1, 0.1, 0.1, "Not Tested", "Not Tested", 0)
temp = UltimateTest(CLng(TestCases(j)), False, False, 3)
myVar(2) = temp(0): myVar(9) = temp(1)
myVar(4) = UltimateTest(CLng(TestCases(j)), False, False, 4)
myVar(5) = UltimateTest(CLng(TestCases(j)), False, False, 5)
myVar(6) = UltimateTest(CLng(TestCases(j)), False, False, 6)
End If
Cells(4 + j, 6) = TestCases(j)
For i = 1 To 9: Cells(4 + j, 6 + i) = myVar(i - 1): Next i
Cells(4 + j, 17) = myVar(9)
Next j
End Sub
Summary
From the table of results, we can see that the Dictionary
method works really well for cases less than about 500,000, however, after that, the IndexMethod
really starts to dominate. You will notice that when order doesn't matter and your data is made up of positive integers, there is no comparison to the IndexMethod
algorithm (it returns the unique values from an array containing 10 million elements in less than 1 sec!!! Incredible!). Below I have a breakdown of which algorithm is preferred in various cases.
Case 1
Your Data contains integers (i.e. whole numbers, both positive and negative): IndexMethod
Case 2
Your Data contains non-integers (i.e. variant, double, string, etc.) with less than 200000 elements: Dictionary Method
Case 3
Your Data contains non-integers (i.e. variant, double, string, etc.) with more than 200000 elements: Collection Method
If you had to choose one algorithm, in my opinion, the Collection
method is still the best as it only requires a few lines of code, it's super general, and it's fast enough.
It is very friendly framework for Notification Area Application... it is enough to add NotificationIcon to base form and change auto-generated code to code below:
public partial class Form1 : Form
{
private bool hidden = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ShowInTaskbar = false;
//this.WindowState = FormWindowState.Minimized;
this.Hide();
hidden = true;
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
if (hidden) // this.WindowState == FormWindowState.Minimized)
{
// this.WindowState = FormWindowState.Normal;
this.Show();
hidden = false;
}
else
{
// this.WindowState = FormWindowState.Minimized;
this.Hide();
hidden = true;
}
}
}
For me, ensuring that I had:
#include <iostream>
#include<string>
using namespace std;
in my file made something like to_string(12345)
work.
My version is a simple fast encoder (decoder) of Base64 for C++Builder.
// ---------------------------------------------------------------------------
UnicodeString __fastcall TExample::Base64Encode(void *data, int length)
{
if (length <= 0)
return L"";
static const char set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char *in = (unsigned char*)data;
char *pos, *out = pos = new char[((length - 1) / 3 + 1) << 2];
while ((length -= 3) >= 0)
{
pos[0] = set[in[0] >> 2];
pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];
pos[2] = set[((in[1] & 0x0F) << 2) | (in[2] >> 6)];
pos[3] = set[in[2] & 0x3F];
pos += 4;
in += 3;
};
if ((length & 2) != 0)
{
pos[0] = set[in[0] >> 2];
if ((length & 1) != 0)
{
pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];
pos[2] = set[(in[1] & 0x0F) << 2];
}
else
{
pos[1] = set[(in[0] & 0x03) << 4];
pos[2] = '=';
};
pos[3] = '=';
pos += 4;
};
UnicodeString code = UnicodeString(out, pos - out);
delete[] out;
return code;
};
// ---------------------------------------------------------------------------
int __fastcall TExample::Base64Decode(const UnicodeString &code, unsigned char **data)
{
int length;
if (((length = code.Length()) == 0) || ((length & 3) != 0))
return 0;
wchar_t *str = code.c_str();
unsigned char *pos, *out = pos = new unsigned char[(length >> 2) * 3];
while (*str != 0)
{
length = -1;
int shift = 18, bits = 0;
do
{
wchar_t s = str[++length];
if ((s >= L'A') && (s <= L'Z'))
bits |= (s - L'A') << shift;
else if ((s >= L'a') && (s <= L'z'))
bits |= (s - (L'a' - 26)) << shift;
else if (((s >= L'0') && (s <= L'9')))
bits |= (s - (L'0' - 52)) << shift;
else if (s == L'+')
bits |= 62 << shift;
else if (s == L'/')
bits |= 63 << shift;
else if (s == L'=')
{
length--;
break;
}
else
{
delete[] out;
return 0;
};
}
while ((shift -= 6) >= 0);
pos[0] = bits >> 16;
pos[1] = bits >> 8;
pos[2] = bits;
pos += length;
str += 4;
};
*data = out;
return pos - out;
};
//---------------------------------------------------------------------------
I hope this isn't leading too far away from the posted question, but setting the default editor and then using
git commit -e
might be much more comfortable.
A memory heap is a location in memory where memory may be allocated at random access.
Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated.
Programmatically, you could use:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
The ProGit book has a very good explanation:
Tracking Branches
Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push
, Git automatically knows which server and branch to push to. Also, running git pull
while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch.
When you clone a repository, it generally automatically creates a master branch that tracks origin/master. That’s why git push
and git pull
work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on origin and don’t track the master branch. The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]
. If you have Git version 1.6.2 or later, you can also use the --track
shorthand:
$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "serverfix"
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
$ git checkout -b sf origin/serverfix
Branch sf set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "sf"
Now, your local branch sf
will automatically push to and pull from origin/serverfix
.
BONUS: extra git status
info
With a tracking branch, git status
will tell you whether how far behind your tracking branch you are - useful to remind you that you haven't pushed your changes yet! It looks like this:
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
or
$ git status
On branch dev
Your branch and 'origin/dev' have diverged,
and have 3 and 1 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
If you changed my.ini
and restarted mysql
and you still get this error please check your file path and replace "\"
to "/"
.
I solved my proplem after replacing.
Give an ID to uniquely identify the button, lets say myBtn
// when DOM is ready
$(document).ready(function () {
// Attach Button click event listener
$("#myBtn").click(function(){
// show Modal
$('#myModal').modal('show');
});
});
I found at least three ways of doing this:
public getters
on your entity that you try to serialize;public getters
. This will change the default for Jackson from Visbility=DEFAULT
to @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
where any access modifiers are accepted;ObjectMapper
globally by setting objectMapperInstance.setVisibility(JsonMethod.FIELD, Visibility.ANY);
. This should be avoided if you don't need this functionality globally.Choose based on your needs.
I made a jsben.ch for you http://jsben.ch/#/aWxtF ...seems that indexOf is a bit faster.
Two other alternatives:
a combination of NULLIF
and NVL2
. You can only use this if emp_id
is NOT NULL
, which it is in your case:
select nvl2(nullif(emp_id,1),'False','True') from employee;
simple CASE
expression (Mt. Schneiders used a so-called searched CASE
expression)
select case emp_id when 1 then 'True' else 'False' end from employee;
You could search for:
<li><a href="#">[^\n]+
And replace with:
$0</a>
Where $0
is the whole match. The exact semantics will depend on the language are you using though.
WARNING: You should avoid parsing HTML with regex. Here's why.
For me the solution was to add the following line to the layout:
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
...
>
And \n shows up as a new line in the visual editor. Hope it helps!
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
This is a rewrite of the great post by @Kay, which throws IOException and provides an early exit:
/**
* Gets image dimensions for given file
* @param imgFile image file
* @return dimensions of image
* @throws IOException if the file is not a known image
*/
public static Dimension getImageDimension(File imgFile) throws IOException {
int pos = imgFile.getName().lastIndexOf(".");
if (pos == -1)
throw new IOException("No extension for file: " + imgFile.getAbsolutePath());
String suffix = imgFile.getName().substring(pos + 1);
Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
while(iter.hasNext()) {
ImageReader reader = iter.next();
try {
ImageInputStream stream = new FileImageInputStream(imgFile);
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
return new Dimension(width, height);
} catch (IOException e) {
log.warn("Error reading: " + imgFile.getAbsolutePath(), e);
} finally {
reader.dispose();
}
}
throw new IOException("Not a known image file: " + imgFile.getAbsolutePath());
}
I guess my rep is not high enough for my input to be considered worthy as a reply.
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
Because it appends an element to a list? Push is usually used when referring to stacks.
Make sure Tomcat is not currently running and the PID file is removed. Them you should start Tomcat successfully.
If you start fresh then:
setenv.sh
file in <CATALINA_HOME>/bin
.CATALINA_PID=/tmp/tomcat.pid
(or other directory of your choice) so you have more control over the Tomcat process.Then to start Tomcat find catalina.sh
in <CATALINA_HOME>/bin
and execute:
./catalina.sh start
and to stop it run:
./catalina.sh stop 10 -force
From catalina.sh
script's doc:
./catalina.sh
Usage: catalina.sh ( commands ... )
commands:
start Start Catalina in a separate window
stop Stop Catalina, waiting up to 5 seconds for the process to end
stop n Stop Catalina, waiting up to n seconds for the process to end
stop -force Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
stop n -force Stop Catalina, wait up to n seconds and then use kill -KILL if still running
Note: If you want to use -force
flag then setting CATALINA_PID
is mandatory.
if you have the property "MyProperty" on your data-class, then you bind the IsChecked like this.... (the converter is optional, but sometimes you need that)
<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>
This is expected.
Refer to Javadocs for split
.
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want to keep the multi dimensional array, one should nest the array brackets. see example below where one is added to every element.
>>> a = [[1, 2], [3, 4]]
>>> [[col +1 for col in row] for row in a]
[[2, 3], [4, 5]]
>>> [col +1 for row in a for col in row]
[2, 3, 4, 5]
That will only work if register_globals
is on, and it should never be on (unless of course you are defining that variable somewhere else).
Try setting the form
's action
attribute to ?
...
<form method="post" action="?">
...
</form>
You can also set it to be blank (""
), but older WebKit versions had a bug.
Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.
Use Conda
instead of pip
.
It works perfectly
conda install PyAudio
Just use GETDATE()
or GETUTCDATE()
(if you want to get the "universal" UTC time, instead of your local server's time-zone related time).
INSERT INTO [Business]
([IsDeleted]
,[FirstName]
,[LastName]
,[LastUpdated]
,[LastUpdatedBy])
VALUES
(0, 'Joe', 'Thomas',
GETDATE(), <LastUpdatedBy, nvarchar(50),>)
In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:
sudo snap stop docker
sudo snap remove docker
... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:
sudo apt purge snap
:-)
You want getActivity()
inside your class. It's better to use
yourclassname.this.getActivity()
Try this. It's helpful for you.
If you need to order your code into namespaces, just use the keyword namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use
. If in file2 you put
use foo\bar as mypath;
you need to use mypath
instead of bar
anywhere in the file:
$obj = new mypath\myObj();
Using use foo\bar;
is equal to use foo\bar as bar;
.
This is one of the dumb mistakes I've done. I spent a lot of time trying to debug this problem and tried all the responses posted above, but in the end, it was one of my many dumb mistakes.
I was using org.apache.logging.log4j.Logger
(:fml:) whereas I should have used org.apache.log4j.Logger
. Using this correct logger saved my evening.
My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.
Inside [app.config] :
First, under 'configSections', you need to add below piece of code;
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)
<log4net debug="true">
<logger name="log">
<level value="All"></level>
<appender-ref ref="RollingLogFileAppender" />
</logger>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="1" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
</layout>
</appender>
</log4net>
Inside Calling Class :
Inside the class where you are going to use this log4net, you need to declare below piece of code.
ILog log = LogManager.GetLogger("log");
Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.
log.Error("message");
Use the BigInteger
class that is a part of the Java library.
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html
Set the DIV's z-index to one larger than the other DIVs. You'll also need to make sure the DIV has a position
other than static
set on it, too.
CSS:
#someDiv {
z-index:9;
}
Read more here: http://coding.smashingmagazine.com/2009/09/15/the-z-index-css-property-a-comprehensive-look/
"void value not ignored as it ought to be" this error occurs when function like srand(time(NULL)) does not return something and you are treating it as it is returning something. As in case of pop() function in queue ,if you will store the popped element in a variable you will get the same error because it does not return anything.
Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).
This should be pretty efficient, and easier than getting the whole TPL Dataflow working:
var customers = await ids.SelectAsync(async i =>
{
ICustomerRepo repo = new CustomerRepo();
return await repo.GetCustomer(i);
});
...
public static async Task<IList<TResult>> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector, int maxDegreesOfParallelism = 4)
{
var results = new List<TResult>();
var activeTasks = new HashSet<Task<TResult>>();
foreach (var item in source)
{
activeTasks.Add(selector(item));
if (activeTasks.Count >= maxDegreesOfParallelism)
{
var completed = await Task.WhenAny(activeTasks);
activeTasks.Remove(completed);
results.Add(completed.Result);
}
}
results.AddRange(await Task.WhenAll(activeTasks));
return results;
}
Subset is a very slow function , and I personally find it useless.
I assume you have a data.frame, array, matrix called Mat
with A
, B
, C
as column names; then all you need to do is:
In the case of one condition on one column, lets say column A
Mat[which(Mat[,'A'] == 10), ]
In the case of multiple conditions on different column, you can create a dummy variable. Suppose the conditions are A = 10
, B = 5
, and C > 2
, then we have:
aux = which(Mat[,'A'] == 10)
aux = aux[which(Mat[aux,'B'] == 5)]
aux = aux[which(Mat[aux,'C'] > 2)]
Mat[aux, ]
By testing the speed advantage with system.time
, the which
method is 10x faster than the subset
method.
To do what most people would want, create a placeholder that isn't an actual line breaking character. Then you can actually combine the approaches for:
REPLACE(REPLACE(REPLACE(MyField, CHAR(13) + CHAR(10), 'something else'), CHAR(13), 'something else'), CHAR(10), 'something else')
This way you replace only once. The approach of:
REPLACE(REPLACE(MyField, CHAR(13), ''), CHAR(10), '')
Works great if you just want to get rid of the CRLF characters, but if you want a placeholder, such as
<br/>
or something, then the first approach is a little more accurate.
My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.
E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify
action. This is checked at compile time.
In Python, there is no such thing as compile time
and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify
attribute.
This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used
PowerShell currently doesn't didn't have a native Inline If (or ternary If) but you could consider to use the custom cmdlet:
IIf <condition> <condition-is-true> <condition-is-false>
Here is a working css, tested under Firefox / IE7 / Safari / Chrome / Opera.
* {margin:0px;padding:0px;overflow:hidden}
div {position:absolute}
div#header {top:0px;left:0px;right:0px;height:60px}
div#wrapper {top:60px;left:0px;right:0px;bottom:0px;}
div#left {top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}
div#right {top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}
"overflow-y" is not w3c-approved, but every major browser supports it. Your two divs #left and #right will display a vertical scrollbar if their content is too high.
For this to work under IE7, you have to trigger the standards-compliant mode by adding a DOCTYPE :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"_x000D_
"http://www.w3.org/TR/html4/strict.dtd">_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
<style type="text/css">_x000D_
*{margin:0px;padding:0px;overflow:hidden}_x000D_
div{position:absolute}_x000D_
div#header{top:0px;left:0px;right:0px;height:60px}_x000D_
div#wrapper{top:60px;left:0px;right:0px;bottom:0px;}_x000D_
div#left{top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}_x000D_
div#right{top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div id="header"></div>_x000D_
<div id="wrapper">_x000D_
<div id="left"><div style="height:1000px">high content</div></div>_x000D_
<div id="right"></div>_x000D_
</div>_x000D_
</body>
_x000D_
I know this questions has been answered, however the reason this is happening to you, was probably because you did not add your username to the docker group.
Here are the steps to do it:
Add the docker group if it doesn't already exist:
sudo groupadd docker
Add the connected user ${USER}
to the docker group. Change the user name to match your preferred user:
sudo gpasswd -a ${USER} docker
Restart the Docker daemon:
sudo service docker restart
If you are on Ubuntu 14.04-15.10* use docker.io instead:
sudo service docker.io restart
(If you are on Ubuntu 16.04 the service is named "docker" simply)
Either do a newgrp
docker or log out/in to activate the changes to groups.
There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net
Using that it's quite easy to only display content for a mobile:
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
// Check for any mobile device.
if ($detect->isMobile()){
// mobile content
}
else {
// other content for desktops
}
If your return type is an array then return an empty array otherwise return null.
Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)
In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.
You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.
First it's presented the method with recording in a text file on the server, than the method with MySQL table.
To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.
• Both scripts can be included in ".php" files (with include()
), or in ".html" files (with <script>
), as you can see in the examples presented at the bottom of this page; but the server must run PHP.
To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.
userson.txt
) and give it CHMOD 0777
permissions (in your FTP application, right click on that file, choose Properties, then select Read
, Write
, and Execute
options).usersontxt.php
) having the code below, then copy this php file in the same directory as userson.txt
.The code for usersontxt.php
;
<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
$filetxt = 'userson.txt'; // the file in which the online users /visitors are stored
$timeon = 120; // number of secconds to keep a user online
$sep = '^^'; // characters used to separate the user name and date-time
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the line with visitors
$nrvst = 0; // to store the number of visitors
// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)
$addrow[] = $uvon. $sep. time();
// check if the file from $filetxt exists and is writable
if(is_writable($filetxt)) {
// get into an array the lines added in $filetxt
$ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$nrrows = count($ar_rows);
// number of rows
// if there is at least one line, parse the $ar_rows array
if($nrrows>0) {
for($i=0; $i<$nrrows; $i++) {
// get each line and separate the user /visitor and the timestamp
$ar_line = explode($sep, $ar_rows[$i]);
// add in $addrow array the records in last $timeon seconds
if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
$addrow[] = $ar_rows[$i];
}
}
}
}
$nruvon = count($addrow); // total online
$usron = ''; // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
if(preg_match($rgxvst, $addrow[$i])) $nrvst++; // increment the visitors
else {
// gets and stores the user's name
$ar_usron = explode($sep, $addrow[$i]);
$usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
}
}
$nrusr = $nruvon - $nrvst; // gets the users (total - visitors)
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
4.To show the number of online visitors /users in a ".html" file, use this code:
<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>
This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table
To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.
The code for create_userson.php
:
<?php
header('Content-type: text/html; charset=utf-8');
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());
// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
`uvon` VARCHAR(32) PRIMARY KEY,
`dt` INT(10) UNSIGNED NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci";
// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;
$conn->close();
?>
userson
table (For explanations about the code, see the comments in script).usersmysql.php
):
In both file you must add your personal data for connecting to MySQL database, in the variables: $host
, $user
, $pass
, and $dbname
.The code for usersmysql.php:
<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start(); // start Session, if not already started
// HERE add your data for connecting to MySQ database
$host = 'localhost'; // MySQL server address
$user = 'root'; // User name
$pass = 'password'; // User`s password
$dbname = 'database'; // Database name
/*
If you have an user registration script,
replace $_SESSION['nume'] with the variable in which the user name is stored.
You can get a free registration script from: http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/
// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-'; // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;
$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i'; // regexp to recognize the rows with visitors
$dt = time(); // current timestamp
$timeon = 120; // number of secconds to keep a user online
$nrvst = 0; // to store the number of visitors
$nrusr = 0; // to store the number of usersrs
$usron = ''; // to store the name of logged users
// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);
// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";
// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);
// if the $result contains at least one row
if ($result->num_rows > 0) {
// traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
while($row = $result->fetch_assoc()) {
if(preg_match($rgxvst, $row['uvon'])) $nrvst++; // increment the visitors
else {
$nrusr++; // increment the users
$usron .= '<br/> - <i>'.$row['uvon']. '</i>'; // stores the user's name
}
}
}
$conn->close(); // close the MySQL connection
// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';
// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";
echo $reout; // output /display the result
?>
After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.
Include the usersmysql.php
file in the php file in which you want to display the number of online users and visitors.
Or, if you want to insert it in a ".html" file, add this code:
Examples using these scripts
• Including the "usersontxt.php` in a php file:
<!doctype html>
Counter Online Users and Visitors• Including the "usersmysql.php" in a html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Counter Online Users and Visitors</title>
<meta name="description" content="PHP script to count and show the number of online users and visitors" />
<meta name="keywords" content="online users, online visitors" />
</head>
<body>
<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>
</body>
</html>
Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5
Visitors: 3 Users: 2
The problem is that every System.BadImageFormatException: Could not load file or assembly
including the ones not associated with installutil.exe
at all point to this very thread.
If your issue is related to WindowsBase
or PresentationFramework
dlls and you got analyzers installed make sure to either have them
installed for all of the projects in your solution or for none of
them.
Reference the entire framework in .csproj
file of your library rather than just the two dlls
:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<RazorLangVersion>3.0</RazorLangVersion>
<UseWpf>True</UseWpf>
</PropertyGroup>
Remove bin
and obj
dirs, clean solution and rebuild.
Here is one combining noquote
and paste
:
noquote(paste("Argument is of length zero",sQuote("!"),"and",dQuote("double")))
#[1] Argument is of length zero ‘!’ and “double”
You mean remote debug JBoss from Eclipse ?
From Configuring Eclipse for Remote Debugging:
Set the JAVA_OPTS variable as follows:
set JAVA_OPTS= -Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%
or:
JAVA_OPTS="-Xdebug -Xnoagent
-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n $JAVA_OPTS"
In the Debug frame, select the Remote Java Application node.
In the Connection Properties, specify localhost
as the Host and specify the Port as the port that was specified in the run batch script of the JBoss server, 8787
.
select sys_extract_utc(systimestamp) from dual;
Won't work on Oracle 8, though.
What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer
and java.util.Observable
In it's simplest form, use the answer of Georg Fritzsche
For a bit advanced, you can use this,
QString QString::arg ( int a, int fieldWidth = 0, int base = 10, const QChar & fillChar = QLatin1Char( ' ' ) ) const
Get the documentation and an example here..
There is also a property resourceRef
of JndiObjectFactoryBean
that is, when set to true
, used to automatically prepend the string java:comp/env/
if it is not already present.
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/loc"/>
<property name="resourceRef" value="true"/>
</bean>
Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain
to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.
Adding .
before \r\n
makes it work if the original string before \r\n
has no .
Other characters may work. I didn't try.
With or without the three lines including IsBodyHtml, not a matter.
you can use CONVERT(TIME,GETDATE())
in this case:
INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))
or if you want print it or return that time use like this:
DECLARE @dt TIME
SET @dt = CONVERT(TIME,GETDATE())
PRINT @dt
#include <stdbool.h>
For someone like me here to copy and paste.
Django database objects use the same save() method for creating and changing objects.
obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()
How Django knows to UPDATE vs. INSERT
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
Ref.: https://docs.djangoproject.com/en/1.9/ref/models/instances/
$('div#imageContainer').click(function () {
$('div#imageContainerimg').attr('src', 'YOUR NEW IMAGE URL HERE');
});
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
Sorry to resurrect an old question, but I thought I might contribute a couple of very basic examples and for-dummies explanations. None of the other answers posted thusfar illustrate syntax like the MDN guide's first example, which is about as basic as one can get.
Getter:
var settings = {
firstname: 'John',
lastname: 'Smith',
get fullname() { return this.firstname + ' ' + this.lastname; }
};
console.log(settings.fullname);
... will log John Smith
, of course. A getter behaves like a variable object property, but offers the flexibility of a function to calculate its returned value on the fly. It's basically a fancy way to create a function that doesn't require () when calling.
Setter:
var address = {
set raw(what) {
var loc = what.split(/\s*;\s*/),
area = loc[1].split(/,?\s+(\w{2})\s+(?=\d{5})/);
this.street = loc[0];
this.city = area[0];
this.state = area[1];
this.zip = area[2];
}
};
address.raw = '123 Lexington Ave; New York NY 10001';
console.log(address.city);
... will log New York
to the console. Like getters, setters are called with the same syntax as setting an object property's value, but are yet another fancy way to call a function without ().
See this jsfiddle for a more thorough, perhaps more practical example. Passing values into the object's setter triggers the creation or population of other object items. Specifically, in the jsfiddle example, passing an array of numbers prompts the setter to calculate mean, median, mode, and range; then sets object properties for each result.
You could use --where option on mysqldump to produce an output that you are waiting for:
mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql
At most 100 rows from test.t1 will be dumped from database table.
Cheers, WB
The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file. Then you can refer matplotlib to it like this (replace "crm10.ttf" with your file):
import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')
plt.show()
print(fpath)
will show you where you should put the .ttf.
You can see the output here: https://matplotlib.org/gallery/api/font_file.html
If you have several versions of Python installed, /usr/bin/env
will ensure the interpreter used is the first one on your environment's $PATH
. The alternative would be to hardcode something like #!/usr/bin/python
; that's ok, but less flexible.
In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #!
at the start of the first line, followed by the interpreter (and any flags it may need).
If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).
Here is how I solved my problem:
Directive
app.directive("directive_name", function(){
return {
restrict: 'E',
transclude: true,
template: function(elem, attr){
return '<div><h2>{{'+attr.scope+'}}</h2></div>';
},
replace: true
};
})
Controller
$scope.building = function(data){
var chart = angular.element(document.createElement('directive_name'));
chart.attr('scope', data);
$compile(chart)($scope);
angular.element(document.getElementById('wrapper')).append(chart);
}
I now can use different scopes through the same directive and append them dynamically.
A single bracket ([
) usually actually calls a program named [
; man test
or man [
for more info. Example:
$ VARIABLE=abcdef
$ if [ $VARIABLE == abcdef ] ; then echo yes ; else echo no ; fi
yes
The double bracket ([[
) does the same thing (basically) as a single bracket, but is a bash builtin.
$ VARIABLE=abcdef
$ if [[ $VARIABLE == 123456 ]] ; then echo yes ; else echo no ; fi
no
Parentheses (()
) are used to create a subshell. For example:
$ pwd
/home/user
$ (cd /tmp; pwd)
/tmp
$ pwd
/home/user
As you can see, the subshell allowed you to perform operations without affecting the environment of the current shell.
(a) Braces ({}
) are used to unambiguously identify variables. Example:
$ VARIABLE=abcdef
$ echo Variable: $VARIABLE
Variable: abcdef
$ echo Variable: $VARIABLE123456
Variable:
$ echo Variable: ${VARIABLE}123456
Variable: abcdef123456
(b) Braces are also used to execute a sequence of commands in the current shell context, e.g.
$ { date; top -b -n1 | head ; } >logfile
# 'date' and 'top' output are concatenated,
# could be useful sometimes to hunt for a top loader )
$ { date; make 2>&1; date; } | tee logfile
# now we can calculate the duration of a build from the logfile
There is a subtle syntactic difference with ( )
, though (see bash reference) ; essentially, a semicolon ;
after the last command within braces is a must, and the braces {
, }
must be surrounded by spaces.
In 2019 poetry is the package and dependency manager you are looking for.
https://github.com/sdispater/poetry#why
It's modern, simple and reliable.