I modified the code as follow:
ViewModel
using System.Collections.Generic;
using ContosoUniversity.Models;
namespace ContosoUniversity.ViewModels
{
public class InstructorIndexData
{
public PagedList.IPagedList<Instructor> Instructors { get; set; }
public PagedList.IPagedList<Course> Courses { get; set; }
public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
}
}
Controller
public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
int instructPageNumber = (InstructorPage?? 1);
int CoursePageNumber = (CoursePage?? 1);
int EnrollmentPageNumber = (EnrollmentPage?? 1);
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
viewModel.Enrollments = viewModel.Courses.Where(
x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
}
return View(viewModel);
}
View
<div>
Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount
@Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))
</div>
I hope this would help you!!
There are two issues here, lifetime and scope.
The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().
The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
try this once.
$wp_query->set_404();
status_header(404);
get_template_part('404');
2007 might be a bit complicated as well.
The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.
Rename a .docx file to .zip and you'll see what I mean.
So if you can work within zip files in PHP, you should be on the right path.
Look at a linked list :
[A]=> [B]=> [C]=> [D]=>
It's a ... Train ! Each railroad car contain something and is attached to another railroad car (or nothing for the last one). You can only add a railroad car at the end and if you want to get rid of one you must attach the previous one with the next one.
You can use length()
from EditText
.
public boolean isEditTextEmpty(EditText mInput){
return mInput.length() == 0;
}
Your code concatenates three strings, then converts the result to a number.
You need to convert each variable to a number by calling parseFloat()
around each one.
total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
Since x!=x
returns the same boolean array with np.isnan(x)
(because np.nan!=np.nan
would return True
), you could also write:
np.argwhere(x!=x)
However, I still recommend writing np.argwhere(np.isnan(x))
since it is more readable. I just try to provide another way to write the code in this answer.
Create a java module to be initially run when starting your app. This module would be extending the android Application class and would initialize any global app variables and also contain app-wide utility routines -
public class MyApplicationName extends Application {
private final String PACKAGE_NAME = "com.mysite.myAppPackageName";
public String getPackageName() { return PACKAGE_NAME; }
}
Of course, this could include logic to obtain the package name from the android system; however, the above is smaller, faster and cleaner code than obtaining it from android.
Be sure to place an entry in your AndroidManifest.xml file to tell android to run your application module before running any activities -
<application
android:name=".MyApplicationName"
...
>
Then, to obtain the package name from any other module, enter
MyApp myApp = (MyApp) getApplicationContext();
String myPackage = myApp.getPackageName();
Using an application module also gives you a context for modules that need but don't have a context.
I had to use a slightly extended version @Erwin Brandstetter used:
DO
$do$
DECLARE
_db TEXT := 'some_db';
_user TEXT := 'postgres_user';
_password TEXT := 'password';
BEGIN
CREATE EXTENSION IF NOT EXISTS dblink; -- enable extension
IF EXISTS (SELECT 1 FROM pg_database WHERE datname = _db) THEN
RAISE NOTICE 'Database already exists';
ELSE
PERFORM dblink_connect('host=localhost user=' || _user || ' password=' || _password || ' dbname=' || current_database());
PERFORM dblink_exec('CREATE DATABASE ' || _db);
END IF;
END
$do$
I had to enable the dblink
extension, plus i had to provide the credentials for dblink.
Works with Postgres 9.4.
you can use <br>
tag in your string for show in html pages
I use following code, found somewhere in the internet don't remember the source though.
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return JSON.parse(allText);
So I try htmlspecialchars() or htmlentities() which outputs <p>Résumé<p> and the browser renders <p>Résumé<p>.
If you've got it working where it displays Résumé
with <p></p>
tags around it, then just don't convert the paragraph, only your string. Then the paragraph will be rendered as HTML and your string will be displayed within.
The direct parent of your child is markerDiv, so you should call remove from markerDiv as so:
markerDiv.removeChild(myCoolDiv);
Alternatively, you may want to remove markerNode. Since that node was appended directly to videoContainer, it can be removed with:
document.getElementById("playerContainer").removeChild(markerDiv);
Now, the easiest general way to remove a node, if you are absolutely confident that you did insert it into the DOM, is this:
markerDiv.parentNode.removeChild(markerDiv);
This works for any node (just replace markerDiv with a different node), and finds the parent of the node directly in order to call remove from it. If you are unsure if you added it, double check if the parentNode is non-null before calling removeChild.
You can check out my bash-based C call tree generator here. It lets you specify one or more C functions for which you want caller and/or called information, or you can specify a set of functions and determine the reachability graph of function calls that connects them... I.e. tell me all the ways main(), foo(), and bar() are connected. It uses graphviz/dot for a graphing engine.
This issue is not always related to the PowerShell Execution Policy. My machine is configured as "Unrestricted" for both PowerShell x64 and x86, but I still get this error message from times to times in Visual Studio 2013.
When I try to open the Package Manager Console:
Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of Unrestricted. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help Set-ExecutionPolicy".
This is not a valid error message.
Rebooting Visual Studio does not always resolve the problem.
Running the process as an admin never resolves the problem.
Like Declan, the latest update of the Package Manager plugin fixed the issue: 2.8.60723.765
In my case, I was able to resolve the issue by doing the following:
I changed my code from this:
var r2 = db.Instances.Where(x => x.Player1 == inputViewModel.InstanceList.FirstOrDefault().Player2 && x.Player2 == inputViewModel.InstanceList.FirstOrDefault().Player1).ToList();
To this:
var p1 = inputViewModel.InstanceList.FirstOrDefault().Player1;
var p2 = inputViewModel.InstanceList.FirstOrDefault().Player2;
var r1 = db.Instances.Where(x => x.Player1 == p1 && x.Player2 == p2).ToList();
The solution for me was related to the fact that the project that was implementing the interface had the property "Register for COM Interop" set. Unchecking this option resolved the issue for me.
It works fine for me, but it's a little tricky :)
Now you have settings for this session set (every time you load session it will be logged).
The accepted answer work when you have a single line string(the email) but if you have a
multiline string, the error will remain.
Please look into this matter:
<!-- start: definition-->
@{
dynamic item = new System.Dynamic.ExpandoObject();
item.MultiLineString = @"a multi-line
string";
item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
function Getinfo(text) {
alert(text);
}
</script>
Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:
<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>
If you define your array like this:
string[][] table = new string[][] {
new string[] { "aa", "aaa" },
new string[]{ "bb", "bbb" }
};
Then you can use a foreach loop on it.
The backslash in C is used to escape characters in strings. Strings would not recognize %
as a special character, and therefore no escape would be necessary. printf
is another matter: use %%
to print one %
.
If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:
diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
print k, ':', dict1[k], '->', dict2[k]
pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.
You can do like this
var filter = {_x000D_
address: 'England',_x000D_
name: 'Mark'_x000D_
};_x000D_
var users = [{_x000D_
name: 'John',_x000D_
email: '[email protected]',_x000D_
age: 25,_x000D_
address: 'USA'_x000D_
},_x000D_
{_x000D_
name: 'Tom',_x000D_
email: '[email protected]',_x000D_
age: 35,_x000D_
address: 'England'_x000D_
},_x000D_
{_x000D_
name: 'Mark',_x000D_
email: '[email protected]',_x000D_
age: 28,_x000D_
address: 'England'_x000D_
}_x000D_
];_x000D_
_x000D_
_x000D_
users= users.filter(function(item) {_x000D_
for (var key in filter) {_x000D_
if (item[key] === undefined || item[key] != filter[key])_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
});_x000D_
_x000D_
console.log(users)
_x000D_
You can customize your tost:
LayoutInflater mInflater=LayoutInflater.from(this);
View view=mInflater.inflate(R.layout.your_layout_file,null);
Toast toast=new Toast(this);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
Or General way:
Toast.makeText(context,"Your message.", Toast.LENGTH_LONG).show();
if you are expecting them in a certain order, you can just use diff
diff file1 file2 | grep ">"
If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.
Steps to create:
Good thing about this solution:
Not so good thing about this solution:
Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq
<button class="btn btn--animation-from-right">
<span class="btn__text-static">Cover left</span>
<div class="btn__text-dynamic">
<span class="btn__text-dynamic-inner">Cover left</span>
</div>
</button>
.btn {
padding: 10px 20px;
position: relative;
border: 2px solid #222;
color: #fff;
background-color: #222;
position: relative;
overflow: hidden;
cursor: pointer;
text-transform: uppercase;
font-family: monospace;
letter-spacing: -1px;
[class^="btn__text"] {
font-size: 24px;
}
.btn__text-dynamic,
.btn__text-dynamic-inner {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
z-index: 2;
transition: all ease 0.5s;
}
.btn__text-dynamic {
background-color: #fff;
color: #222;
overflow: hidden;
}
&:hover {
.btn__text-dynamic {
transform: translateX(-100%);
}
.btn__text-dynamic-inner {
transform: translateX(100%);
}
}
}
.btn--animation-from-right {
&:hover {
.btn__text-dynamic {
transform: translateX(100%);
}
.btn__text-dynamic-inner {
transform: translateX(-100%);
}
}
}
You can remove .btn--animation-from-right modifier if you want to animate to the left.
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
First of all do not use list
as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list
with the output of the np.getfromtext()
method in the first 2 indexes.
The first can be referenced with my_list[0]
and the second with my_list[1]
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
You need to ensure that C:\Python35\Sripts
is in your system path. Follow the top answer instructions here to do that:
You run the command in windows command prompt, not in the python interpreter that you have open.
Press:
Win + R
Type CMD
in the run window which has opened
Type pip install openpyxl
in windows command prompt.
I am using Ansible 1.9.4 and this is what worked for me -
- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"
There is no selector in CSS which does this. Attribute selectors match attribute values, not computed values.
You would have to use JavaScript.
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Copy all the (''.ipynb) files in the Desired folder then execute:
import os
desired_path = 'C:\\Users\\Docs\\Ipynb Covertor'
os.chdir(desired_path)
list_of_directory = os.listdir(desired_path)
for file in list_of_directory:
os.system('ipython nbconvert --to script ' + str(file))
json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
c# code: to take only a single value, for example the word "bike".
//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
string Text = stuff1[0].hws[2];
Console.WriteLine(Text);
output:
bike
You can just put !
and it will work:
print(var1) // optional("something")
print(var1!) // "something"
you can even do this by numpy
import numpy as np
np.array(your_list,dtype=float)
this return np array of your list as float
you also can set 'dtype' as int
UPDATE `table` SET table_column='test';
set encoding=utf-8 " The encoding displayed.
set fileencoding=utf-8 " The encoding written to file.
You may as well set both in your ~/.vimrc
if you always want to work with utf-8.
You might be interested in itertools.product
, which returns an iterable yielding tuples of values from all the iterables you pass it. That is, itertools.product(A, B)
yields all values of the form (a, b)
, where the a
values come from A
and the b
values come from B
. For example:
import itertools
A = [50, 60, 70]
B = [0.1, 0.2, 0.3, 0.4]
print [a + b for a, b in itertools.product(A, B)]
This prints:
[50.1, 50.2, 50.3, 50.4, 60.1, 60.2, 60.3, 60.4, 70.1, 70.2, 70.3, 70.4]
Notice how the final argument passed to itertools.product
is the "inner" one. Generally, itertools.product(a0, a1, ... an)
is equal to [(i0, i1, ... in) for in in an for in-1 in an-1 ... for i0 in a0]
When m2eclipse is installed properly, it should add dependencies automatically. However, you should generate the eclipse project files by entering:
mvn eclipse:m2eclipse
or, alternatively if you don't use m2eclipse:
mvn eclipse:eclipse
Form1 OpenNewForm = new Form1();
OpenNewForm.Show();
"OpenNewForm" is the name of the Form. In the second the form opens.
If you want to close the previous form:
this.Close();
Using the usual grouper recipe, you could do:
Python 2:
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))
Python 3:
d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))
You can use df.index
to access the index object and then get the values in a list using df.index.tolist()
. Similarly, you can use df['col'].tolist()
for Series.
These are questions which, in my opionion, requires different knowledge from different domains.
That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
}
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
}
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
This answer is the culmination of various other StackOverflow posts and tutorials around the internet brought into one place for my future reference, and to help anyone else who may be facing the same issue. All credit is given for other answers at the end.
In the Finder, duplicate the project folder to the desired location of your new project. Do not rename the .xcodeproj file name or any associated folders at this stage.
In Xcode, rename the project. Select your project from the navigator pane (left pane). In the Utilities pane (right pane) rename your project, Accept the changes Xcode proposes.
In Xcode, rename the schemes in "Manage Schemes", also rename any targets you may have.
If you're not using the default Bundle Identifier which contains the current PRODUCT_NAME at the end (so will update automatically), then change your Bundle Identifier to the new one you will be using for your duplicated project.
So after following the above steps you should have a duplicated and renamed Xcode project that should build and compile successfully, however your source code folder will still be named as it was in the original project. This doesn't cause any compiler issues, but it's not the clearest file structure for people to navigate in SCM, etc. To rename this folder without breaking all your file links, follow these steps:
In the Finder, rename the source folder. This will break your project, because Xcode won't automatically detect the changes. All of your xcode file listings will lose their links with the actual files, so will all turn red.
In Xcode, click on the virtual folder which you renamed (This will likely be right at the top, just under your actual .xcodeproject) Rename this to match the name in the Finder, this won't fix anything and strictly isn't a required step but it's nice to have the file names matching.
In Xcode, Select the folder you just renamed in the navigation pane. Then in the Utilities pane (far right) click the icon that looks like dark grey folder, just underneath the 'Location' drop down menu. From here, navigate to your renamed folder in the finder and click 'Choose'. This will automagically re-associate all your files, and they should no longer appear red within the Xcode navigation pane.
In your project / targets build settings, search for the old folder name and manually rename any occurrences you find. Normally there is one for the prefix.pch and one for the info.plist, but there may be more.
If you are using any third party libraries (Testflight/Hockeyapp/etc) you will also need to search for 'Library Search Paths' and rename any occurrences of the old file name here too.
Repeat this process for any unit test source code folders your project may contain, the process is identical.
This should allow you to duplicate & rename an xcode project and all associated files without having to manually edit any xcode files, and risk messing things up.
Many thanks is given to Nick Lockwood, and Pauly Glott for providing the separate answers to this problem.
Various forms depending on type of List, for Array List:
val myList = mutableListOf<Kolory>()
// or more specifically use the helper for a specific list type
val myList = arrayListOf<Kolory>()
For LinkedList:
val myList = linkedListOf<Kolory>()
// same as
val myList: MutableList<Kolory> = linkedListOf()
For other list types, will be assumed Mutable if you construct them directly:
val myList = ArrayList<Kolory>()
// or
val myList = LinkedList<Kolory>()
This holds true for anything implementing the List
interface (i.e. other collections libraries).
No need to repeat the type on the left side if the list is already Mutable. Or only if you want to treat them as read-only, for example:
val myList: List<Kolory> = ArrayList()
A very simple answer if you are looking to revert the change that you pushed just now :
commit 446sjb1uznnmaownlaybiosqwbs278q87
Merge: 123jshc 90asaf
git revert -m 2 446sjb1uznnmaownlaybiosqwbs278q87 //does the work
You can just use render and wrap your own div or span around it. TD`s are hard to style when it comes to max-width, max-height, etc. Div and span is easy..
See: https://datatables.net/examples/advanced_init/column_render.html
I think a nicer solution then working with CSS hacks which are not supported cross browser.
You git reset --hard
your local branch to remove changes from working tree and index, and you git push --force
your revised local branch to the remote. (other solution here, involving deleting the remote branch, and re-pushing it)
This SO answer illustrates the danger of such a command, especially if people depends on the remote history for their own local repos.
You need to be prepared to point out people to the RECOVERING FROM UPSTREAM REBASE section of the git rebase
man page
With Git 2.23 (August 2019, nine years later), you would use the new command git switch
.
That is: git switch -C mybranch origin/mybranch~n
(replace n
by the number of commits to remove)
That will restore the index and working tree, like a git reset --hard
would.
The documentation adds:
-C <new-branch> --force-create <new-branch>
Similar to
--create
except that if<new-branch>
already exists, it will be reset to<start-point>
.
This is a convenient shortcut for:$ git branch -f <new-branch> $ git switch <new-branch>
Given the general support of .innerHTML
these days, the only effective difference now is that .html()
will execute code in any <script>
tags if there are any in the html you give it. .innerHTML
, under HTML5, will not.
From the jQuery docs:
By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example,
<img onload="">
). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Note: both .innerHTML
and .html()
can execute js other ways (e.g the onerror
attribute).
To literally fix your example you would use this:
Sub Normalize()
Dim Ticker As Range
Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy
Sheets("Sheet2").Select
Cells(1, 1).PasteSpecial xlPasteAll
End Sub
To Make slight improvments on it would be to get rid of the Select and Activates:
Sub Normalize()
With Sheets("Sheet1")
.Range(.Cells(2, 1), .Cells(65, 1)).Copy Sheets("Sheet2").Cells(1, 1)
End With
End Sub
but using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.
Sub Normalize()
Dim CopyFrom As Range
Set CopyFrom = Sheets("Sheet1").Range("A2", [A65])
Sheets("Sheet2").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
End Sub
To define the CopyFrom
you can use anything you want to define the range, You could use Range("A2:A65")
, Range("A2",[A65])
, Range("A2", "A65")
all would be valid entries. also if the A2:A65 Will never change the code could be further simplified to:
Sub Normalize()
Sheets("Sheet2").Range("A1:A65").Value = Sheets("Sheet1").Range("A2:A66").Value
End Sub
I added the Copy from range, and the Resize
property to make it slightly more dynamic in case you had other ranges you wanted to use in the future.
I happen to be working on this now...
List<Integer> a = Arrays.asList(1, 2, 3);
List<Integer> b = Arrays.asList(3, 4);
List<int[]> pairs = a.stream()
.flatMap(x -> b.stream().map(y -> new int[]{x, y}))
.collect(Collectors.toList());
Consumer<int[]> pretty = xs -> System.out.printf("\n(%d,%d)", xs[0], xs[1]);
pairs.forEach(pretty);
One of the nicest things about git is that you don't need to track file renames explicitly. Git will figure it out by comparing the contents of the files.
So, in your case, don't work so hard:
$ mkdir include
$ mv common include
$ git rm -r common
$ git add include/common
Running git status
should show you something like this:
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: common/file.txt -> include/common/file.txt
#
I just leave my solution here.
import csv
import numpy as np
with open(name, newline='') as f:
reader = csv.reader(f, delimiter=",")
# skip header
next(reader)
# convert csv to list and then to np.array
data = np.array(list(reader))[:, 1:] # skip the first column
print(data.shape) # => (N, 2)
# sum each row
s = data.sum(axis=1)
print(s.shape) # => (N,)
We have now (jan2017) a csv layer import inside Google Maps itself.
Google Maps > "Your Places" > "Open in My Maps"
This should work:
<span class="vote-up@(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>
Here is a simple filter pipe for array of objects that contain attributes with string values (ES6)
filter-array-pipe.js
import {Pipe} from 'angular2/core';
// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
Your component
myobjComponent.js
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';
@Component({
templateUrl: 'myobj.list.html',
providers: [HTTP_PROVIDERS],
pipes: [FilterArrayPipe]
})
export class MyObjList {
static get parameters() {
return [[Http]];
}
constructor(_http) {
_http.get('/api/myobj')
.map(res => res.json())
.subscribe(
data => this.myobjs = data,
err => this.logError(err))
);
}
resetQuery(){
this.query = '';
}
}
In your template
myobj.list.html
<input type="text" [(ngModel)]="query" placeholder="... filter" >
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>
a string is essentially a sequence of characters and so the slicing operation works on it. What you are doing is in fact:
-> get an slice of 'a' from start to end in steps of 1 backward.
For php 7.1
sudo apt-get install php7.1-mbstring
Cheers!
The accepted answers really limit what you can do with your code. For example, you would not be able to search an array of Object Ids
by using the equals method. Instead, it would make more sense to always cast to string and compare the keys.
Here's an example answer in case if you need to use indexOf()
to check within an array of references for a specific id. assume query
is a query you are executing, assume someModel
is a mongo model for the id you are looking for, and finally assume results.idList
is the field you are looking for your object id in.
query.exec(function(err,results){
var array = results.idList.map(function(v){ return v.toString(); });
var exists = array.indexOf(someModel._id.toString()) >= 0;
console.log(exists);
});
You can extend the string type to include the inset method:
String.prototype.append = function (index,value) {_x000D_
return this.slice(0,index) + value + this.slice(index);_x000D_
};_x000D_
_x000D_
var s = "New string";_x000D_
alert(s.append(4,"complete "));
_x000D_
Then you can call the function:
You can also use the following syntax for the strongly typed version:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(),
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>
Set the same date and time in your android phone and in your laptop.
I had a similar problem of logs not showing, and when I set the correct date in the phone I started seeing the logs (I restarted the phone and the hour was completely wrong!).
Following answer can help in this and other similar situations like synchronous AJAX call -
Working example
waitForMe().then(function(intentsArr){
console.log('Finally, I can execute!!!');
},
function(err){
console.log('This is error message.');
})
function waitForMe(){
// Returns promise
console.log('Inside waitForMe');
return new Promise(function(resolve, reject){
if(true){ // Try changing to 'false'
setTimeout(function(){
console.log('waitForMe\'s function succeeded');
resolve();
}, 2500);
}
else{
setTimeout(function(){
console.log('waitForMe\'s else block failed');
resolve();
}, 2500);
}
});
}
To piggyback on @niutech's answer, you can make a very simple bookmark snippet.
Using Chrome, though it works similarly with other browsers
javascript:top.location="http://htmlpreview.github.com/?"+document.URL
I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:
Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:
- NET STOP iisadmin /y
- NET START w3svc
There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.
In ExtJs, you can use
xtype: 'image'
to render a image.
Here is a fiddle showing rendering of binary data with extjs.
atob -- > converts ascii to binary
btoa -- > converts binary to ascii
Ext.application({
name: 'Fiddle',
launch: function () {
var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));
Ext.create("Ext.panel.Panel", {
title: "Test",
renderTo: Ext.getBody(),
height: 400,
items: [{
xtype: 'image',
width: 100,
height: 100,
src: srcBase64
}]
})
}
});
There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data
argument as yadda
, but miss one of the places it is used in the function's body... Now data
refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError
if you didn't have a global name data
.
Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo
at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo
.
Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.
None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.
I also faced the same issue, but my fault was that I was running "rails s" outside of my application directory. After opening the cmd, just go inside your application and run the commands from their, it worked for me.
Map files (source maps) are there to de-reference minified code (css and javascript).
And they are mainly used to help developers debugging a production environment, because developers usually use minified files for production which makes it impossible to debug. Map files help them de-referencing the code to see how the original file looked like.
Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.
For example, here's a simple table Grades
:
| Letters |
|---------|
| A |
| A |
| B |
| C |
We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):
SELECT
COUNT(CASE WHEN Letter = 'A' THEN 1 END) AS [Count - End],
COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END) AS [Count - Else Zero],
SUM(CASE WHEN Letter = 'A' THEN 1 END) AS [Sum - End],
SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Sum - Else Null],
SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END) AS [Sum - Else Zero]
FROM Grades
And here are the results (unpivoted for readability):
| Description | Counts |
|-------------------|--------|
| Count - End | 2 |
| Count - Else Null | 2 |
| Count - Else Zero | 4 | *Note: Will include count of zero values
| Sum - End | 2 |
| Sum - Else Null | 2 |
| Sum - Else Zero | 2 |
Which lines up with the docs for Aggregate Functions in SQL
Docs for COUNT
:
COUNT(*)
- returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression)
- evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression)
- evaluates expression for each row in a group, and returns the number of unique, nonnull values.
Docs for SUM
:
ALL
- Applies the aggregate function to all values. ALL is the default.
DISTINCT
- Specifies that SUM return the sum of unique values.
I'll explain it in a simple way.
Generics defined at Class level are completely separate from the generics defined at the (static) method level.
class Greet<T> {
public static <T> void sayHello(T obj) {
System.out.println("Hello " + obj);
}
}
When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.
class Greet<T> {
public static <E> void sayHello(E obj) {
System.out.println("Hello " + obj);
}
}
Why the static method needs to have its own generics separate from those of the Class?
This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.
So, whenever you are calling the static method,
Greet.sayHello("Bob");
Greet.sayHello(123);
JVM interprets it as the following.
Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);
Both giving the same outputs.
Hello Bob
Hello 123
Referencing the Rails documents we see that there are a few ways to link to images from css. Just go to section 2.3.2.
First, make sure your css file has the .scss extension if it's a sass file.
Next, you can use the ruby method, which is really ugly:
#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
Or you can use the specific form that is nicer:
image-url("rails.png") returns url(/assets/rails.png)
image-path("rails.png") returns "/assets/rails.png"
Lastly, you can use the general form:
asset-url("rails.png") returns url(/assets/rails.png)
asset-path("rails.png") returns "/assets/rails.png"
You can keep your initial linear layout by nesting the relative layout within the linear layout:
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="welcome"
android:id="@+id/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:text="submit"
android:id="@+id/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true">
</Button>
<EditText android:id="@+id/EditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/Button"
android:layout_alignParentBottom="true">
</EditText>
</RelativeLayout>
</LinearLayout>
#include <stdlib.h>
int main()
{
int x;
x = rand(6);
printf("%d", x);
}
Especially as a beginner, you should ask your compiler to print every warning about bad code that it can generate. Modern compilers know lots of different warnings which help you to program better. For example, when you compile this program with the GNU C Compiler:
$ gcc -W -Wall rand.c
rand.c: In function `main':
rand.c:5: error: too many arguments to function `rand'
rand.c:6: warning: implicit declaration of function `printf'
You get two warnings here. The first one says that the rand
function only takes zero arguments, not one as you tried. To get a random number between 0 and n
, you can use the expression rand() % n
, which is not perfect but ok for small n
. The resulting random numbers are normally not evenly distributed; smaller values are returned more often.
The second warning tells you that you are calling a function that the compiler doesn't know at that point. You have to tell the compiler by saying #include <stdio.h>
. Which include files are needed for which functions is not always simple, but asking the Open Group specification for portable operating systems works in many cases: http://www.google.com/search?q=opengroup+rand.
These two warnings tell you much about the history of the C programming language. 40 years back, the definition of a function didn't include the number of parameters or the types of the parameters. It was also ok to call an unknown function, which in most cases worked. If you want to write code today, you should not rely on these old features but instead enable your compiler's warnings, understand the warnings and then fix them properly.
Essentially, PHPStorm = WebStorm + PHP, SQL and more.
BUT (and this is a very important "but") because it is capable of parsing so much more, it quite often fails to parse Node.js dependencies, as they (probably) conflict with some other syntax it is capable of parsing.
The most notable example of that would be Mongoose model definition, where WebStorm easily recognizes mongoose.model method, whereas PHPStorm marks it as unresolved as soon as you connect Node.js plugin.
Surprisingly, it manages to resolve the method if you turn the plugin off, but leave the core modules connected, but then it cannot be used for debugging. And this happens to quite a few methods out there.
All this goes for PHPStorm 8.0.1, maybe in later releases this annoying bug would be fixed.
There are several ways to do this:
One way is to use slicing:
>>> a="line=Name Age Group Class Profession"
>>> b=a.split()
>>> b[2:2]=[b[2]]*3
>>> b
['line=Name', 'Age', 'Group', 'Group', 'Group', 'Group', 'Class', 'Profession']
>>> a=" ".join(b)
>>> a
'line=Name Age Group Group Group Group Class Profession'
Another would be to use regular expressions:
>>> import re
>>> a=re.sub(r"(\S+\s+\S+\s+)(\S+\s+)(.*)", r"\1\2\2\2\2\3", a)
>>> a
'line=Name Age Group Group Group Group Class Profession'
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
After much digging around we were able to scrape the info more or less (mainly from Keycloak's own JS client lib):
/auth/realms/{realm}/tokens/login
/auth/realms/{realm}/tokens/access/codes
As for OpenID Connect UserInfo, right now (1.1.0.Final) Keycloak doesn't implement this endpoint, so it is not fully OpenID Connect compliant. However, there is already a patch that adds that as of this writing should be included in 1.2.x.
But - Ironically Keycloak does send back an id_token
in together with the access token. Both the id_token
and the access_token
are signed JWTs, and the keys of the token are OpenID Connect's keys, i.e:
"iss": "{realm}"
"sub": "5bf30443-0cf7-4d31-b204-efd11a432659"
"name": "Amir Abiri"
"email: "..."
So while Keycloak 1.1.x is not fully OpenID Connect compliant, it does "speak" in OpenID Connect language.
There is now an extension for Visual Studio 2012 and 2013:
http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459
First read Official documentation for Swift language.
Answer should be
var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)"
println(str)
Here
1) Any floating point value by default double
EX.
var myVal = 5.2 // its double by default;
-> If you want to display floating point value then you need to explicitly define such like a
EX.
var myVal:Float = 5.2 // now its float value;
This is far more clear.
Swift 3.0 version
let arr = yourString.components(separatedBy: "/")
let month = arr[0]
for (int i=0; i<6; i++)
{
for (int k=0; k<6-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<i*2+1; j++)
{
System.out.print("*");
}
System.out.println("");
}
What classes are missing? The class name itself should be a good clue to the missing module.
FYI, I know its really convenient to include the uber spring jar but this really causes issues when integrating with other projects. One of the benefits behind the dependency system is that it will resolve version conflicts among the dependencies.
If my library depends on spring-core:2.5 and you depend on my library and uber-spring:3.0, you now have 2 versions of spring on your classpath.
You can get around this with exclusions but its much easier to list the dependencies correctly and not have to worry about it.
As other posters already indicated; your system clock is probably not synchronized up to microseconds to actual world time. Nonetheless are microsecond precision timestamps useful as a hybrid for both indicating current wall time, and measuring/profiling the duration of things.
I label all events/messages written to a log files using timestamps like "2012-10-21 19:13:45.267128". These convey both when it happened ("wall" time), and can also be used to measure the duration between this and the next event in the log file (relative difference in microseconds).
To achieve this, you need to link System.currentTimeMillis() with System.nanoTime() and work exclusively with System.nanoTime() from that moment forward. Example code:
/**
* Class to generate timestamps with microsecond precision
* For example: MicroTimestamp.INSTANCE.get() = "2012-10-21 19:13:45.267128"
*/
public enum MicroTimestamp
{ INSTANCE ;
private long startDate ;
private long startNanoseconds ;
private SimpleDateFormat dateFormat ;
private MicroTimestamp()
{ this.startDate = System.currentTimeMillis() ;
this.startNanoseconds = System.nanoTime() ;
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
}
public String get()
{ long microSeconds = (System.nanoTime() - this.startNanoseconds) / 1000 ;
long date = this.startDate + (microSeconds/1000) ;
return this.dateFormat.format(date) + String.format("%03d", microSeconds % 1000) ;
}
}
For those who didn't know already, you would have to put the declare
statement outside your class
just like this:
declare var Chart: any;
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent {
//you can use Chart now and compiler wont complain
private color = Chart.color;
}
In TypeScript
the declare keyword is used where you want to define a variable that may not have originated from a TypeScript
file.
It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.
I guess you are asking why is 1388516401 equal to 2014-01-01...?
There is an historical reason for that. There is a 32-bit integer variable, called time_t
, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t
will be equal to 1388516401.
This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t
will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:
EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")
After that you can do this:
EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )
R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.
The C# compiler infers the true type of the var
variable at compile time. There's no difference in the generated IL.
Yeah. Just put the $ sign in front of your desired constant cell.
Like $A6 if you wish to just change the number 6 serially and keep a constant, or $A$6 if you do not want anything from that reference to change at all.
Example: Cell A5 contains my exchange rate. In B1 you put say ( = C1 * $A$1). when you fill B1 through B....... the value in A5 remains constant and the value in C1 increases serially.
I am by far not be good at teacher, but I hope this helps!!!! Wink wink
There is a neat way of doing this.
If it's an Unit Test you can do this:
@RunWith(MockitoJUnitRunner.class)
public class MyUnitTest {
@Mock
private MyFirstMock myFirstMock;
@Mock
private MySecondMock mySecondMock;
@Spy
private MySpiedClass mySpiedClass = new MySpiedClass();
// It's gonna inject the 2 mocks and the spied object per reflection to this object
// The java doc of @InjectMocks explains it really well how and when it does the injection
@InjectMocks
private MyClassToTest myClassToTest;
@Test
public void testSomething() {
}
}
EDIT: If it's an Integration test you can do this(not intended to be used that way with Spring. Just showcase that you can initialize mocks with diferent Runners):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("aplicationContext.xml")
public class MyIntegrationTest {
@Mock
private MyFirstMock myFirstMock;
@Mock
private MySecondMock mySecondMock;
@Spy
private MySpiedClass mySpiedClass = new MySpiedClass();
// It's gonna inject the 2 mocks and the spied object per reflection to this object
// The java doc of @InjectMocks explains it really well how and when it does the injection
@InjectMocks
private MyClassToTest myClassToTest;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSomething() {
}
}
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass@localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
You can use below code
$.when( Typer() ).done(function() {
playBGM();
});
You can just use the error function that's built in to the math library, as stated on their website.
Yet another solution, assuming the number of items in the folder is not huge:
tar -czf workspace.tar.gz `ls -A`
(ls -A
prints normal and hidden files but not "." and ".." as ls -a
does.)
The problem is that you mapped your servlet to /register.html
and it expects POST method, because you implemented only doPost()
method. So when you open register.html
page, it will not open html page with the form but servlet that handles the form data.
Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).
To fix:
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-
When we mark a parameter as optional in the action uri using ?
character then we must provide default values to the parameters in the method signature as shown below:
MyMethod(string name = "someDefaultValue", int? Id = null)
I believe your best shot is to declare the list as a list of objects:
List<Object> anything = new ArrayList<Object>();
Then you can put whatever you want in it, like:
anything.add(new Employee(..))
Evidently, you will not be able to read anything out of the list without a proper casting:
Employee mike = (Employee) anything.get(0);
I would discourage the use of raw types like:
List anything = new ArrayList()
Since the whole purpose of generics is precisely to avoid them, in the future Java may no longer suport raw types, the raw types are considered legacy and once you use a raw type you are not allowed to use generics at all in a given reference. For instance, take a look a this another question: Combining Raw Types and Generic Methods
I've read some good answers here; however, there are some minor mistakes. Some have answered that the Message Length field in the UDP header is a max of 65535 (0xFFFF); this is technically true. Some have answered that the actual maximum is (65535 - IPHL - UDPHL = 65507). The mistake, is that the Message Length field in the UDP Header includes all payload (Layers 5-7), plus the length of the UDP Header (8 Bytes). What this means is that if the message length field is 200 Bytes (0x00C8), the payload is actually 192 Bytes (0x00C0).
What is hard and fast is that the maximum size of an IP datagram is 65535 Bytes. This number is arrived at the sum total of the L3 and L4 headers, plus the Layers 5-7 payload. IP Header + UDP Header + Layers 5-7 = 65535 (Max).
The most correct answer for what is the maximum size of a UDP datagam is 65515 Bytes (0xFFEB), as a UDP datagram includes the UDP header. The most correct answer for what is the maximum size of a UDP payload is 65507 Bytes, as a UDP Payload does not include the UDP header.
Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.
import React from 'react';
import { Link } from 'react-router';
export default class Nav extends React.Component {
render() {
return (
<nav className="Nav">
<div className="Nav__container">
<Link to="/" className="Nav__brand">
<img src="logo.svg" className="Nav__logo" />
</Link>
<div className="Nav__right">
<ul className="Nav__item-wrapper">
<li className="Nav__item">
<Link className="Nav__link" to="/path1">Link 1</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path2">Link 2</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path3">Link 3</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<div>
<Nav />
<Switch>
<Route exactly component={Landing} pattern="/" />
<Route exactly component={Page1} pattern="/path1" />
<Route exactly component={Page2} pattern="/path2" />
<Route exactly component={Page3} pattern="/path3" />
<Route component={Page404} />
</Switch>
</div>
</Router>
</div>
);
}
}
Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar
A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
const NavRoute = ({exact, path, component: Component}) => (
<Route exact={exact} path={path} render={(props) => (
<div>
<Header/>
<Component {...props}/>
</div>
)}/>
)
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Switch>
<NavRoute exactly component={Landing} pattern="/" />
<Route exactly component={Login} pattern="/login" />
<NavRoute exactly component={Page1} pattern="/path1" />
<NavRoute exactly component={Page2} pattern="/path2" />
<NavRoute component={Page404} />
</Switch>
</Router>
</div>
);
}
}
Just for the record solution that works across most database engines though might not be the most efficient:
Select Top (ReturnCount) *
From (
Select Top (SkipCount + ReturnCount) *
From SourceTable
Order By ReverseSortCondition
) ReverseSorted
Order By SortCondition
Pelase note: the last page would still contain ReturnCount rows no matter what SkipCount is. But that might be a good thing in many cases.
Not an official name per se, but I've heard vertical ellipsis referred to as "snowman" in SAS community.
There's better support for this now through conda-env
. You can, for example, now do:
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"
It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml
file.
If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml
), then run the command: conda env update -f environment.yml
.
It's more likely that you would want to create a new environment:
conda env create -f environment.yml
(changed as supposed in the comments)
try this:
Use ´return false´ for to cut the flow of the event:
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
Edit
corroborate if the form element with the 'length' of jQuery:
alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
OR:
it waits for the DOM is ready:
jQuery(function() {
alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
});
Do you put your code inside the event "ready" the document or after the DOM is ready?
I personally prefer VisualVM. One of the features I like in VisualVM is heap dump comparison. When you are doing a heap dump analysis there are various ways to go about figuring out what caused the crash. One of the ways I have found useful is doing a comparison of healthy vs unhealthy heap dumps.
Following are the steps you can follow for it :
link : https://visualvm.github.io
Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.
df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])
in df.index
works for the first level only when checking single index value.
'a' in df.index # True
'X' in df.index # False
Check df.index.levels
for other levels.
'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True
Check in df.index
for an index combination tuple.
('a', 'X') in df.index # True
('a', 'Y') in df.index # False
HTML
<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>
JavaScript
jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
I think it is the domain that you run your app.
For example, your canvas URL is facebook.yourdomain.com, you should give App domain as .yourdomain.com
It's been many functions, macros and objects since I posted this question. The way I handled it, which is mentioned in one of the answers here, is by creating a string function that handles the errors that get generate by the vlookup function, and returns either nothing or the vlookup result if any.
Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String
Dim s As String
On Error Resume Next
s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False)
If IsError(s) Then
fsVlookup = ""
Else
fsVlookup = s
End If
End Function
One could argue about the position of the error handling or by shortening this code, but it works in all cases for me, and as they say, "if it ain't broke, don't try and fix it".
I don't have a windows box handy to try this but I think you can use a DataView and do something like so:
DataView view = new DataView(ds.Tables["MyTable"]);
view.RowFilter = "MyValue = 42"; // MyValue here is a column name
// Delete these rows.
foreach (DataRowView row in view)
{
row.Delete();
}
I haven't tested this, though. You might give it a try.
Add a column to your existing data to get rid of the hour:minute:second time stamp on each row:
=DATE(YEAR(A1), MONTH(A1), DAY(A1))
Extend this down the length of your data. Even easier: quit collecting the hh:mm:ss data if you don't need it. Assuming your date/time was in column A, and your value was in column B, you'd put the above formula in column C, and auto-extend it for all your data.
Now, in another column (let's say E), create a series of dates corresponding to each day of the specific month you're interested in. Just type the first date, (for example, 10/7/2016 in E1), and auto-extend. Then, in the cell next to the first date, F1, enter:
=SUMIF(C:C, E1, B:B )
autoextend the formula to cover every date in the month, and you're done. Begin at 1/1/2016, and auto-extend for the whole year if you like.
an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.
Another solution is to mix valueChangeListener, ajax and process:
<p:selectManyCheckbox id="employees" value="#{employees}" columns="1" layout="grid" valueChangeListener="#{mybean.fireSelection}" >
<f:selectItems var="employee" value="#{employeesSI}" />
<p:ajax event="valueChange" immediate="true" process="@this"/>
</p:selectManyCheckbox>
Method in mybean is just :
public void fireSelection(ValueChangeEvent event) {
log.debug("New: "+event.getNewValue()+", Old: "+event.getOldValue());
}
Like this, valueChangeEvent is very light !
PS: Works fine with PrimeFaces 5.0
I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. Send your specific date, and get its value in string form:
public string RelativeDateTimeCount(DateTime inputDateTime)
{
string outputDateTime = string.Empty;
TimeSpan ts = DateTime.Now - inputDateTime;
if (ts.Days > 7)
{ outputDateTime = inputDateTime.ToString("MMMM d, yyyy"); }
else if (ts.Days > 0)
{
outputDateTime = ts.Days == 1 ? ("about 1 Day ago") : ("about " + ts.Days.ToString() + " Days ago");
}
else if (ts.Hours > 0)
{
outputDateTime = ts.Hours == 1 ? ("an hour ago") : (ts.Hours.ToString() + " hours ago");
}
else if (ts.Minutes > 0)
{
outputDateTime = ts.Minutes == 1 ? ("1 minute ago") : (ts.Minutes.ToString() + " minutes ago");
}
else outputDateTime = "few seconds ago";
return outputDateTime;
}
For me, it just was that service console restart didn't work after tomcat ran into an error. Only stop/start brought it back.
I thing ng-if
should work:
<div ng-repeat="product in products" ng-if="product.color === 'red'
|| product.color === 'blue'">
None of these answers worked for me. I'm now using:
document.addEventListener('dragleave', function(e){
var top = e.pageY;
var right = document.body.clientWidth - e.pageX;
var bottom = document.body.clientHeight - e.pageY;
var left = e.pageX;
if(top < 10 || right < 20 || bottom < 10 || left < 10){
console.log('Mouse has moved out of window');
}
});
I'm using this for a drag and drop file uploading widget. It's not absolutely accurate, being triggered when the mouse gets to a certain distance from the edge of the window.
There's a few approaches for this:
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
This is based on @Macarse answer.
Use this to get the resources Id in a more faster and code friendly way.
public static int getId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
Example:
getId("icon", R.drawable.class);
What worked for me was upgrading pandas to latest version:
From Command Line do:
conda update pandas
In my case it was due to a bad URL (http://
instead of git://
, no .git
at the end) for one of the dependencies.
I found a nice solution which does not need an event to be triggered:
@FXML
private Button cancelButton;
close(new Event(cancelButton, stage, null));
@FXML
private void close(Event event) {
((Node)(event.getSource())).getScene().getWindow().hide();
}
When this happens to me, it is because DNS is not working properly. Try using the IP address instead of the server name in the SQL Server login.
Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file()
(it's called move not store) for more.
There is a ToArray() function on Values:
Foo[] arr = new Foo[dict.Count];
dict.Values.CopyTo(arr, 0);
But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:
IEnumerable<Foo> foos = dict.Values;
For mobiles, it’s better to use it
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
because it will display incorrectly after changing the orientation.The “viewport” will be increased when changing the orientation to portrait.See full example
Here I am providing a negative example where your want to avoid when converting floating number to strings.
float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;
You get
99463 99.463 99.462997
Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.
I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.
string ftos(float f, int nd) {
ostringstream ostr;
int tens = stoi("1" + string(nd, '0'));
ostr << round(f*tens)/tens;
return ostr.str();
}
yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"
Try the below code:
Sub opendfiles()
Dim myfile As Variant
Dim counter As Integer
Dim path As String
myfolder = "D:\temp\"
ChDir myfolder
myfile = Application.GetOpenFilename(, , , , True)
counter = 1
If IsNumeric(myfile) = True Then
MsgBox "No files selected"
End If
While counter <= UBound(myfile)
path = myfile(counter)
Workbooks.Open path
counter = counter + 1
Wend
End Sub
add
credits: {
enabled: false
}
[NOTE] that it is in the same line with
xAxis: {}
and yAxis: {}
UPDATE: I have created a video on sending multipart/form-data requests to explain this better.
Actually, Postman can do this. Here is a screenshot
Newer version : Screenshot captured from postman chrome extension
Another version
Older version
Make sure you check the comment from @maxkoryukov
Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
found = False
def check():
datafile = file('example.txt')
for line in datafile:
if blabla in line:
found = True
break
return found
if check():
print "true"
else:
print "false"
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
is you want fix XSS on input element? you can encode string before output to input field
PHP:
$str = htmlentities($str);
C#:
str = WebUtility.HtmlEncode(str);
after that output value direct to input field:
<input type="text" value="<?php echo $str" />
Inspired by Samuel's answer, I wrote an improved version:
The resulting source code is over 30K characters so I can't post it here, check it on Github.
When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.
If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/
<div class="parent">
<img src="http://placehold.it/500x500" class="img-responsive"/>
<div class="fa fa-plus project-overlay"></div>
</div>
.parent {
position: relative;
}
If you also want to make this deletion operation chainable, so you can delete some item and keep on chaining operations on the resulting array, use tap
:
[2, 4, 6, 3, 8].tap { |ary| ary.delete(3) }.count #=> 4
Swift 5.*
Navigation:
guard let myVC = self.storyboard?.instantiateViewController(withIdentifier: "MyViewController") else { return }
let navController = UINavigationController(rootViewController: myVC)
self.navigationController?.present(navController, animated: true, completion: nil)
Going Back:
self.dismiss(animated: true, completion: nil)
Swift 2.0
Navigation:
let myVC = self.storyboard?.instantiateViewControllerWithIdentifier("MyViewController");
let navController = UINavigationController(rootViewController: myVC!)
self.navigationController?.presentViewController(navController, animated: true, completion: nil)
Going Back:
self.dismissViewControllerAnimated(true, completion: nil)
I got this working with the following directive:
app.directive('datatableSetup', function () {
return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});
And in the HTML:
<table class="table table-hover dataTable dataTable-columnfilter " datatable-setup="">
trouble shooting if the above doesnt work for you.
1) note that 'datatableSetup' is the equivalent of 'datatable-setup'. Angular changes the format into camel case.
2) make sure that app is defined before the directive. e.g. simple app definition and directive.
var app = angular.module('app', []);
app.directive('datatableSetup', function () {
return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});
Well, I can understand your pain, but, quite frankly, people like you and I -- or pretty much any regular Stack Overflow user -- are not the rule.
What I mean by that is that... most programmers won't care about that type signature, because they'll never see them! They don't read documentation.
As long as they saw some example of how the code works, and the code doesn't fail them in producing the result they expect, they won't ever look at the documentation. When that fails, they'll look at the documentation and expect to see usage examples at the top.
With these things in mind, I think that:
Anyone (as in, most people) who ever comes across that type signature will mock Scala to no end if they are pre-disposed against it, and will consider it a symbol of Scala's power if they like Scala.
If the documentation isn't enhanced to provide usage examples and explain clearly what a method is for and how to use it, it can detract from Scala adoption a bit.
In the long run, it won't matter. That Scala can do stuff like that will make libraries written for Scala much more powerful and safer to use. These libraries and frameworks will attract programmers atracted to powerful tools.
Programmers who like simplicity and directness will continue to use PHP, or similar languages.
Alas, Java programmers are much into power tools, so, in answering that, I have just revised my expectation of mainstream Scala adoption. I have no doubt at all that Scala will become a mainstream language. Not C-mainstream, but perhaps Perl-mainstream or PHP-mainstream.
Speaking of Java, did you ever replace the class loader? Have you ever looked into what that involves? Java can be scary, if you look at the places framework writers do. It's just that most people don't. The same thing applies to Scala, IMHO, but early adopters have a tendency to look under each rock they encounter, to see if there's something hiding there.
Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args
parameter), is to compile normally, and use r arg1 arg2 arg3
directly from within gdb
, like so:
$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3
JSL 1.7
The Oracle documentation mentions:
unchecked
: Unchecked warnings are identified by the string "unchecked". deprecation
: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); orIt then explains that implementations can add and document their own:
Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.
Try this:
<marquee behavior="" Height="200px" direction="up" scroll onmouseover="this.setAttribute('scrollamount', 0, 0);this.stop();" onmouseout="this.setAttribute('scrollamount', 3, 0);this.start();" scrollamount="3" valign="center">
<img src="images/a.jpg">
<img src="images/a.jpg">
<img src="images/a.jpg">
<img src="images/a.jpg">
<img src="images/a.jpg">
<img src="images/a.jpg">
</marquee>
Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section
within your _Layout
which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
@RenderSection("Scripts",false/*required*/)
</head>
<body>
@RenderBody()
</body>
</html>
@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
<script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}
Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script>
declaration within the view.
https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso
There is much more to this but this is a high level overview on which is which.
Procore supports both SP- and IdP-initiated SSO:
Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.
A very portable version (even to legacy bourne shell):
if [ "$varA" = 1 -a \( "$varB" = "t1" -o "$varB" = "t2" \) ]
then do-something
fi
This has the additional quality of running only one subprocess at most (which is the process [
), whatever the shell flavor.
Replace =
with -eq
if variables contain numeric values, e.g.
3 -eq 03
is true, but3 = 03
is false. (string comparison)Use this:
if(string.endsWith("x")) {
string= string.substring(0, string.length() - 1);
}
You're using an Array
like an "associative array", which does not exist in JavaScript. Use an Object
({}
) instead.
If you are going to continue with an array, realize that toString()
will join all the numbered properties together separated by a comma. (the same as .join(",")
).
Properties like a
and b
will not come up using this method because they are not in the numeric indexes. (ie. the "body" of the array)
In JavaScript, Array inherits from Object
, so you can add and delete properties on it like any other object. So for an array, the numbered properties (they're technically just strings under the hood) are what counts in methods like .toString()
, .join()
, etc. Your other properties are still there and very much accessible. :)
Read Mozilla's documentation for more information about Arrays.
var aa = [];
// these are now properties of the object, but not part of the "array body"
aa.a = "A";
aa.b = "B";
// these are part of the array's body/contents
aa[0] = "foo";
aa[1] = "bar";
aa.toString(); // most browsers will say "foo,bar" -- the same as .join(",")
Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib
Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.
As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:
/targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"
Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:
/targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.
Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.
Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.
Holdover from C.
You can use it to raise errors as part of error-checking:
if (a < b):
raise ValueError()
Or handle some errors, and then pass them on as part of error-handling:
try:
f = open('file.txt', 'r')
except IOError:
# do some processing here
# and then pass the error on
raise
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
select with no lock - will select records which may / may not going to be inserted. you will read a dirty data.
for example - lets say a transaction insert 1000 rows and then fails.
when you select - you will get the 1000 rows.
Refer the scripts inside the angular-cli.json
(angular.json
when using angular 6+) file.
"scripts": [
"../path"
];
then add in typings.d.ts
(create this file in src
if it does not already exist)
declare var variableName:any;
Import it in your file as
import * as variable from 'variableName';
Install C++ SDK:
Help > Install New Software > Work with: path for your eclipse version
> search for C++ and install C++ sdk development tools.
Example for a path: Mars - http://download.eclipse.org/releases/mars
For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr
and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr
:
// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);
Here is the complete C# 7 solution...
switch (value)
{
case var s when new[] { 1,2,3 }.Contains(s):
// Do something
break;
case var s when new[] { 4,5,6 }.Contains(s):
// Do something
break;
default:
// Do the default
break;
}
It works with strings too...
switch (mystring)
{
case var s when new[] { "Alpha","Beta","Gamma" }.Contains(s):
// Do something
break;
...
}
Same answer as above, but with async await
and ready to use!
const fs = require('fs/promises');
const path = require('path');
async function isExists(path) {
try {
await fs.access(path);
return true;
} catch {
return false;
}
};
async function writeFile(filePath, data) {
try {
const dirname = path.dirname(filePath);
const exist = await isExists(dirname);
if (!exist) {
await fs.mkdir(dirname, {recursive: true});
}
await fs.writeFile(filePath, data, 'utf8');
} catch (err) {
throw new Error(err);
}
}
Example:
(async () {
const data = 'Hello, World!';
await writeFile('dist/posts/hello-world.html', data);
})();
I like @Anders answer because the explanation of the %~z1 secret sauce. However, as pointed out, that only works when the filename is passed as the first parameter to the batch file.
@Anders worked around this by using FOR
, which, is a great 1-liner fix to
the problem, but, it's somewhat harder to read.
Instead, we can go back to a simpler answer with %~z1 by using CALL
.
If you have a filename stored in an environment variable it will become
%1 if you use it as a parameter to a routine in your batch file:
@echo off
setlocal
set file=test.cmd
set maxbytesize=1000
call :setsize %file%
if %size% lss %maxbytesize% (
echo File is less than %maxbytesize% bytes
) else (
echo File is greater than or equal %maxbytesize% bytes
)
goto :eof
:setsize
set size=%~z1
goto :eof
I've been curious about J. Bouvrie's concern regarding 32-bit limitations. It appears he is talking about an issue with using LSS
not on the filesize logic itself. To deal with J. Bouvrie's concern, I've rewritten the solution to use a padded string comparison:
@echo on
setlocal
set file=test.cmd
set maxbytesize=1000
call :setsize %file%
set checksize=00000000000000000000%size%
set checkmaxbytesize=00000000000000000000%maxbytesize%
if "%checksize:~-20%" lss "%checkmaxbytesize:~-20%" (
echo File is less than %maxbytesize% bytes
) else (
echo File is greater than or equal %maxbytesize% bytes
)
goto :eof
:setsize
set size=%~z1
goto :eof
change your code to:
function ChangePurpose(Vid, PurId) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
async: false,
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
Success = true;
},
error: function (textStatus, errorThrown) {
Success = false;
}
});
//done after here
return Success;
}
You can only return the values from a synchronous
function. Otherwise you will have to make a callback
.
So I just added async:false,
to your ajax call
Update:
jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.
A better approach will be:
// callbackfn is the pointer to any function that needs to be called
function ChangePurpose(Vid, PurId, callbackfn) {
var Success = false;
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
success: function (data) {
callbackfn(data)
},
error: function (textStatus, errorThrown) {
callbackfn("Error getting the data")
}
});
}
function Callback(data)
{
alert(data);
}
and call the ajax as:
// Callback is the callback-function that needs to be called when asynchronous call is complete
ChangePurpose(Vid, PurId, Callback);
Use WORKSPACE environment variable to change workspace directory.
If doing using Jenkinsfile, use following code :
dir("${env.WORKSPACE}/aQA"){
sh "pwd"
}
If you have lots of columns and only one is different you could do:
In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
Organisation Name Amount
Company Name
Vifor Pharma UK Ltd 5 4207.93
Note you can then rename the Organisation Name column as you wish.
I personally prefer the simpler syntax of the ~ operator.
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;
Worth reading through Difference between LIKE and ~ in Postgres to understand the difference. `
you can also use gcc -v
command that works like gcc --version
and if you would like to now where gcc
is you can use whereis gcc
command
I hope it'll be usefull
If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools
Example, function BS_SQL("SELECT ...")
:
Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet
and inside it you will have two methods that look like
public void doPost(HttpServletRequest req, HttpServletResponse resp){
}
and
public void doGet(HttpServletRequest req, HttpServletResponse resp){
}
One of them is called to handle GET
operations and another is used to handle POST
operations. You will then use the HttpServletRequest
object to get the parameters that were passed as part of the form like so:
String name = req.getParameter("name");
Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.
You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp ) to save values before refreshing the page.
Here is a demo. Use position:fixed; top:0; left:0;
so the header always stay on top.
?#header {
background:red;
height:50px;
width:100%;
position:fixed;
top:0;
left:0;
}.scroller {
height:300px;
overflow:scroll;
}
Typeface.js and Cufon are two other interesting options. They are JavaScript components that render special font data in JSON format (which you can convert from TrueType or OpenType formats on their web sites) via the new <canvas> element in all newer browsers except Internet Explorer and via VML in Internet Explorer.
The main problem with both (as of now) is that selecting text does not work or at least works only quite awkwardly.
Still, it is very nice for headlines. Body text... I don't know.
And it's surprisingly fast.
Setting a custom font to a regular ProgressDialog/AlertDialog:
font=Typeface.createFromAsset(getAssets(),"DroidSans.ttf");
ProgressDialog dialog = ProgressDialog.show(this, "titleText", "messageText", true);
((TextView)dialog.findViewById(Resources.getSystem().getIdentifier("message", "id", "android"))).setTypeface(font);
((TextView)dialog.findViewById(Resources.getSystem().getIdentifier("alertTitle", "id", "android"))).setTypeface(font);
The documentation states several ways to do this.
If you want to replace the default
ObjectMapper
completely, define a@Bean
of that type and mark it as@Primary
.Defining a
@Bean
of typeJackson2ObjectMapperBuilder
will allow you to customize both defaultObjectMapper
andXmlMapper
(used inMappingJackson2HttpMessageConverter
andMappingJackson2XmlHttpMessageConverter
respectively).
I prefer this syntax as it allows to set configuration parameters for the shell:
---
- name: an example
shell:
cmd: |
docker build -t current_dir .
echo "Hello World"
date
chdir: /home/vagrant/
You can use the DataFrame method .apply()
to operate on the values in Mycol:
>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
Mycol
0 05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x:
dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
Mycol
0 2014-09-05
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag
and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object"
.
Should you set Symbol.toStringTag
? Maybe. But relying on the string always being [object Object]
for "true" objects is not the best idea.
try this
ini_set("SMTP","aspmx.l.google.com");
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: [email protected]" . "\r\n";
mail("[email protected]","test subject","test body",$headers);
This should give you the required layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/flag"
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Play with the android:layout_marginTop="20dp"
to see which one suits you better. Use the id textview
to dynamically set the android:text
value.
Since a RelativeLayout stacks its children, defining the TextView after ImageView puts it 'over' the ImageView.
NOTE: Similar results can be obtained using a FrameLayout
as the parent, along with the efficiency gain over using any other android container. Thanks to Igor Ganapolsky
(see comment below) for pointing out that this answer needs an update.
HTML5 basically behaves as if the trailing slash is not there. There is no such thing as a self-closing tag in HTML5 syntax.
Self-closing tags on non-void elements like <p/>
, <div/>
will not work at all. The trailing slash will be ignored, and these will be treated as opening tags. This is likely to lead to nesting problems.
This is true regardless of whether there is whitespace in front of the slash: <p />
and <div />
also won't work for the same reason.
Self-closing tags on void elements like <br/>
or <img src="" alt=""/>
will work, but only because the trailing slash is ignored, and in this case that happens to result in the correct behaviour.
The result is, anything that worked in your old "XHTML 1.0 served as text/html" will continue to work as it did before: trailing slashes on non-void tags were not accepted there either whereas the trailing slash on void elements worked.
One more note: it is possible to represent an HTML5 document as XML, and this is sometimes dubbed "XHTML 5.0". In this case the rules of XML apply and self-closing tags will always be handled. It would always need to be served with an XML mime type.
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
The (m)
indicates the column display width; applications such as the MySQL client make use of this when showing the query results.
For example:
| v | a | b | c |
+-----+-----+-----+-----+
| 1 | 1 | 1 | 1 |
| 10 | 10 | 10 | 10 |
| 100 | 100 | 100 | 100 |
Here a
, b
and c
are using TINYINT(1)
, TINYINT(2)
and TINYINT(3)
respectively. As you can see, it pads the values on the left side using the display width.
It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1)
still accepts [-128 .. 127]
.
Alternatively, you can use the matplotlib.pyplot.axis() function, which allows you inverting any of the plot axis
ax = matplotlib.pyplot.axis()
matplotlib.pyplot.axis((ax[0],ax[1],ax[3],ax[2]))
Or if you prefer to only reverse the X-axis, then
matplotlib.pyplot.axis((ax[1],ax[0],ax[2],ax[3]))
Indeed, you can invert both axis:
matplotlib.pyplot.axis((ax[1],ax[0],ax[3],ax[2]))
It seems you are hitting a UTF-8 byte order mark (BOM). Try using this unicode string with BOM extracted out:
import codecs
content = unicode(q.content.strip(codecs.BOM_UTF8), 'utf-8')
parser.parse(StringIO.StringIO(content))
I used strip
instead of lstrip
because in your case you had multiple occurences of BOM, possibly due to concatenated file contents.
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
For me i was using MYSQLWorkbench and the port was 3306 MAMP using 8889
You can use now()
like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Sometimes it can make the assignment of a bool value easier to read at first glance:
// With
button.IsEnabled = someControl.HasError ? false : true;
// Without
button.IsEnabled = !someControl.HasError;
We had this exact problem with our ETL jobs at Snowplow, so we extracted our parallel file-copy code (Ruby, built on top of Fog), into its own Ruby gem, called Sluice:
https://github.com/snowplow/sluice
Sluice also handles S3 file delete, move and download; all parallelised and with automatic re-try if an operation fails (which it does surprisingly often). I hope it's useful!
In my case, I just had to do
It all then went fine. I still have no clue what happened.
import os
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def file_size(file_path):
"""
this function will return the file size
"""
if os.path.isfile(file_path):
file_info = os.stat(file_path)
return convert_bytes(file_info.st_size)
# Lets check the file size of MS Paint exe
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)
Result:
6.1 MB
Use String.PadLeft like this:
var result = input.ToString().PadLeft(length, '0');
Add the Library file in project.. Project->right click->Properties->android->Library-> click Add and select the Library Project and give apply and ok.. then, clean the project and run again.. if you want restart the eclipse..
And also, sometimes, need to update Android SDK build tools..
What you are looking for is probably this:
ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"
int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);
Let me know if this was helpful :)
edit_text.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" />
<corners android:radius="5dp"/>
<stroke android:width="2dip" android:color="@color/button_color_submit" />
</shape>
use here
<EditText
-----
------
android:background="@drawable/edit_text.xml"
/>