Create your directory structure in src folder like
.
means to create subpkg1 folder under pkg1 folder (source folder in eclipse) then place your source code inside and then modify its package declaration.
Line continuations also can be achieved through clever use of syntax.
In the case of echo
:
# echo '-n' flag prevents trailing <CR>
echo -n "This is my one-line statement" ;
echo -n " that I would like to make."
This is my one-line statement that I would like to make.
In the case of vars:
outp="This is my one-line statement" ;
outp+=" that I would like to make." ;
echo -n "${outp}"
This is my one-line statement that I would like to make.
Another approach in the case of vars:
outp="This is my one-line statement" ;
outp="${outp} that I would like to make." ;
echo -n "${outp}"
This is my one-line statement that I would like to make.
Voila!
If you have the generated SSH key for your project from GitLab you can add it to your keychain in OS X via terminal.
ssh-add -K <ssh_generated_key_file.txt>
Once executed you will be asked for the passphrase that you entered when creating the SSH key.
Once the SSH key is in the keychain you can paste the URL from GitLab into Sourcetree like you normally would to clone the project.
overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.
overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.
overflow: hidden;
would remove both scrollbars
My solution was updating VirtualBox.
I first ran into this issue after fresh install of Docker toolbox(v1.12.5) on my Windows 8.1. What worked for me was update of VirtualBox. Then I had the same problem after some Windows Update, and updating VirtualBox fixed the issue again.
According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.
Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.
For example:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
I just talked to some Xcode engineers at WWDC and the auto discovery of iDevices is still a little buggy. Also sometimes your phone is not correctly broadcasting. Switching your device on and off can help.
There are a few workarounds/fallbacks:
You can check if your phone is broadcasting with Bonjour Browser (www.tildesoft.com). Look if your wifi address is listed under the service called '_apple-mobdev2._tcp. - 215' (you can find your wifi address here: settings > general > about > wifi address.
As a fallback you can connect to your device by manually entering the IP address (right click on your devices in the Devices window). However this IP address will be persisted, so if you change networks you'll need to reset this. That option is not available in Xcode yet, but you can do it via the terminal with the following command:
defaults read com.apple.dt.Xcode | grep IDEIDS
This will print an identifier which you need to use in the next command:
defaults delete com.apple.dt.Xcode <identifier>
Now the ip address is cleared and you can enter a new one.
The last option is to create a computer-to-computer network. This works fine, but logically you won't have internet access then.
If you revise your regular expression like this:
drupal-6.14/(?=sites(?!/all|/default)).*
^^
...then it will match all inputs that contain drupal-6.14/
followed by sites
followed by anything other than /all
or /default
. For example:
drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall
Changing ?=
to ?!
to match your original regex simply negates those matches:
drupal-6.14/(?!sites(?!/all|/default)).*
^^
So, this simply means that drupal-6.14/
now cannot be followed by sites
followed by anything other than /all
or /default
. So now, these inputs will satisfy the regex:
drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42
But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/
is followed by anything other than sites
as well. For example:
drupal-6.14/foo
drupal-6.14/xsites
Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14
except those subdirectories of sites
whose name begins with anything other than all
or default
.
This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:
$(function () {
var timerId = 0;
$('textarea').focus(function () {
clearInterval(timerId);
});
$('textarea').blur(function () {
timerId = setInterval(function () {
//some code here
}, 1000);
});
});
Very basic model with Gender field. GetGenderSelectItems()
returns select items needed to populate DropDownList.
public enum Gender
{
Male, Female
}
public class MyModel
{
public Gender Gender { get; set; }
public static IEnumerable<SelectListItem> GetGenderSelectItems()
{
yield return new SelectListItem { Text = "Male", Value = "Male" };
yield return new SelectListItem { Text = "Female", Value = "Female" };
}
}
Please make sure you wrapped your @Html.DropDownListFor
in a form tag.
@model MyModel
@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
@Html.DropDownListFor(m => m.Gender, MyModel.GetGenderSelectItems())
<input type="submit" value="Send" />
}
Your .cshtml Razor view name should be the same as controller action name and folder name should match controller name e.g Views\MyController\MyAction.cshtml
.
public class MyController : Controller
{
public ActionResult MyAction()
{
// shows your form when you load the page
return View();
}
[HttpPost]
public ActionResult MyAction(MyModel model)
{
// the value is received in the controller.
var selectedGender = model.Gender;
return View(model);
}
}
Now let's make it strongly-typed and enum independent:
var genderSelectItems = Enum.GetValues(typeof(Gender))
.Cast<string>()
.Select(genderString => new SelectListItem
{
Text = genderString,
Value = genderString,
}).AsEnumerable();
Late to answer, but no-one has specified that css property with dash won't work in object declaration in jquery:
.css({margin-left:'200px'});//won't work
.css({marginLeft:'200px'});//works
So, do not forget to use quotes if you prefer to use dash style property in jquery code.
.css({'margin-left':'200px'});//works
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
I think currently your api's actually responding the way it should. The first 100 records on the page in the overall order of objects you are maintaining. Your explanation tells that you are using some kind of ordering ids to define the order of your objects for pagination.
Now, in case you want that page 2 should always start from 101 and end at 200, then you must make the number of entries on the page as variable, since they are subject to deletion.
You should do something like the below pseudocode:
page_max = 100
def get_page_results(page_no) :
start = (page_no - 1) * page_max + 1
end = page_no * page_max
return fetch_results_by_id_between(start, end)
Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""
import java.util.Scanner;
class SwiCas {
public static void main(String as[]) {
Scanner s= new Scanner(System.in);
char a=s.next().charAt(0);//this line shows how to take character input in java
switch(a) {
case 'a':
System.out.println("Vowel....");
break;
case 'e':
System.out.println("Vowel....");
break;
case 'i':
System.out.println("Vowel....");
break;
case 'o':
System.out.println("Vowel....");
break;
case 'u':
System.out.println("Vowel....");
break;
case 'A':
System.out.println("Vowel....");
break;
case 'E':
System.out.println("Vowel....");
break;
case 'I':
System.out.println("Vowel....");
break;
case 'O':
System.out.println("Vowel....");
break;
case 'U':
System.out.println("Vowel....");
break;
default:
System.out.println("Consonants....");
}
}
}
.NET 3.5 and newer have a new public type, System.Data.Linq.Binary
that encapsulates byte[]
. It implements IEquatable<Binary>
that (in effect) compares two byte arrays. Note that System.Data.Linq.Binary
also has implicit conversion operator from byte[]
.
MSDN documentation:System.Data.Linq.Binary
Reflector decompile of the Equals method:
private bool EqualsTo(Binary binary)
{
if (this != binary)
{
if (binary == null)
{
return false;
}
if (this.bytes.Length != binary.bytes.Length)
{
return false;
}
if (this.hashCode != binary.hashCode)
{
return false;
}
int index = 0;
int length = this.bytes.Length;
while (index < length)
{
if (this.bytes[index] != binary.bytes[index])
{
return false;
}
index++;
}
}
return true;
}
Interesting twist is that they only proceed to byte-by-byte comparison loop if hashes of the two Binary objects are the same. This, however, comes at the cost of computing the hash in constructor of Binary
objects (by traversing the array with for
loop :-) ).
The above implementation means that in the worst case you may have to traverse the arrays three times: first to compute hash of array1, then to compute hash of array2 and finally (because this is the worst case scenario, lengths and hashes equal) to compare bytes in array1 with bytes in array 2.
Overall, even though System.Data.Linq.Binary
is built into BCL, I don't think it is the fastest way to compare two byte arrays :-|.
This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number
$('#help_number').keyup(function(){
$(this).val().match(/\d+/g).join("")
});
Explanation:
str= "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give a array of string as output >> ["34", "56766"]
str.match(/\d+/g).join("")
join will convert and concatenate that array data into single string
output >> "3456766"
In my example I need the output as 209-356-6788 so I used replace
$('#help_number').keyup(function(){
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
Using sn.exe utility:
sn -T YourAssembly.dll
or loading the assembly in Reflector.
Setting windowLightStatusBar
to true
not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc.
I've found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.
And I think, it would be better to tell your customer that coloring status bar (for example) white - is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark
according to the guidelines
If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:
CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();
it should be slightly faster since it doesn't need to parse an input format.
For money: decimal
. It costs a little more memory, but doesn't have rounding troubles like double
sometimes has.
Did you choose the customized version of Bootstrap? There is an issue that the font files included in the customized package are broken (see https://github.com/twbs/bootstrap/issues/9925). If you do not want to use the CDN, you have to download them manually and replace your own fonts with the downloaded ones:
https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot
After that try a strong reload (CTRL + F5), hope it helps.
You can use FileInfo object to get all information of your file.
FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
MessageBox.Show(f.Name);
MessageBox.Show(f.FullName);
MessageBox.Show(f.Extension );
MessageBox.Show(f.DirectoryName);
Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html
You could default the parameter to null
or false
.
This way, it would be shorter to test if a value has been passed as parameter.
@mixin clearfix($width: null) {
@if not ($width) {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
Officially, ConstraintLayout
is much faster
In the N release of Android, the
ConstraintLayout
class provides similar functionality toRelativeLayout
, but at a significantly lower cost.
Convert text to string array where separating each value by comma, and trim every field, for example:
String[] stringArray = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);
If you are using Toolbar, you don't need those solutions. You only have to change the theme of the toolbar
app:theme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
If you are using a dark.actionBar your back button is going to be white else if you are using light actionbar theme it is going to be black.
Which one of those is indexable?
This one is definitely btree-indexable:
WHERE title >= '0' AND title < ':'
Note that ':' comes after '9' in ASCII.
I have had this error for some time as well. It might be some kind of netbeans bug that has to do with netbeans connector. I can't find any mention of favicon.ico
in my code or in the project settings.
I was able to fix it by putting the following line in the head
section of my html file
<link rel="shortcut icon" href="#">
I am currently using this in my testing environment, but I would remove it for any production environment.
type which java
in terminal to show where it is installed.
Specify the Class Card for the constructor-:
void Card::Card(Card::Rank rank, Card::Suit suit) {
And also define the default constructor and destructor.
import numpy
a = numpy.array([1,2,3])
with open(r'test.txt', 'w') as f:
f.write(" ".join(map(str, a)))
I had the same problem using Android Studio 1.5.1.
This was solved by using the Android SDK Manager and updating Android Support Library, as well as Local Maven repository for Support Libraries.
After updating the SDK and restarting Android Studio, the problem was rectified.
Hope this helps anyone who has the same problem after trying other suggestions.
For RHEL/CentOS, run "python --version" command to find out Python version. E.g. below:
$ python --version
Python 2.7.12
Now run "sudo yum search lxml" to find out python*-lxml package.
$ sudo yum search lxml
Failed to set locale, defaulting to C
Loaded plugins: priorities, update-motd, upgrade-helper
1014 packages excluded due to repository priority protections
============================================================================================================= N/S matched: lxml =============================================================================================================
python26-lxml-docs.noarch : Documentation for python-lxml
python27-lxml-docs.noarch : Documentation for python-lxml
python26-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt
python27-lxml.x86_64 : ElementTree-like Python bindings for libxml2 and libxslt
Now you can choose package as per your Python version and run command like below:
$ sudo yum install python27-lxml.x86_64
Please use a <pre>
tag
demo : http://jsfiddle.net/K83cK/
var data = {_x000D_
"data": {_x000D_
"x": "1",_x000D_
"y": "1",_x000D_
"url": "http://url.com"_x000D_
},_x000D_
"event": "start",_x000D_
"show": 1,_x000D_
"id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
Index access (mentioned here) is the practical difference. If you need to access the successor or predecessor, you need SortedList. SortedDictionary cannot do that so you are fairly limited with how you can use the sorting (first / foreach).
Since nobody has yet mentioned this, if you are using C# version 6 or above (i.e. Visual Studio 2015) then you can use string interpolation to simplify your code. So instead of using string.Format(...)
, you can just do this:
Key = $"{i:D2}";
You just need to specify the Position
column to be an ordered factor where the levels are ordered by their counts:
theTable <- transform( theTable,
Position = ordered(Position, levels = names( sort(-table(Position)))))
(Note that the table(Position)
produces a frequency-count of the Position
column.)
Then your ggplot
function will show the bars in decreasing order of count.
I don't know if there's an option in geom_bar
to do this without having to explicitly create an ordered factor.
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
This is my implementation to convert any kind of encoding to UTF-8 without BOM and replacing windows enlines by universal format:
def utf8_converter(file_path, universal_endline=True):
'''
Convert any type of file to UTF-8 without BOM
and using universal endline by default.
Parameters
----------
file_path : string, file path.
universal_endline : boolean (True),
by default convert endlines to universal format.
'''
# Fix file path
file_path = os.path.realpath(os.path.expanduser(file_path))
# Read from file
file_open = open(file_path)
raw = file_open.read()
file_open.close()
# Decode
raw = raw.decode(chardet.detect(raw)['encoding'])
# Remove windows end line
if universal_endline:
raw = raw.replace('\r\n', '\n')
# Encode to UTF-8
raw = raw.encode('utf8')
# Remove BOM
if raw.startswith(codecs.BOM_UTF8):
raw = raw.replace(codecs.BOM_UTF8, '', 1)
# Write to file
file_open = open(file_path, 'w')
file_open.write(raw)
file_open.close()
return 0
You can use it in the same datafram (df) using the previously provided code
df[!grepl("REVERSE", df$Name),]
or you might assign a different name to the datafram using this code
df1<-df[!grepl("REVERSE", df$Name),]
Check target-membership of PrimeNumberModel.swift in your testing target.
Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.
Hashing:
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
Verifying:
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
It is easier to use UseWaitCursor at the Form or Window level. A typical use case can look like below:
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Enabled = false;//optional, better target a panel or specific controls
this.UseWaitCursor = true;//from the Form/Window instance
Application.DoEvents();//messages pumped to update controls
//execute a lengthy blocking operation here,
//bla bla ....
}
finally
{
this.Enabled = true;//optional
this.UseWaitCursor = false;
}
}
For a better UI experience you should use Asynchrony from a different thread.
Are you looking for
\begin{cases}
math text
\end{cases}
It wasn't very clear from the description. But may be this is what you are looking for http://en.wikipedia.org/wiki/Help:Displaying_a_formula#Continuation_and_cases
With:
FILES = $(shell ls)
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.1)
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
as your shell command.
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
1The GNU Make documentation notes further that POSIX make added ::=
assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make
variants support ::=
assignment, although GNU make does today, with the same meaning as :=
, i.e., do the assignment right now with expansion.
Note that VAR := $(shell command args...)
can also be spelled VAR != command args...
in several make
variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell)
so using VAR != command args...
is superior in both being shorter and working in more variants.
When you need to accept a function as argument which takes no arguments and returns no result (void), in my opinion it is still best to have something like
public interface Thunk { void apply(); }
somewhere in your code. In my functional programming courses the word 'thunk' was used to describe such functions. Why it isn't in java.util.function is beyond my comprehension.
In other cases I find that even when java.util.function does have something that matches the signature I want - it still doesn't always feel right when the naming of the interface doesn't match the use of the function in my code. I guess it's a similar point that is made elsewhere here regarding 'Runnable' - which is a term associated with the Thread class - so while it may have he signature I need, it is still likely to confuse the reader.
string string1 = "This is an example string and my data is here";
string toFind1 = "my";
string toFind2 = "is";
int start = string1.IndexOf(toFind1) + toFind1.Length;
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
string string2 = string1.Substring(start, end - start);
To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:
FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY "%%I" <<NewDir>> & GOTO :END
:END
Install Entity Framework in each project (Ex: In Web, In Class Libraries) from NuGet Package Manager orelse Open Tools - Nuget Package Manager - Package Manager Console and use Install-Package EntityFramework to install the Entity Framework.
Don't need to add the below code in every config file. By default it will be added in the project where the database is called through Entity Framework.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');
I know that I’m late to the party. After looking into wonderful answers provided here, I thought mine will add some value to this post. Although the posted answers are amazing and easy to understand however, all are calculating the height to the BST in linear time. I think this can be improved and Height can be retrieved in constant time, hence writing this answer – hope you will like it. Let’s start with the Node class:
public class Node
{
public Node(string key)
{
Key = key;
Height = 1;
}
public int Height { get; set; }
public string Key { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public override string ToString()
{
return $"{Key}";
}
}
BinarySearchTree class
So you might have guessed the trick here… Im keeping node instance variable Height to keep track of each node when added. Lets move to the BinarySearchTree class that allows us to add nodes into our BST:
public class BinarySearchTree
{
public Node RootNode { get; private set; }
public void Put(string key)
{
if (ContainsKey(key))
{
return;
}
RootNode = Put(RootNode, key);
}
private Node Put(Node node, string key)
{
if (node == null) return new Node(key);
if (node.Key.CompareTo(key) < 0)
{
node.Right = Put(node.Right, key);
}
else
{
node.Left = Put(node.Left, key);
}
// since each node has height property that is maintained through this Put method that creates the binary search tree.
// calculate the height of this node by getting the max height of its left or right subtree and adding 1 to it.
node.Height = Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
return node;
}
private int GetHeight(Node node)
{
return node?.Height ?? 0;
}
public Node Get(Node node, string key)
{
if (node == null) return null;
if (node.Key == key) return node;
if (node.Key.CompareTo(key) < 0)
{
// node.Key = M, key = P which results in -1
return Get(node.Right, key);
}
return Get(node.Left, key);
}
public bool ContainsKey(string key)
{
Node node = Get(RootNode, key);
return node != null;
}
}
Once we have added the key, values in the BST, we can just call Height property on the RootNode object that will return us the Height of the RootNode tree in constant time. The trick is to keep the height updated when a new node is added into the tree. Hope this helps someone out there in the wild world of computer science enthusiast!
Unit test:
[TestCase("SEARCHEXAMPLE", 6)]
[TestCase("SEBAQRCHGEXAMPLE", 6)]
[TestCase("STUVWXYZEBAQRCHGEXAMPLE", 8)]
public void HeightTest(string data, int expectedHeight)
{
// Arrange.
var runner = GetRootNode(data);
// Assert.
Assert.AreEqual(expectedHeight, runner.RootNode.Height);
}
private BinarySearchTree GetRootNode(string data)
{
var runner = new BinarySearchTree();
foreach (char nextKey in data)
{
runner.Put(nextKey.ToString());
}
return runner;
}
Note: This idea of keeping the Height of tree maintained in every Put operation is inspired by the Size of BST method found in the 3rd chapter (page 399) of Algorithm (Fourth Edition) book.
For huge one-liners (prints characters from 1
to 99
):
cut -c 1-99 filename
Good example for Iterable to compute factorial
FactorialIterable fi = new FactorialIterable(10);
Iterator<Integer> iterator = fi.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
Short code for Java 1.8
new FactorialIterable(5).forEach(System.out::println);
Custom Iterable class
public class FactorialIterable implements Iterable<Integer> {
private final FactorialIterator factorialIterator;
public FactorialIterable(Integer value) {
factorialIterator = new FactorialIterator(value);
}
@Override
public Iterator<Integer> iterator() {
return factorialIterator;
}
@Override
public void forEach(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
Integer last = 0;
for (Integer t : this) {
last = t;
}
action.accept(last);
}
}
Custom Iterator class
public class FactorialIterator implements Iterator<Integer> {
private final Integer mNumber;
private Integer mPosition;
private Integer mFactorial;
public FactorialIterator(Integer number) {
this.mNumber = number;
this.mPosition = 1;
this.mFactorial = 1;
}
@Override
public boolean hasNext() {
return mPosition <= mNumber;
}
@Override
public Integer next() {
if (!hasNext())
return 0;
mFactorial = mFactorial * mPosition;
mPosition++;
return mFactorial;
}
}
Just so you know the iPhone 6 lies about it's min-width. It thinks it is 320 instead of 375 it is suppose to be.
@media only screen and (max-device-width: 667px)
and (-webkit-device-pixel-ratio: 2) {
}
This was the only thing I could get to work to target the iPhone 6. The 6+ works fine the using this method:
@media screen and (min-device-width : 414px)
and (max-device-height : 736px) and (max-resolution: 401dpi)
{
}
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
Firstly, try
/ except
are not functions, but statements.
To convert a string (or any other type that can be converted) to an integer in Python, simply call the int()
built-in function. int()
will raise
a ValueError
if it fails and you should catch this specifically:
>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
... try:
... print '%s as an int is %d' % (str(value), int(value))
... except ValueError as ex:
... print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
the syntax has changed slightly:
>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
... try:
... print('%s as an int is %d' % (str(value), int(value)))
... except ValueError as ex:
... print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.
For instance, ExternalResource executes code before and after a test method, without having to use @Before
and @After
. Using an ExternalResource
rather than @Before
and @After
gives opportunities for better code reuse; the same rule can be used from two different test classes.
The design was based upon: Interceptors in JUnit
For more information see JUnit wiki : Rules.
Try command + /. It works for me.
So, you just highlight the block of code you want to comment out and press those two keys.
This will validate with HTML5.
<form action="#">
FYI, sender
and e
are not specific to ASP.NET or to C#. See Events (C# Programming Guide) and Events in Visual Basic.
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
See this link --> http://www.akadia.com/services/dotnet_delegates_and_events.html
The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>
</tomcat-users>
It works for me very well
Use strncpy
e.g.
strncpy(dest, src + beginIndex, endIndex - beginIndex);
This assumes you've
dest
is large enough.endIndex
is greater than beginIndex
beginIndex
is less than strlen(src)
endIndex
is less than strlen(src)
SELECT (MONTHS_BETWEEN(date2,date1) + (datediff(day,date2,date1))/30) as num_months,
datediff(day,date2,date1) as diff_in_days FROM dual;
// You should replace date2 with TO_DATE('2012/03/25', 'YYYY/MM/DD')
// You should replace date1 with TO_DATE('2012/01/01', 'YYYY/MM/DD')
// To get you results
clip-path
This is something I feel this question has missed; clip-path
clip-path
in a nutshellClipping, with the
clip-path
property, is akin to cutting a shape (like a circle or a pentagon) from a rectangular piece of paper. The property belongs to the “CSS Masking Module Level 1” specification. The spec states, “CSS masking provides two means for partially or fully hiding portions of visual elements: masking and clipping”.
clip-path
will use the element itself rather than its borders to cut the shape you specify in its parameters. It uses a super simple percentage based co-ordinate system which makes editing it very easy and means you can pick it up and create weird and wonderful shapes in a matter of minutes.
div {_x000D_
-webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);_x000D_
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);_x000D_
background: red;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}
_x000D_
<div></div>
_x000D_
It does have a major downside at the moment, one being it's major lack of support, only really being covered within -webkit-
browsers and having no support on IE and only very partial in FireFox.
Here are some useful resources and material to help better understand clip-path
and also start creating your own.
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
It could be not supported file encoding. Change it to UTF-8 for example.
I've done this using Sublime
Acked Unseen sample
Hi guys! Just some observations from what I just found in my capture:
On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client
Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC
In the capture example above, frame 67795 sends an ACK for 10384
Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194
This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.
In Offline Web Applications (which is really any HTML5 website) applicationCache.swapCache()
can be used to update the cached version of your website without the need for manually reloading the page.
This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
See also Using the application cache on Mozilla Developer Network for more info.
Things change quickly on the Web. This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolo for pointing it out in the comments.
Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:
This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.
So does Using the application cache on Mozilla Developer Network that I referenced in 2012:
Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.
Define it as
<return type> AnalyzeArray(ArrayList<Integer> list) {
If you are trying to create mapping in your edmx file to a "function Imports", this can result this error. Just clear the fields for insert, update and delete that is located in Mapping Details for a given entity in your edmx, and it should work. I hope I made it clear.
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
If express.static
is handling the request, you need to move your middleware up:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()
when the cookie has been set.
Update
As of now the cookie parser is a seperate npm package, so instead of using
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parser
and then use it as:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
TLDR: do not append items to a series one by one, better extend with an ordered collection
I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.
You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.
By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.
The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.
If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.
Below are some code samples:
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: s = pd.Series(np.arange(4)**2, index=np.arange(4))
In [4]: s
Out[4]:
0 0
1 1
2 4
3 9
dtype: int64
In [6]: id(s.index), id(s.values)
Out[6]: (4470549648, 4470593296)
When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)
In [7]: s[2] = 14
In [8]: id(s.index), id(s.values)
Out[8]: (4470549648, 4470593296)
But when you add a new item, a new index and a new values array is generated:
In [9]: s[4] = 16
In [10]: s
Out[10]:
0 0
1 1
2 14
3 9
4 16
dtype: int64
In [11]: id(s.index), id(s.values)
Out[11]: (4470548560, 4470595056)
That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:
In [13]: new_items = {item: item**2 for item in range(5, 7)}
In [14]: s2 = pd.Series(new_items)
In [15]: s2 # keys are guaranteed to be sorted!
Out[15]:
5 25
6 36
dtype: int64
In [16]: s = s.append(s2); s
Out[16]:
0 0
1 1
2 14
3 9
4 16
5 25
6 36
dtype: int64
There are two steps you need to take.
First, you need to put the PDF in an iframe.
<iframe id="pdf" name="pdf" src="document.pdf"></iframe>
To print the iframe you can look at the answers here:
Javascript Print iframe contents only
If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>
:
<iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>
the loader can look like this:
function isLoaded()
{
var pdfFrame = window.frames["pdf"];
pdfFrame.focus();
pdfFrame.print();
}
This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).
I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.
The ONLY right way to do it with XPath :
//div[contains(concat(" ", normalize-space(@class), " "), " Test ")]
The function normalize-space
strips leading and trailing whitespace, and also replaces sequences of whitespace characters by a single space.
If not need many of these Xpath queries, you might want to use a library that converts CSS selectors to XPath, as CSS selectors are usually a lot easier to both read and write than XPath queries. For example, in this case, you could use both div[class~="Test"]
and div.Test
to get the same result.
Some libraries I've been able to find :
Here is the solution:
var isMobile = {
Android: function() {
return /Android/i.test(navigator.userAgent);
},
iOS: function() {
return /iPhone|iPad|iPod/i.test(navigator.userAgent);
}
};
if(isMobile.Android())
{
var previousWidth=$(window).width();
$(window).on({
resize: function(e) {
var YourFunction=(function(){
var screenWidth=$(window).width();
if(previousWidth!=screenWidth)
{
previousWidth=screenWidth;
alert("oreientation changed");
}
})();
}
});
}
else//mainly for ios
{
$(window).on({
orientationchange: function(e) {
alert("orientation changed");
}
});
}
The example from MySQL documentation http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html (i shrink it, documentation for this section is the same for 5.5)
mysql> create table t1 (i int, d1 double, d2 double);
mysql> insert into t1 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t1
group by
i
having a <> b; -- a != b
+------+-------------------+------+
| i | a | b |
+------+-------------------+------+
| 2 | 76.80000000000001 | 76.8 |
+------+-------------------+------+
1 row in set (0.00 sec)
Basically if you sum a you get 0-13.2+59.6+30.4 = 76.8. If we sum up b we get 0+0+46.4+30.4=76.8. The sum of a and b is the same but MySQL documentation says:
A floating-point value as written in an SQL statement may not be the same as the value represented internally.
If we repeat the same with decimal:
mysql> create table t2 (i int, d1 decimal(60,30), d2 decimal(60,30));
Query OK, 0 rows affected (0.09 sec)
mysql> insert into t2 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
Query OK, 4 rows affected (0.07 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t2
group by
i
having a <> b;
Empty set (0.00 sec)
The result as expected is empty set.
So as long you do not perform any SQL arithemetic operations you can use DOUBLE, but I would still prefer DECIMAL.
Another thing to note about DECIMAL is rounding if fractional part is too large. Example:
mysql> create table t3 (d decimal(5,2));
Query OK, 0 rows affected (0.07 sec)
mysql> insert into t3 (d) values(34.432);
Query OK, 1 row affected, 1 warning (0.10 sec)
mysql> show warnings;
+-------+------+----------------------------------------+
| Level | Code | Message |
+-------+------+----------------------------------------+
| Note | 1265 | Data truncated for column 'd' at row 1 |
+-------+------+----------------------------------------+
1 row in set (0.00 sec)
mysql> select * from t3;
+-------+
| d |
+-------+
| 34.43 |
+-------+
1 row in set (0.00 sec)
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.
UITableViewAutomaticDimension
to rowHeight & estimatedRowHeightheightForRowAt
and return a value UITableViewAutomaticDimension
to it)-
Objective C:
// in ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property IBOutlet UITableView * table;
@end
// in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.table.dataSource = self;
self.table.delegate = self;
self.table.rowHeight = UITableViewAutomaticDimension;
self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Swift:
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
// Swift 4.2 onwards
table.rowHeight = UITableView.automaticDimension
table.estimatedRowHeight = UITableView.automaticDimension
// Swift 4.1 and below
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Swift 4.2 onwards
return UITableView.automaticDimension
// Swift 4.1 and below
return UITableViewAutomaticDimension
}
For label instance in UITableviewCell
Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.
I just removed the line
.babel('resources/assets/js/app.js')
for laravel 5.6 with vue.js. in webpack.mix.js
It is an old question but i want to add that if you want to resize image according to viewport size only with css; you can use viewport units "vh (viewport height) or vw (viewport width)".
.img {
width: 100vw;
height: 100vh;
}
I happened across this due to having the same problem. I'm working with variable font size, so this takes that into account:
var texts=($(this).find('.noteContent').html()).split("<br>");
for (var k in texts) {
ctx.fillText(texts[k], left, (top+((parseInt(ctx.font)+2)*k)));
}
where .noteContent is the contenteditable div the user edited (this is nested in a jQuery each function), and ctx.font is "14px Arial" (notice that the pixel size comes first)
I found that using the Common Event described above works well and you could have the common event set up like this:
private void checkChanged(object sender, EventArgs e)
{
foreach (RadioButton r in yourPanel.Controls)
{
if (r.Checked)
textBox.Text = r.Text;
}
}
Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)
<?php if(!class_exists('PDO2')) {
class PDO2 {
private static $_instance;
public static function getInstance() {
if (!isset(self::$_instance)) {
try {
self::$_instance = new PDO(
'mysql:host=***;dbname=***',
'***',
'***',
array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int) $e->getCode());
}
}
return self::$_instance;
}
public static function closeInstance() {
return self::$_instance = null;
}
}
}
$req = PDO2::getInstance()->prepare('SELECT * FROM table');
$req->execute();
$count = $req->rowCount();
$results = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
// Do other requests maybe
// And close connection
PDO2::closeInstance();
// print output
Full example, with custom class PDO2.
An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?
memcpy(arrayOfByte, &x, sizeof x);
A simple elegant one liner that will also work with any other data type.
If you need the bytes reversed you can use std::reverse
memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);
or better yet, just copy the bytes in reverse to begin with
BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);
If you don't want to make a copy of the data at all, and just have its byte representation
BYTE* bytes = (BYTE*) &x;
I had to enable USB debugging (Security settings)
developer option in addition to USB debugging
in Redmi Note 4.
This simulates a tab through a form and gives focus to the next input when the enter key is pressed.
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var inputs = document.getElementsByClassName('input');
for (var i = 0; i < inputs.length; i++) {
if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
inputs[i+1].focus();
break;
}
}
I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.
Breaking this down to a simple answer for .Net core 3.1:
If it is a MSTest project:
rename file in project to testhost.dll.config
OR
Use post-build command provided by DeepSpace101
If you use T instead of t there is no need to jump back because the new tab will be opened, but vim's focus will simply remain within NERDTree.
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
Calculate the length of your text line and create a block which is the same size as the line of text. Center the block. If you have two lines you will need two blocks if they are different lengths. You could use a span tag and a br tag if you don't want extra spaces from the blocks. You can also use the pre tag to format inside a block.
And you can do this: style='text-align:center;'
For vertical see: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp
Here is the best way for blocks and web page layouts, go here and learn flex the new standard which started in 2009. http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#justify-content-property
Also w3schools has lots of flex examples.
Problem is that you seed the random generator again. Every time you seed it the initial state of the random number generator gets reset and the first random number you generate will be the first random number after the initial state
Hmm now that I think about it, maybe Arrays.fill
:
char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
Of course, I assume that the fill
method does the same thing as your code, so it will probably perform about the same, but at least this is fewer lines.
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:
The complete regular expression is:
-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*
So all of your listed character except “-
” and “_
” are not allowed if used directly. But you can encode them using a backslash foo\~bar
or using the unicode notation foo\7E bar
.
Using Boost's string algorithms would be easiest:
#include <boost/algorithm/string.hpp>
std::string str("hello world! ");
boost::trim_right(str);
str
is now "hello world!"
. There's also trim_left
and trim
, which trims both sides.
If you add _copy
suffix to any of above function names e.g. trim_copy
, the function will return a trimmed copy of the string instead of modifying it through a reference.
If you add _if
suffix to any of above function names e.g. trim_copy_if
, you can trim all characters satisfying your custom predicate, as opposed to just whitespaces.
You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:
http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
You can render your icon using the SVG Path notation.
See Google documentation for more information.
Here is a basic example:
var icon = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon
});
Here is a working example on how to display and scale a marker SVG icon:
Edit:
Another example here with a complex icon:
Edit 2:
And here is how you can have a SVG file as an icon:
If you are working with anaconda-project, you can query the PROJECT_ROOT from the environment variable --> os.getenv('PROJECT_ROOT'). This works only if the script is executed via anaconda-project run .
If you do not want your script run by anaconda-project, you can query the absolute path of the executable binary of the Python interpreter you are using and extract the path string up to the envs directory exclusiv. For example: The python interpreter of my conda env is located at:
/home/user/project_root/envs/default/bin/python
# You can first retrieve the env variable PROJECT_DIR.
# If not set, get the python interpreter location and strip off the string till envs inclusiv...
if os.getenv('PROJECT_DIR'):
PROJECT_DIR = os.getenv('PROJECT_DIR')
else:
PYTHON_PATH = sys.executable
path_rem = os.path.join('envs', 'default', 'bin', 'python')
PROJECT_DIR = py_path.split(path_rem)[0]
This works only with conda-project with fixed project structure of a anaconda-project
Since you mentioned you use a proxy, try setting up the firefox driver with a proxy by following the answer given here proxy selenium python firefox
DESC KEYSPACES will do the job.
Also, If you want to describe schema of a particular keyspace you can use
DESC
Same thing happend to me after upgrading distro.
Running sudo apt-get install php7.0-mysql
fixed it for me.
I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:
<script type="text/javascript" language="JavaScript">
$.ajax({
url: "x.html",
context: document.body,
success: function(response) {
$("#yourDiv").html(response);
}
});
</script>
On unix systems, you can use the following command to determine where git is installed:
whereis git
If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.
Use the cgwin command SPLIT. Samples
To split a file every 500 lines counts:
split -l 500 [filename.ext]
by default, it adds xa,xb,xc... to filename after extension
To generate files with numbers and ending in correct extension, use following
split -l 1000 sourcefilename.ext destinationfilename -d --additional-suffix=.ext
the position of -d or -l does not matter,
For more: split --help
To change the panel's background color, use the following code:
myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))
To change the color of the plot (but not the color of the panel), you can do:
myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))
See here for more theme details Quick reference sheet for legends, axes and themes.
IMHO, fs.readFile()
should be avoided because it loads ALL the file in memory and it won't call the callback until all the file has been read.
The easiest way to read a text file is to read it line by line. I recommend a BufferedReader:
new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log ("error: " + error);
})
.on ("line", function (line){
console.log ("line: " + line);
})
.on ("end", function (){
console.log ("EOF");
})
.read ();
For complex data structures like .properties or json files you need to use a parser (internally it should also use a buffered reader).
You could do this by creating a reverse (collapse) animation with clip-path.
#child0 {_x000D_
display: none;_x000D_
}_x000D_
#parent0:hover #child0 {_x000D_
display: block;_x000D_
animation: height-animation;_x000D_
animation-duration: 200ms;_x000D_
animation-timing-function: linear;_x000D_
animation-fill-mode: backwards;_x000D_
animation-iteration-count: 1;_x000D_
animation-delay: 200ms;_x000D_
}_x000D_
@keyframes height-animation {_x000D_
0% {_x000D_
clip-path: polygon(0% 0%, 100% 0.00%, 100% 0%, 0% 0%);_x000D_
}_x000D_
100% {_x000D_
clip-path: polygon(0% 0%, 100% 0.00%, 100% 100%, 0% 100%);_x000D_
}_x000D_
}
_x000D_
<div id="parent0">_x000D_
<h1>Hover me (height: 0)</h1>_x000D_
<div id="child0">Some content_x000D_
<br>Some content_x000D_
<br>Some content_x000D_
<br>Some content_x000D_
<br>Some content_x000D_
<br>Some content_x000D_
<br>_x000D_
</div>_x000D_
</div>
_x000D_
In addition to all the above, one should note that, for a defined value v
:
String(v)
calls v.toString()
'' + v
calls v.valueOf()
prior to any other type castSo we could do something like:
var mixin = {
valueOf: function () { return false },
toString: function () { return 'true' }
};
mixin === false; // false
mixin == false; // true
'' + mixin; // "false"
String(mixin) // "true"
Tested in FF 34.0 and Node 0.10
Great New Application
No Need to root your Phone and You Can Run your js File From anywere.
Update instruction to node js 8 (async await)
Download node.js v8.3.0 arm zip file and unzip.
copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)
open the shell(check it out in the app's menu)
cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )
rm node
cp /sdcard/node .
(chmod a+x node
(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)
Implement the HandlerInterceptor
interface, and then inject the UserDetails
into each request that has a Model, as follows:
@Component
public class UserInterceptor implements HandlerInterceptor {
....other methods not shown....
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(modelAndView != null){
modelAndView.addObject("user", (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
}
A solution that works for S3 modified from Minkymorgan.
Simply pass the temporary partitioned directory path (with different name than final path) as the srcPath
and single final csv/txt as destPath
Specify also deleteSource
if you want to remove the original directory.
/**
* Merges multiple partitions of spark text file output into single file.
* @param srcPath source directory of partitioned files
* @param dstPath output path of individual path
* @param deleteSource whether or not to delete source directory after merging
* @param spark sparkSession
*/
def mergeTextFiles(srcPath: String, dstPath: String, deleteSource: Boolean): Unit = {
import org.apache.hadoop.fs.FileUtil
import java.net.URI
val config = spark.sparkContext.hadoopConfiguration
val fs: FileSystem = FileSystem.get(new URI(srcPath), config)
FileUtil.copyMerge(
fs, new Path(srcPath), fs, new Path(dstPath), deleteSource, config, null
)
}
I Think this is the best way to do it.
REPLACE(CONVERT(NVARCHAR,CAST(WeekEnding AS DATETIME), 106), ' ', '-')
Because you do not have to use varchar(11)
or varchar(10)
that can make problem in future.
Based on this guide for Mercurial my .gitignore includes:
.DS_Store
*.swp
*~.nib
build/
*.pbxuser
*.perspective
*.perspectivev3
I've also chosen to include:
*.mode1v3
*.mode2v3
which, according to this Apple mailing list post, are "user-specific project settings".
And for Xcode 4:
xcuserdata
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
Something new in ASP.Net 3.5 is this "PostBackUrl" property of ASP buttons. You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you've indicated. Handy. Be sure UseSubmitBehavior is also set to TRUE.
Do it the hard way. Use the awesome MODEL
clause:
SELECT V
FROM DUAL
MODEL DIMENSION BY (0 R)
MEASURES (0 V)
RULES ITERATE (100) (
V[ITERATION_NUMBER] = ITERATION_NUMBER + 1
)
ORDER BY 1
There is no generic type which will tell the compiler that a method returns nothing.
I believe the convention is to use Object when inheriting as a type parameter
OR
Propagate the type parameter up and then let users of your class instantiate using Object and assigning the object to a variable typed using a type-wildcard ?
:
interface B<E>{ E method(); }
class A<T> implements B<T>{
public T method(){
// do something
return null;
}
}
A<?> a = new A<Object>();
Some answers already pointed out background-size: cover
is useful in the case, but none points out the browser support details. Here it is:
Add this CSS into your stylesheet:
body {
background: url(background.jpg) no-repeat center center fixed;
background-size: cover; /* for IE9+, Safari 4.1+, Chrome 3.0+, Firefox 3.6+ */
-webkit-background-size: cover; /* for Safari 3.0 - 4.0 , Chrome 1.0 - 3.0 */
-moz-background-size: cover; /* optional for Firefox 3.6 */
-o-background-size: cover; /* for Opera 9.5 */
margin: 0; /* to remove the default white margin of body */
padding: 0; /* to remove the default white margin of body */
}
-moz-background-size: cover;
is optional for Firefox, as Firefox starts supporting the value cover
since version 3.6. If you need to support Konqueror 3.5.4+ as well, add -khtml-background-size: cover;
.
As you're using CSS3, it's suggested to change your DOCTYPE to HTML5. Also, HTML5 CSS Reset stylesheet is suggested to be added BEFORE your our stylesheet to provide a consistent look & feel for modern browsers.
Reference: background-size at MDN
If you ever need to support old browsers like IE 8 or below, you can still go for Javascript way (scroll down to jQuery section)
Last, if you predict your users will use mobile phones to browse your website, do not use the same background image for mobile web, as your desktop image is probably large in file size, which will be a burden to mobile network usage. Use media query to branch CSS.
If you are running iOS 13 or above use this code in your SceneDelegate:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let notificationResponse = connectionOptions.notificationResponse else { return }
let pushTitle = notificationResponse.notification.request.content.title
let pushSubtitle = notificationResponse.notification.request.content.subtitle
let pushBody = notificationResponse.notification.request.content.body
// do your staff here
}
How do I properly compare strings?
char input[40];
char check[40];
strcpy(input, "Hello"); // input assigned somehow
strcpy(check, "Hello"); // check assigned somehow
// insufficient
while (check != input)
// good
while (strcmp(check, input) != 0)
// or
while (strcmp(check, input))
Let us dig deeper to see why check != input
is not sufficient.
In C, string is a standard library specification.
A string is a contiguous sequence of characters terminated by and including the first null character.
C11 §7.1.1 1
input
above is not a string. input
is array 40 of char.
The contents of input
can become a string.
In most cases, when an array is used in an expression, it is converted to the address of its 1st element.
The below converts check
and input
to their respective addresses of the first element, then those addresses are compared.
check != input // Compare addresses, not the contents of what addresses reference
To compare strings, we need to use those addresses and then look at the data they point to.
strcmp()
does the job. §7.23.4.2
int strcmp(const char *s1, const char *s2);
The
strcmp
function compares the string pointed to bys1
to the string pointed to bys2
.The
strcmp
function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to bys1
is greater than, equal to, or less than the string pointed to bys2
.
Not only can code find if the strings are of the same data, but which one is greater/less when they differ.
The below is true when the string differ.
strcmp(check, input) != 0
For insight, see Creating my own strcmp()
function
Try to close the process that is using your port.
netstat -tulnp | grep <port_number>
Installing the below pakcage fixed it for me forever.
npm install [email protected] --save-dev --save-exact
Run this command in your terminal :
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:
fs.inotify.max_user_watches=524288
Then execute:
sysctl --system
This will also persist across reboots.
https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers#the-technical-details
Use get_the_category()
function.
$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
I can't leave this question in this state with that final code in the question hanging over me...
dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:
There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.
The with
statement (recommended in another answer) removes the bother of closing the file through the context handler.
Use a dictionary instead of two lists.
A generator comprehension ((x for y in z)
) is used to do the translation in one line.
Wrap as little code as you can in a try
/except
block to reduce the probability of catching an exception you didn't mean to.
Use the input()
argument rather than print()
ing first - Use '\n'
to get the new line you want.
Don't write code across multiple lines or with intermediate variables like this just for the sake of it:
a = a.b()
a = a.c()
b = a.x()
c = b.y()
Instead, write these constructs like this, chaining the calls as is perfectly valid:
a = a.b().c()
c = a.x().y()
code = {}
with open('morseCode.txt', 'r') as morse_code_file:
# line format is <letter>:<morse code translation>
for line in morse_code_file:
line = line.rstrip() # Remove NL
code[line[0]] = line[2:]
user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
try:
print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
except KeyError:
print("Error in input. Only alphanumeric characters, a comma, and period allowed")
user_input = input("Try again or press <enter> to quit\n")
You have too many methods count. Android dex file has a limit of 65536 methods you are allowed to have.
For starters, if you don't need all of google play services API and just the location, replace
compile 'com.google.android.gms:play-services:11.8.0'
with
compile 'com.google.android.gms:play-services-location:11.8.0'
You can refer to this page for ways to avoid it or if needed to allow more: https://developer.android.com/studio/build/multidex.html
You can also do this if you want to play around with pandas. However, I like punchagan's way.
# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'],
'area': [10, 20, 30, 40],
'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)
# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)
output: {10: 7, 20: 5, 30: 2, 40: 3}
In C++11 you can use any_of
. For example if it is a vector<string> v;
then:
if (any_of(v.begin(), v.end(), bind(equal_to<string>(), _1, item)))
do_this();
else
do_that();
Alternatively, use a lambda:
if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
do_this();
else
do_that();
You can even use this one. worked well for me
$("#registerform").attr("action", "register.php?btnsubmit=Save")
$('#registerform').submit();
this will submit btnsubmit =Save as GET value to register.php form.
Just invoke ruby XXXXX.rb
in terminal, if the interpreter is in your $PATH variable.
( this can hardly be a rails thing, until you have it running. )
Here is what I'm using:
if (mySQLConnection.State != ConnectionState.Open)
{
mySQLConnection.Close();
mySQLConnection.Open();
}
The reason I'm not simply using:
if (mySQLConnection.State == ConnectionState.Closed)
{
mySQLConnection.Open();
}
Is because the ConnectionState can also be:
Broken, Connnecting, Executing, Fetching
In addition to
Open, Closed
Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v=vs.110).aspx
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
Arrays are non-negative integer indexed , so maximum array size you can access would be Integer.MAX_VALUE
. The other thing is how big array you can create. It depends on the maximum memory available to your JVM
and the content type of the array. Each array element has it's size, example. byte = 1 byte
, int = 4 bytes
, Object reference = 4 bytes (on a 32 bit system)
So if you have 1 MB
memory available on your machine, you could allocate an array of byte[1024 * 1024]
or Object[256 * 1024]
.
Answering your question - You can allocate an array of size (maximum available memory / size of array item).
Summary - Theoretically the maximum size of an array will be Integer.MAX_VALUE
. Practically it depends on how much memory your JVM
has and how much of that has already been allocated to other objects.
You can make use of variable NF
which is set to the total number of fields in the input record:
awk '{print $(NF-1),"\t",$NF}' file
this assumes that you have at least 2 fields.
I had use two different tools to debug procedures and functions:
Another potential cause is that docker will not follow symbolic links by default (i.e don't use ln -s
).
Firstly, application.properties in the @PropertySource should read application-test.properties
if that's what the file is named (matching these things up matters):
@PropertySource("classpath:application-test.properties ")
That file should be under your /src/test/resources
classpath (at the root).
I don't understand why you'd specify a dependency hard coded to a file called application-test.properties
. Is that component only to be used in the test environment?
The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.
In a typically laid out application, you'd have:
src/test/resources/application.properties
and
src/main/resources/application.properties
And then inject it like this:
@PropertySource("classpath:application.properties")
The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?
If you hit git stash
when you have changes in the working copy (not in the staging area), git will create a stashed object and pushes onto the stack of stashes (just like you did git checkout -- .
but you won't lose changes). Later, you can pop from the top of the stack.
n = Math.floor(x);
remainder = x % 1;
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
TSQL, Alternative using variable declaration. (it might improve Query's readability)
DECLARE @gapPeriod DATETIME = DATEADD(MONTH,-2,GETDATE()); --Period:Last 2 months.
SELECT
*
FROM
FB as A
WHERE
A.Dte <= @gapPeriod; --only older records.
I'd suggest trying file mapping. I used mmap
in the past, in a UNIX environment, and I was impressed by the high performance I could achieve
If you add jars in tomcat's lib folder you can see this error
I would recommend using a library like PapaParse: https://github.com/mholt/PapaParse
The accepted answer currently has multiple issues including:
I always do ...
myTimer.Stop();
myTimer.Start();
... is that a hack? :)
Per comment, on Threading.Timer, it's the Change method ...
dueTime Type:
System.Int32
The amount of time to delay before the invoking the callback method specified when the Timer was constructed, in milliseconds. SpecifyTimeout.Infinite
to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.
It will draw Silver gray colored Line between TextView
& ListView
<TextView
android:id="@+id/textView1"
style="@style/behindMenuItemLabel1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:text="FaceBook Feeds" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#c0c0c0"/>
<ListView
android:id="@+id/list1"
android:layout_width="350dp"
android:layout_height="50dp" />
If your compiler supports (at least part of) C++11 you could do something like:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.
Simple answer
If you want to match single character, put it inside those brackets [ ]
Examples
...and so on. You can check your regular expresion online on this site: https://regex101.com/
(updated based on comment)
As of the date of this answer (March 2020) there is a plugin for chrome called CORS unblock that allows you to skip that browser policy. The 'same origin policy' is an important security feature of browsers. Please only install this plugin for development or testing purposes. Do not promote its installation in end client browsers because you compromise the security of users and the chrome community will be forced to remove this plugin from the store.
public void DeleteColFromTable(String DbName, String TableName, String ColName){
SQLiteDatabase db = openOrCreateDatabase(""+DbName+"", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS "+TableName+"(1x00dff);");
Cursor c = db.rawQuery("PRAGMA table_info("+TableName+")", null);
if (c.getCount() == 0) {
} else {
String columns1 = "";
String columns2 = "";
while (c.moveToNext()) {
if (c.getString(1).equals(ColName)) {
} else {
columns1 = columns1 + ", " + c.getString(1) + " " + c.getString(2);
columns2 = columns2 + ", " + c.getString(1);
}
if (c.isLast()) {
db.execSQL("CREATE TABLE IF NOT EXISTS DataBackup (" + columns1 + ");");
db.execSQL("INSERT INTO DataBackup SELECT " + columns2 + " FROM "+TableName+";");
db.execSQL("DROP TABLE "+TableName+"");
db.execSQL("ALTER TABLE DataBackup RENAME TO "+TableName+";");
}
}
}
}
and just call a method
DeleteColFromTable("Database name","Table name","Col name which want to delete");
I do not like putting the nav in the header. My reasoning is:
Logic
The header contains introductory information about the document. The nav is a menu that links to other documents. To my mind this means that the content of the nav belongs to the site rather than the document. An exception would be if the NAV held forward links.
Accessibility
I like to put menus at the end of the source code rather than the start. I use CSS to send it to the top of a computer screen or leave it at the end for text-speech browsers and small screens. This avoids the need for skip-links.
Try this when you want to "fix" your body's scroll:
jQuery('body').css('height', '100vh').css('overflow-y', 'hidden');
and this when you want to turn it normal again:
jQuery('body').css('height', '').css('overflow-y', '');
I came up with this pretty basic code. I think it could be useful to anyone.
$link = "link to the CSV here"
$fp = fopen($link, 'r');
while(($line = fgetcsv($fp)) !== FALSE) {
foreach($line as $key => $value) {
echo $key . " - " . $value . "<br>";
}
}
fclose($fp);
for .NET CORE use System.AppContext.BaseDirectory
(as a replacement for AppDomain.CurrentDomain.BaseDirectory
)
I wouldn't even pay attention to the contents of the parens.
Just match any line that starts with for
and ends with semi-colon:
^\t*for.+;$
Unless you've got for
statements split over multiple lines, that will work fine?
If you need to preserve your seed so that it generates the "same" random data every time, you can do the following:
1. Create a view that returns select rand()
if object_id('cr_sample_randView') is not null
begin
drop view cr_sample_randView
end
go
create view cr_sample_randView
as
select rand() as random_number
go
2. Create a UDF that selects the value from the view.
if object_id('cr_sample_fnPerRowRand') is not null
begin
drop function cr_sample_fnPerRowRand
end
go
create function cr_sample_fnPerRowRand()
returns float
as
begin
declare @returnValue float
select @returnValue = random_number from cr_sample_randView
return @returnValue
end
go
3. Before selecting your data, seed the rand() function, and then use the UDF in your select statement.
select rand(200); -- see the rand() function
with cte(id) as
(select row_number() over(order by object_id) from sys.all_objects)
select
id,
dbo.cr_sample_fnPerRowRand()
from cte
where id <= 1000 -- limit the results to 1000 random numbers
This worked for me on Ubuntu 16.04:
python2 -m pip install ipykernel
python2 -m ipykernel install --user
python3 -m pip install ipykernel
python3 -m ipykernel install --user
Reference to the documentation:
Kernels for Python 2 and 3. Installing the IPython kernel - IPython Docs.
Simply use the global keyword.
e.g.:
class myClass() {
private function foo() {
global $MyNumber;
...
$MyNumber will then become accessible (and indeed modifyable) within that method.
However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)
If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.
Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):
SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1),
"STRING_COLUMN")
AS OUTPUT FROM DUAL
You can use this repo: GSBorderLabel
It's quite simple:
GSBorderLabel *myLabel = [[GSBorderLabel alloc] initWithTextColor:aColor
andBorderColor:anotherColor
andBorderWidth:2];
It is possible to print a 15 decimal number in C++ using the following:
#include <iomanip>
#include <iostream>
cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();
return 0;
Here is a shorter version that should also work:
$('#ddlCodes').change(function() {
$('#txtEntry2').text(this.val());
});
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
class A
{
void method()
{
}
}
class Demo
{
static void method2()
{
A a=new A();
a.method();
}
/*
void method3()
{
A a=new A();
a.method();
}
*/
public static void main(String args[])
{
A a=new A();
/*an instance of the class is created to access non-static method from a static method */
a.method();
method2();
/*method3();it will show error non-static method can not be accessed from a static method*/
}
}
So by default you can open CMD and write
java -jar jenkins.war
But if your port 8080 is already is in use,so you have to change the Jenkins port number, so for that open Jenkins folder in Program File and open Jenkins.XML file and change the port number such as 8088
Now Open CMD and write
java -jar jenkins.war --httpPort=8088
Just had the same problem after creating a new user profile on my development machine.
The problem was that I wasn't running the console (command prompt\powershell ISE) as admin.
Running as admin solved this problem for me.
Change android:stretchColumns
value to *
.
Value 0
means stretch the first column. Value 1
means stretch the second column and so on.
Value *
means stretch all the columns.
In command line, you can use
spark-shell -i file.scala
to run code which is written in file.scala
I solved this issue by removing empty string from my resolve array. Check out resolve documentation on webpack's site.
//Doesn't work
module.exports = {
resolve: {
extensions: ['', '.js', '.jsx']
}
...
};
//Works!
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
}
...
};
If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ()
.
case
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore
But it'll be better if you show your full query to get context of what you actually need.
You can go to jwt.io
, paste your token and read the contents. This is jarring for a lot of people initially.
The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.
The logical question is what is the motivation for not concerning itself with encrypted contents?
The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure
(is not transmitted via HTTP, only via HTTPS) and httpOnly
(can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.
This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).
JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.
It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.
I'm using webstorm on the deployed files
Another alternative
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );
While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :
Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).
You can add this formatter into your global config :
HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));
WebApi should now use BinaryMediaTypeFormatter
if the request specifies the correct Accept header.
I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").
If you want, you can export all collections to csv without specifying --fields
(will export all fields).
From http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/ run this bash script
OIFS=$IFS;
IFS=",";
# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT
# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);
# for each collection
for ((i=0; i<${#collectionArray[@]}; ++i));
do
echo 'exporting collection' ${collectionArray[$i]}
# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done
IFS=$OIFS;
Copypastable version of wearesicc's 5 col solution with bootstrap variables:
.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
position: relative;
min-height: 1px;
padding-right: ($gutter / 2);
padding-left: ($gutter / 2);
}
.col-xs-15 {
width: 20%;
float: left;
}
@media (min-width: $screen-sm) {
.col-sm-15 {
width: 20%;
float: left;
}
}
@media (min-width: $screen-md) {
.col-md-15 {
width: 20%;
float: left;
}
}
@media (min-width: $screen-lg) {
.col-lg-15 {
width: 20%;
float: left;
}
}
$("#citiesList").change(function() {
alert($("#citiesList option:selected").text());
alert($("#citiesList option:selected").val());
});
citiesList is id of select tag
This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.
One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.
ArrayList<Double> marks = new ArrayList<Double>();
@Maxim
try this...
pom.xml
<groupId>org.opensource</groupId>
<artifactId>base</artifactId>
<version>1.0.0.SNAPSHOT</version>
..............
<properties>
<my.version>4.0.8.8</my.version>
</properties>
<build>
<finalName>my-base-project</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<goals>
<goal>install-file</goal>
</goals>
<phase>install</phase>
<configuration>
<file>${project.build.finalName}.${project.packaging}</file>
<generatePom>false</generatePom>
<pomFile>pom.xml</pomFile>
<version>${my.version}</version>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Commnad mvn clean install
Output
[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ base ---
[INFO] Building jar: D:\dev\project\base\target\my-base-project.jar
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ base ---
[INFO] Installing D:\dev\project\base\target\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.pom
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default) @ base ---
[INFO] Installing D:\dev\project\base\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
Just make sur that the static option is set to false
@ViewChild('contentPlaceholder', {static: false}) contentPlaceholder: ElementRef;
You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.
See the MySQL 5.1 Reference Manual for the [RENAME TABLE
][1] and [CREATE TABLE
][2] commands.
RENAME TABLE tbl TO tbl_old;
CREATE TABLE tbl LIKE tbl_old;
DROP TABLE tbl_old; -- at your leisure
This approach can help minimize application downtime.
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
See execSync library.
It's fairly easy to do with node-ffi. I wouldn't recommend for server processes, but for general development utilities it gets things done. Install the library.
npm install node-ffi
Example script:
var FFI = require("node-ffi");
var libc = new FFI.Library(null, {
"system": ["int32", ["string"]]
});
var run = libc.system;
run("echo $USER");
[EDIT Jun 2012: How to get STDOUT]
var lib = ffi.Library(null, {
// FILE* popen(char* cmd, char* mode);
popen: ['pointer', ['string', 'string']],
// void pclose(FILE* fp);
pclose: ['void', [ 'pointer']],
// char* fgets(char* buff, int buff, in)
fgets: ['string', ['string', 'int','pointer']]
});
function execSync(cmd) {
var
buffer = new Buffer(1024),
result = "",
fp = lib.popen(cmd, 'r');
if (!fp) throw new Error('execSync error: '+cmd);
while(lib.fgets(buffer, 1024, fp)) {
result += buffer.readCString();
};
lib.pclose(fp);
return result;
}
console.log(execSync('echo $HOME'));
First composer requires doctrine/dbal
, then:
$table->longText('column_name')->change();
Although there isn't a syntax, you can still get close by using the built-in block comment buttons:
If you're not viewing the Edit toolbar already, right-click on the toolbar and enable the Edit toolbar:
Then, select a block of code and hit the "Comment Block" button; or if it's already commented out, use the "Uncomment Block" button:
Fast and easy!
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.
if(strstr(sent, word) != NULL) {
/* ... */
}
Note that strstr
returns a pointer to the start of the word in sent
if the word word
is found.
To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database