If anyone else runs into this issue and none of the above solutions work due to "Duplicate identifier" issues, run this:
npm install typings --global
With older versions of typings things mess up and you'll get a bunch of "Duplicate identifier" issues. Also you don't need to use --ambient
anymore as far as I could tell.
So once typings is up to date, this should work (using the Angular 2 quickstart).
Run:
npm install lodash --save
typings install lodash --save
First, add this to systemjs.config.js:
'lodash': 'node_modules/lodash/lodash.js'
Now you can use this in any file: import * as _ from 'lodash';
Delete your typings folder and run npm install
if you're still having issues.
Since pip v1.5
, (released Jan 1 2014: CHANGELOG, PR) you may also specify a subdirectory of a git repo to contain your module. The syntax looks like this:
pip install -e git+https://git.repo/some_repo.git#egg=my_subdir_pkg&subdirectory=my_subdir_pkg # install a python package from a repo subdirectory
Note: As a pip module author, ideally you'd probably want to publish your module in it's own top-level repo if you can. Yet this feature is helpful for some pre-existing repos that contain python modules in subdirectories. You might be forced to install them this way if they are not published to pypi too.
Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.
For example if you delete a record using ORM, and your DELETE CASCADE
will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
The Boolean object doesn't have a 'parse' method. Boolean('false')
returns true, so that won't work. !!'false'
also returns true
, so that won't work also.
If you want string 'true'
to return boolean true
and string 'false'
to return boolean false
, then the simplest solution is to use eval()
. eval('true')
returns true and eval('false')
returns false. Keep in mind the performance implications when using eval()
though.
To Hex:
string hex = intValue.ToString("X");
To int:
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
You can also use bashible (which internally uses the evaluating approach described above/below).
There is an example, how to generate a HTML from multiple parts:
https://github.com/mig1984/bashible/tree/master/examples/templates
short direct answer is no or not out of the box but i have come up with a method to use a text box and pure JS code to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.
Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.
for %a in (*.*) do ren "%~a" "%~na-affix%~xa"
You can change the "-affix" part.
Here's an answer that actually gives the solution the OP asked for:
>>> d = {320:1, 321:0, 322:3}
>>> d.items()
[(320, 1), (321, 0), (322, 3)]
>>> # find the minimum by comparing the second element of each tuple
>>> min(d.items(), key=lambda x: x[1])
(321, 0)
Using d.iteritems()
will be more efficient for larger dictionaries, however.
Jenkins uses Cron format on scheduling. You can refer this link for more detailhttps://en.wikipedia.org/wiki/Cron. One more thing, Jenkins provide us a very useful preview. Please take a look on the screenshot.
I hope this help. Thanks
You might like IntervalHeap from the C5 Generic Collection Library. To quote the user guide
Class
IntervalHeap<T>
implements interfaceIPriorityQueue<T>
using an interval heap stored as an array of pairs. TheFindMin
andFindMax
operations, and the indexer’s get-accessor, take time O(1). TheDeleteMin
,DeleteMax
, Add and Update operations, and the indexer’s set-accessor, take time O(log n). In contrast to an ordinary priority queue, an interval heap offers both minimum and maximum operations with the same efficiency.
The API is simple enough
> var heap = new C5.IntervalHeap<int>();
> heap.Add(10);
> heap.Add(5);
> heap.FindMin();
5
Install from Nuget https://www.nuget.org/packages/C5 or GitHub https://github.com/sestoft/C5/
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
Make a text using notepad or any text editor of you choice. Open notepad, write this short command "cmd.exe" without the quote aand save it as cmd.bat.
Click cmd.bat and choose "run as administrator".
What is the difference between left join and left outer join?
Nothing. LEFT JOIN
and LEFT OUTER JOIN
are equivalent.
Look at placing your radio buttons in a GroupBox.
It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of .
or ..
is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments .
and ..
”, without clarifying whether they match .
and ..
before or after pct-encoding.
Personally I find Firefox's interpretation that %2E
does not mean .
most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only .
or ..
.
I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F
, %00
and %5C
sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.
This works for me.
json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Suppose JSON file is like this:
{
"emp_details":[
{
"emp_name":"John",
"emp_emailId":"[email protected]"
},
{
"emp_name":"Aditya",
"emp_emailId":"[email protected]"
}
]
}
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
#Output:
{'emp_name':'John','emp_emailId':'[email protected]'}
{'emp_name':'Aditya','emp_emailId':'[email protected]'}
How about this (in you don't want an one liner) ?
for row in df.collect():
d = row.asDict()
s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
f.write(s)
f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.
The best way I found is count by converting it to a list.
IEnumerable<T> enumList = ReturnFromSomeFunction();
int count = new List<T>(enumList).Count;
If you are in that phase of development where you have an method inside your context class that creates testdata for you, don't call it in your constructor, it will try to create those test records while you don't have tables yet. Just sharing my mistake...
select replace(wm_concat(new),',','-') exp_res from (select distinct initcap(substr(name,decode(level,1,1,instr(name,'-',1,level-1)+1),decode(level,(length(name)-length(replace(name,'-','')))+1,9999,instr(name,'-',1,level)-1-decode(level,1,0,instr(name,'-',1,level-1))))) new from table;
connect by level<= (select (length(name)-length(replace(name,'-','')))+1 from table));
Alternative:
boolean isWhiteSpaces( String s ) {
return s != null && s.matches("\\s+");
}
Your problem is that you have key
and value
in quotes making them strings, i.e. you're setting aKey
to contain the string "key"
and not the value of the variable key
. Also, you're not clearing out the temp
list, so you're adding to it each time, instead of just having two items in it.
To fix your code, try something like:
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
You don't need to copy the loop variables key
and value
into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value])
if we wanted to be as brief as possible.
Or just use dict.items()
as has been suggested.
I'd just add to the answers the "why?".
.
is standard member access operator that has a higher precedence than *
pointer operator.
When you are trying to access a struct's internals and you wrote it as *foo.bar
then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.
Thus you need to ask the compiler to first dereference whith (*foo)
and then access the member element: (*foo).bar
, which is a bit clumsy to write so the good folks have come up with a shorthand version: foo->bar
which is sort of member access by pointer operator.
You shouldn't be using .findall()
at all - .search()
is what you want. It finds the leftmost match, which is what you want (or returns None
if no match exists).
m = re.search(pattern, text)
result = m.group(0) if m else ""
Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search()
on its own finds a match (it returns None
if it didn't, or an SRE_Match
object if it did).
Coming late to the party, but since I had the additional requirement of having one word per line, this one addition did the trick for me:
label.numberOfLines = [labelString componentsSeparatedByString:@" "].count;
Apple Docs say:
Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.
But this is a lie. A lie I tell you! It's true for all iOS versions. Specifically, this is true when using a UILabel
within a UICollectionViewCell
for which the size is determined by constraints adjusted dynamically at runtime via custom layout (ex. self.menuCollectionViewLayout.itemSize = size
).
So when used in conjunction with adjustsFontSizeToFitWidth
and minimumScaleFactor
, as mentioned in previous answers, programmatically setting numberOfLines
based on word count solved the autoshrink problem. Doing something similar based on word count or even character count might produce a "close enough" solution.
Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.
I'm new to python (really really new) and in one of the books I'm reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:
Open shell / Create new document / Create function as follows:
def clear():
print('\n' * 50)
Save it inside the lib folder in you python directory (mine is C:\Python33\Lib) Next time you nedd to clear your console just call the function with:
clear()
that's it. PS: you can name you function anyway you want. Iv' seen people using "wiper" "wipe" and variations.
For versions prior to 3.0 honeycomb: Yes, do call System.gc()
.
I tried to create Bitmaps, but was always getting "VM out of memory error". But, when I called System.gc()
first, it was OK.
When creating bitmaps, Android often fails with out of memory errors, and does not try to garbage collect first. Hence, call System.gc()
, and you have enough memory to create Bitmaps.
If creating Objects, I think System.gc
will be called automatically if needed,
but not for creating bitmaps. It just fails.
So I recommend manually calling System.gc()
before creating bitmaps.
A major practical difference is its use:
in security scenario
where we always needed a new session, we should use request.getSession(true)
.
request.getSession(false): will return null if no session found.
I know the purists will hate this method, but you can cat
the file.
NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
echo "$NAME"
done
I was now able to find reason behind the error guys. It's on the webhosting site settings not on my app pool or what so ever. I changed the asp.net version from 2.0 to 4.0 but I forgot to click the update button. I feel so embarrased. :( I've been struggling for days to fix this error and only to found out its on the webhosting site settings. GgrrRR.. As of now I'm facing new error but has nothing to do with this question. Anyway thanks guys for your efforts to help me. :)
Simple PHP function to unzip. Please make sure you have zip extension installed on your server.
/**
* Unzip
* @param string $zip_file_path Eg - /tmp/my.zip
* @param string $extract_path Eg - /tmp/new_dir_name
* @return boolean
*/
function unzip(string $zip_file_path, string $extract_dir_path) {
$zip = new \ZipArchive;
$res = $zip->open($zip_file_path);
if ($res === TRUE) {
$zip->extractTo($extract_dir_path);
$zip->close();
return TRUE;
} else {
return FALSE;
}
}
Follow the below example --
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
The access to your Apache server is forbidden from addresses other than 127.0.0.1
in httpd.conf
(Apache's config file) :
<Directory "c:/wamp/www/">
Options Indexes FollowSymLinks
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
The same goes for your PHPMyAdmin access, the config file is phpmyadmin.conf
:
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
You can set them to allow connections from all IP addresses like follows :
AllowOverride All
Order allow,deny
Allow from all
in mysql workbench server>>>>>>export Data then follow instructions it will generate insert statements for all tables data each table will has .sql file for all its contained data
For Each row As DataGridViewRow In yourDGV.SelectedRows
yourDGV.Rows.Remove(row)
Next
This will delete all rows that had been selected.
But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.
Replace in System Sounds the "Critical Stop" to a wav-file which is silent 1.
Just removing the sound completely did not work for me. Apparently some default sound was used in this case.
(Credits for this.lau_ on SuperUser for discovering this).
What the browser does when you've got
<a onclick="alert('Hi');" ... >
is to set the actual value of "onclick" to something effectively like:
new Function("event", "alert('Hi');");
That is, it creates a function that expects an "event" parameter. (Well, IE doesn't; it's more like a plain simple anonymous function.)
For iOS 4+ or OS X 10.6+, Apple added passingTest
series of APIs in NSMutableArray
, like – indexesOfObjectsPassingTest:
. A solution with such API would be:
NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [self shouldRemove:obj];
}];
[someList removeObjectsAtIndexes:indexesToBeRemoved];
In case it helps somebody else, I got this error message after accidentally deleting .git/objects/
fatal: Not a git repository (or any of the parent directories): .git
Restoring it solved the problem.
Try an HTML table or use the following CSS :
<div id="bloc1" style="float:left">...</div>
<div id="bloc2">...</div>
(or use an HTML table)
There are two stages for how events propagate. These are called "capturing" and "bubbling".
| | / \
---------------| |----------------- ---------------| |-----------------
| element1 | | | | element1 | | |
| -----------| |----------- | | -----------| |----------- |
| |element2 \ / | | | |element2 | | | |
| ------------------------- | | ------------------------- |
| Event CAPTURING | | Event BUBBLING |
----------------------------------- -----------------------------------
The capturing stage happen first, and are then followed by the bubbling stage. When you register an event using the regular DOM api, the events will be part of the bubbling stage by default, but this can be specified upon event creation
// CAPTURING event
button.addEventListener('click', handleClick, true)
// BUBBLING events
button.addEventListener('click', handleClick, false)
button.addEventListener('click', handleClick)
In React, bubbling events are also what you use by default.
// handleClick is a BUBBLING (synthetic) event
<button onClick={handleClick}></button>
// handleClick is a CAPTURING (synthetic) event
<button onClickCapture={handleClick}></button>
function handleClick(e) {
// This will prevent any synthetic events from firing after this one
e.stopPropagation()
}
function handleClick(e) {
// This will set e.defaultPrevented to true
// (for all synthetic events firing after this one)
e.preventDefault()
}
If you call e.preventDefault() in all of your events, you can check if an event has already been handled, and prevent it from being handled again:
handleEvent(e) {
if (e.defaultPrevented) return // Exits here if event has been handled
e.preventDefault()
// Perform whatever you need to here.
}
For the difference between synthetic events and native events, see the React documentation: https://reactjs.org/docs/events.html
Building on dotancohen's answer I'm using an alias:
alias sudo="cygstart --action=runas"
Works as a charm:
sudo chown User:Group <file>
And if you have SysInternals installed you can even start a command shell as the system user very easily
sudo psexec -i -s -d cmd
The following query will find the documents with required string case insensitively and with global occurrence also
var name = 'Peter';
db.User.find({name:{
$regex: new RegExp(name, "ig")
}
},function(err, doc) {
//Your code here...
});
Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.
The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate)
for it to work. (Note you don't need to create a new Date object, it's a static method)
If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.
Everything about scope aside, they can be used differently.
console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1
Something something statement vs expression
Theres a few ways you can do this. You can either add a background to the canvas you are currently working on, which if the canvas isn't going to be redrawn every loop is fine. Otherwise you can make a second canvas underneath your main canvas and draw the background to it. The final way is to just use a standard <img>
element placed under the canvas. To draw a background onto the canvas element you can do something like the following:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
// Draw whatever else over top of it on the canvas.
I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h
. Very simple to use :
char* dechex (int dec);
This will use calloc()
to to return a pointer to an hexadecimal string, this way the quantity of memory used is optimized, so don't forget to use free()
Here the link on github : https://github.com/kevmuret/libhex/
Determine if property is existing (but is not a falsy value):
if (typeof query !== 'undefined' && query !== null){
doStuff();
}
Usually using
if (query){
doStuff();
}
is sufficient. Please note that:
if (!query){
doStuff();
}
doStuff() will execute even if query was an existing variable with falsy value (0, false, undefined or null)
Btw, there's a sexy coffeescript way of doing this:
if object?.property? then doStuff()
which compiles to:
if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null)
{
doStuff();
}
I also faced same problem & here is how I solved :-
I want to change package name np.com.shivakrstha.userlog to np.edu.khec.userlog
I selected shivakrstha and I pressed Shift + F6 for Rename Refract and renamed to khec.
Finally, use the same package name in AndroidManifest.xml, applicationId in build.gradle and don't forget to Rebuild Your Project.
Note:- I tried to change np to jp, so I selected np and I pressed Shift + F6 for Rename Refract and renamed to jp, it's ok to change others too.
You can use Distinct extension method from LINQ
If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"
The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:
HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))
Format..., select formatting, OK, OK.
where I have filled yellow the cells that are triggering the red fill result.
EF Core supports the views, here is the details.
This feature was added in EF Core 2.1 under the name of query types. In EF Core 3.0 the concept was renamed to keyless entity types. The [Keyless] Data Annotation became available in EFCore 5.0.
It is working not that much different than normal entities; but has some special points. According documentation:
- Cannot have a key defined.
- Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
- Are never discovered by convention.
- Only support a subset of navigation mapping capabilities, specifically:
- They may never act as the principal end of a relationship.
- They may not have navigations to owned entities
- They can only contain reference navigation properties pointing to regular entities.
- Entities cannot contain navigation properties to keyless entity types.
- Need to be configured with a [Keyless] data annotation or a .HasNoKey() method call.
- May be mapped to a defining query. A defining query is a query declared in the model that acts as a data source for a keyless entity type
It is working like below:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
}
If you don't have an existing View at database you should create like below:
db.Database.ExecuteSqlRaw(
@"CREATE VIEW View_BlogPostCounts AS
SELECT b.Name, Count(p.PostId) as PostCount
FROM Blogs b
JOIN Posts p on p.BlogId = b.BlogId
GROUP BY b.Name");
And than you should have a class to hold the result from the database view:
public class BlogPostsCount
{
public string BlogName { get; set; }
public int PostCount { get; set; }
}
And than configure the keyless entity type in OnModelCreating using the HasNoKey:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<BlogPostsCount>(eb =>
{
eb.HasNoKey();
eb.ToView("View_BlogPostCounts");
eb.Property(v => v.BlogName).HasColumnName("Name");
});
}
And just configure the DbContext to include the DbSet:
public DbSet<BlogPostsCount> BlogPostCounts { get; set; }
For anyone else who runs into this...
Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.
Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:
<div class="input-group" data-datepicker="true">
<input name="date" type="text" class="form-control" />
<span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>
It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).
$('*[data-datepicker="true"] input[type="text"]').datepicker({
todayBtn: true,
orientation: "top left",
autoclose: true,
todayHighlight: true
});
Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).
$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
$('input[type="text"]', $(this).parent()).focus();
});
NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.
Such as:
DROP TRIGGER IF EXISTS `update_tablename_trigger`;
DELIMITER //
CREATE TRIGGER `update_tablename_trigger` BEFORE UPDATE ON `tablename`
FOR EACH ROW SET NEW.`column_name` = NOW()
//
DELIMITER ;
Check this out on MSDN. It does not appear that you can do this with the implemented properties in the Socket class.
The poster on MSDN actually solved his problem using threading. He had a main thread which called out to other threads which run the connection code for a couple seconds and then check the Connected property of the socket:
I created another method wich actually connected the socket ... had the main thread sleep for 2 seconds and then check on the connecting method (wich is run in a separate thread) if the socket was connected good otherwise throw an exception "Timed out " and that;s all. Thanks again for the repleies.
What are you trying to do, and why can't it wait for 15-30 seconds before timing out?
My solution mayble not good
String url = "https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test";
int start = url.indexOf("v=")+2;
// int start = url.indexOf("list=")+5; **5 is length of ("list=")**
int end = url.indexOf("&", start);
end = (end == -1 ? url.length() : end);
System.out.println(url.substring(start, end));
// result: XcHJMiSy_1c
work fine with:
https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test
https://www.youtube.com/watch?v=XcHJMiSy_1c
With Yglu, you can write your example as:
paths:
root: /path/to/root/
patha: !? .paths.root + a
pathb: !? .paths.root + b
pathc: !? .paths.root + c
Disclaimer: I am the author of Yglu.
It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.
using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
try
{
bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed. What you see in the resulting record is just
<test></test>
Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string>
tag.
The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard. The five parameters to the Insert method map to fields in a SQL Server table.
Note your code contains Dir("thesentence")
which should be Dir(thesentence)
.
Change your code to this
Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)
Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).
I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
You have another process running on the same port.
You could try killing one of the java.exe services running in your task manager - ps make sure you dont kill eclipse since that is listed as java.exe as well. If nothing else works, restarting your machine will fix it anyhow. It looks like youre not shutting down a socket from a previous test. Hope this helps.
How about this?
$( document ).ready(function() {
$('#fixed').width($('#wrap').width());
});
By using jquery you can set any kind of width :)
EDIT: As stated by dream in the comments, using JQuery just for this effect is pointless and even counter productive. I made this example for people who use JQuery for other stuff on their pages and consider using it for this part also. I apologize for any inconvenience my answer caused.
Very good, clean and simple directive with shift + enter support:
app.directive('enterSubmit', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.bind('keydown', function(event) {
var code = event.keyCode || event.which;
if (code === 13) {
if (!event.shiftKey) {
event.preventDefault();
scope.$apply(attrs.enterSubmit);
}
}
});
}
}
});
The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking
For example :
$git rev-list --count --left-right "@{upstream}"...HEAD >4 12
will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:
>error: No upstream branch found for ''
origin
(your forked repo on github) and upstream
(the repo on github you forked from). Those are just interchangeable names, only the 'git@...' url identifies them.Your
.git/config
reads :[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = [email protected]:myusername/reponame.git [remote "upstream"] fetch = +refs/heads/*:refs/remotes/upstream/* url = [email protected]:authorname/reponame.git
it is 'the branch' (if any) on 'said remote', which is tracking the 'current branch' on your 'local repository'.
It's the branch you fetch/pull from whenever you issue a plain
git fetch
/git pull
, without arguments.
Let's say want to set the remote branch origin/master to be the tracking branch for the local master branch you've checked out. Just issue :
$ git branch --set-upstream master origin/master > Branch master set up to track remote branch master from origin.
This adds 2 parameters in
.git/config
:[branch "master"] remote = origin merge = refs/heads/master
now try (provided 'upstream' remote has a 'dev' branch)
$ git branch --set-upstream master upstream/dev > Branch master set up to track remote branch dev from upstream.
.git/config
now reads:[branch "master"] remote = upstream merge = refs/heads/dev
-u --set-upstream
For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull(1) and other commands. For more information, see
branch.<name>.merge
in git-config(1).branch.<name>.merge
Defines, together with
branch.<name>.remote
, the upstream branch for the given branch. It tells git fetch/git pull/git rebase which branch to merge and can also affect git push (see push.default). \ (...)branch.<name>.remote
When in branch < name >, it tells git fetch and git push which remote to fetch from/push to. It defaults to origin if no remote is configured. origin is also used if you are not on any branch.
take a look at git-config(1)
Manual Page
git config --global push.default upstream git config --global push.default tracking (deprecated)
This is to prevent accidental pushes to branches which you’re not ready to push yet.
On a Mac
Delete these using the terminal (usage: rm -rf folderpath):
~/Library/Preferences/AndroidStudioBeta
~/Library/Application Support/AndroidStudioBeta
~/Library/Caches/AndroidStudioBeta
~/Library/Logs/AndroidStudioBeta
As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub
. The simplest way is to change location
to str(location)
when using re.sub
. It wouldn't hurt to do it anyways even if it's already a str
.
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
" ", # Replace all non-letters with spaces
str(location))
$('#txtConfirmPassword').keyup(function(){
if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))
{
alert('confirm password not match');
}
});
My understanding is that those two examples are effectively equivalent. The only difference is that in the first, you can reuse the compiled regular expression elsewhere without causing it to be compiled again.
Here's a reference for you: http://diveintopython3.ep.io/refactoring.html
Calling the compiled pattern object's search function with the string 'M' accomplishes the same thing as calling re.search with both the regular expression and the string 'M'. Only much, much faster. (In fact, the re.search function simply compiles the regular expression and calls the resulting pattern object's search method for you.)
In addition to Roman's answer, something like this might be even simpler. Note that I haven't tested it because I do not have access to R right now.
# Note that I use a global variable here
# normally not advisable, but I liked the
# use here to make the code shorter
index <<- 0
new_column = sapply(df$h_no, function(x) {
if(x == 1) index = index + 1
return(index)
})
The function iterates over the values in n_ho
and always returns the categorie that the current value belongs to. If a value of 1
is detected, we increase the global variable index
and continue.
Simply use str_replace:
$text = str_replace(' ', '_', $text);
You would do this after your previous substr
and strtolower
calls, like so:
$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);
If you want to get fancy, though, you can do it in one line:
$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));
sleep
is a method of Thread
, wait
is a method of Object
, so wait/notify
is a technique of synchronizing shared data in Java (using monitor), but sleep
is a simple method of thread to pause itself.
Keep in mind that you don't want to zoom in/out UIImage. Instead try to zoom in/out the View which contains the UIImage View Controller.
I have made a solution for this problem. Take a look at my code:
@IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
self.view.transform = CGAffineTransformScale(self.view.transform, sender.scale, sender.scale)
sender.scale = 1
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.blackColor()
}
N.B.: Don't forget to hook up the PinchGestureRecognizer.
For others who may come by here, maybe take a look at : http://openhardwaremonitor.org/
Follow that link and at first you might think, "hey that's an Application, that is why it was removed, the question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is.
They also include a Data Interface, here is the description:
Data Interface The Open Hardware Monitor publishes all sensor data to WMI (Windows Management Instrumentation). This allows other applications to read and use the sensor information as well. A preliminary documentation of the interface can be found here(click).
When you download it, it contains the OpenHardwareMonitor.exe application, you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, you're looking for that one.
It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap your self if you feel like it.
I have tried this out from a C# app myself, and it works. Although it is still in beta, it seemed rather stable. It is also open source so it could be a good starting point instead.
At the end of the day I find it hard to believe that is not on topic of this question.
Go to the Declaration of the desired object and mark it Shared.
Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX
Answering this because I trapped myself with it by now knowing this and maybe it will be useful.
Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array)
, and output results with foreach
.
For example:
$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);
if (count($rows) > 0) {
foreach ($rows as $row) {
//output your rows
}
}
You want to join on condition 1 AND condition 2, so simply use the AND keyword as below
ON a.userid = b.sourceid AND a.listid = b.destinationid;
$('#test').click(function() {_x000D_
var todayDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("08.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + todayDate.diff(endDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
Many solutions presented here result in some weird behaviour that doesn't feel like properly implemented paging.
The solution presented in this tutorial, however, doesn't seem to have any issues. It just feels like a perfectly working paging algorithm. You can implement it in 5 simple steps:
private var indexOfCellBeforeDragging = 0
collectionView
delegate
like this: collectionView.delegate = self
UICollectionViewDelegate
via an extension: extension YourType: UICollectionViewDelegate { }
Add the following method to the extension implementing the UICollectionViewDelegate
conformance and set a value for pageWidth
:
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
let pageWidth = // The width your page should have (plus a possible margin)
let proportionalOffset = collectionView.contentOffset.x / pageWidth
indexOfCellBeforeDragging = Int(round(proportionalOffset))
}
Add the following method to the extension implementing the UICollectionViewDelegate
conformance, set the same value for pageWidth
(you may also store this value at a central place) and set a value for collectionViewItemCount
:
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// Stop scrolling
targetContentOffset.pointee = scrollView.contentOffset
// Calculate conditions
let pageWidth = // The width your page should have (plus a possible margin)
let collectionViewItemCount = // The number of items in this section
let proportionalOffset = collectionView.contentOffset.x / pageWidth
let indexOfMajorCell = Int(round(proportionalOffset))
let swipeVelocityThreshold: CGFloat = 0.5
let hasEnoughVelocityToSlideToTheNextCell = indexOfCellBeforeDragging + 1 < collectionViewItemCount && velocity.x > swipeVelocityThreshold
let hasEnoughVelocityToSlideToThePreviousCell = indexOfCellBeforeDragging - 1 >= 0 && velocity.x < -swipeVelocityThreshold
let majorCellIsTheCellBeforeDragging = indexOfMajorCell == indexOfCellBeforeDragging
let didUseSwipeToSkipCell = majorCellIsTheCellBeforeDragging && (hasEnoughVelocityToSlideToTheNextCell || hasEnoughVelocityToSlideToThePreviousCell)
if didUseSwipeToSkipCell {
// Animate so that swipe is just continued
let snapToIndex = indexOfCellBeforeDragging + (hasEnoughVelocityToSlideToTheNextCell ? 1 : -1)
let toValue = pageWidth * CGFloat(snapToIndex)
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: velocity.x,
options: .allowUserInteraction,
animations: {
scrollView.contentOffset = CGPoint(x: toValue, y: 0)
scrollView.layoutIfNeeded()
},
completion: nil
)
} else {
// Pop back (against velocity)
let indexPath = IndexPath(row: indexOfMajorCell, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}
}
For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.
Next open Configuration Properties and then Linker.
Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,
Linker -> Input you'll add the actual library files under Additional Dependencies.
For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.
If there is a dll have a copy of it in your main project folder, and done.
I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.
Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.
This was written for Visual Studio 2008. For 2010 it should be roughly the same.
The problem is that you're displaying time()
, which is a UNIX timestamp based on GMT/UTC. That’s why it doesn’t change. date()
on the other hand, formats the time based on that timestamp.
A timestamp is the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
You can also use nuget: https://www.nuget.org/packages/System.Management.Automation/ It is maybe a better option.
For readability:
using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
for higher precision. this format:
45 11.735N,004 34.281E
and this
45 23.623, 5 38.77
You can also use sequence unpacking with zip
:
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
_, res = zip(*L)
print(res)
# (2, 3, 5, 4, 7, 7, 8)
This also creates a tuple _
from the discarded first elements. Extracting only the second is possible, but more verbose:
from itertools import islice
res = next(islice(zip(*L), 1, None))
I had the same issue, I cleaned and rebuilt the project and it worked.
Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:
<script>
$(document).ready(function() {
$('img.thumbnail').click(function() {
window.location.href = this.id + '.html';
});
});
</script>
Basically, it attaches an onClick
event to all images with class thumbnail
to redirect to the corresponding HTML page (id
+ .html
). Then you only need the images in your HTML (without the a
elements), like this:
<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />
If another module calls yours and you'd still like to know the location of the main file being run you can use a modification of @Jason's code:
var path = require('path'),
__parentDir = path.dirname(process.mainModule.filename);
fs.readFile(__parentDir + '/foo.bar');
That way you'll get the location of the script actually being run.
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
2) Run following commands
For all listening ports
Apply port filter
Finally with the PID we can run the following command to kill the process
3) Copy PID from result set
Ex: taskkill /F /PID 189
Done !!! you can start your service now.
Use break
and continue
to do this. Breaking nested loops can be done in Python using the following:
for a in range(...):
for b in range(..):
if some condition:
# break the inner loop
break
else:
# will be called if the previous loop did not end with a `break`
continue
# but here we end up right after breaking the inner loop, so we can
# simply break the outer loop as well
break
Another way is to wrap everything in a function and use return
to escape from the loop.
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
This is because you have made conflicting changes to its master. And your repository server is not able to tell you that with these words, so it gives this error because it is not a matter of him deal with these conflicts for you, so he asks you to do it by itself. As ?
1- git pull
This will merge your code from your repository to your code of your site master.
So conflicts are shown.
2- treat these manualemente conflicts.
3-
git push origin master
And presto, your problem has been resolved.
You got to add python to your PATH variable. One thing you can do is Edit your Path variable now and add
;%PYTHON%;
Your variable PYTHON should point to the root directory of your python installation.
Sending a docker image to a remote server can be done in 3 simple steps:
docker save -o <path for created tar file> <image name>
Locally, use scp to transfer .tar to remote
On remote server, load image into docker:
docker load -i <path to docker image tar file>
As of IE11, you need to use addEventListener
. attachEvent
is deprecated and throws an error.
You can use .filter() or .find(). One difference that filter
will iterate over all items and returns any which passes the condition as array while find
will return the first matched item and break the iteration.
Example
var questions = [_x000D_
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},_x000D_
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},_x000D_
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},_x000D_
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},_x000D_
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},_x000D_
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},_x000D_
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},_x000D_
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},_x000D_
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},_x000D_
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},_x000D_
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},_x000D_
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},_x000D_
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},_x000D_
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},_x000D_
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}_x000D_
];_x000D_
_x000D_
function getDimensionsByFilter(id){_x000D_
return questions.filter(x => x.id === id);_x000D_
}_x000D_
_x000D_
function getDimensionsByFind(id){_x000D_
return questions.find(x => x.id === id);_x000D_
}_x000D_
_x000D_
var test = getDimensionsByFilter(10);_x000D_
console.log(test);_x000D_
_x000D_
test = getDimensionsByFind(10);_x000D_
console.log(test);
_x000D_
I like the answer from @TrampGuy
CSS is always (well, not always) a better choice, so: text-transform: capitalize;
is certainly the way to go.
But what if your content is all uppercase to begin with? If you try text-transform: capitalize;
on content like "FOO BAR" you'll still get "FOO BAR" in your display. To get around that issue you could put the text-transform: capitalize;
in your css, but also lowercase your string, so:
<ul>
<li class="capitalize">{{ foo.awesome_property | lowercase }}</li>
</ul>
where we are using @TrampGuy's capitalize class:
.capitalize {
text-transform: capitalize;
}
So, pretending that foo.awsome_property
would normally print "FOO BAR", it will now print the desired "Foo Bar".
File size by MySQL type:
There is a UDF that will do that described here:
User Defined Function to Strip HTML
CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
WHILE @Start > 0 AND @End > 0 AND @Length > 0
BEGIN
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@HTMLText))
END
GO
Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.
As of CMake Wiki:
CMAKE_BINARY_DIR if you are building in-source, this is the same as CMAKE_SOURCE_DIR, otherwise this is the top level directory of your build tree
Compare these two variables to determine if out-of-source build was started
you can use more elements "end" in print:
for iValue in arr:
print(iValue, end = ", ");
It has been said in one of the direct comments to your answer already, but just to state it officially. What you want to use is an overload:
virtual const ULONG Write(ULONG &State, bool sequence);
inline const ULONG Write()
{
ULONG state;
bool sequence = true;
Write (state, sequence);
}
Using function overloads also have additional benefits. Firstly you can default any argument you wish:
class A {};
class B {};
class C {};
void foo (A const &, B const &, C const &);
void foo (B const &, C const &); // A defaulted
void foo (A const &, C const &); // B defaulted
void foo (C const &); // A & B defaulted etc...
It is also possible to redefine default arguments to virtual functions in derived class, which overloading avoids:
class Base {
public:
virtual void f1 (int i = 0); // default '0'
virtual void f2 (int);
inline void f2 () {
f2(0); // equivalent to default of '0'
}
};
class Derived : public Base{
public:
virtual void f1 (int i = 10); // default '10'
using Base::f2;
virtual void f2 (int);
};
void bar ()
{
Derived d;
Base & b (d);
d.f1 (); // '10' used
b.f1 (); // '0' used
d.f2 (); // f1(int) called with '0'
b.f2 (); // f1(int) called with '0
}
There is only one situation where a default really needs to be used, and that is on a constructor. It is not possible to call one constructor from another, and so this technique does not work in that case.
Change the field back to numeric and use ZEROFILL
to keep the zeros
or
use LPAD()
SELECT LPAD('1234567', 8, '0');
Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.
You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.
angular.element('*[ng-app]').injector()
In chrome, however, you can point to target ng-app as shown below. and use the $0
hack and issue angular.element($0).injector()
Once you have the injector, get any dependency injected service as below
injector = angular.element($0).injector();
injector.get('$mdToast');
Based on Daniel Krizian's comment, you can also use the pretty_breaks
function from the scales
library, which is imported automatically:
ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10))
All you have to do is insert the number of ticks wanted for n
.
A slightly less useful solution (since you have to specify the data variable again), you can use the built-in pretty
function:
ggplot(dat, aes(x,y)) + geom_point() +
scale_x_continuous(breaks = pretty(dat$x, n = 10)) +
scale_y_continuous(breaks = pretty(dat$y, n = 10))
Here is an example - accepting no parameters and returning nothing.
class CallbackTest
{
public myCallback: {(): void;};
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();
If you want to accept a parameter, you can add that too:
public myCallback: {(msg: string): void;};
And if you want to return a value, you can add that also:
public myCallback: {(msg: string): number;};
or use this header library and write:
// |notEqaul|less|lessEqual|greater|greaterEqual
if(sweet::equal(valueA,valueB))
and don't care about signed/unsigned or different sizes
$("**:**input[type=text], :input[type='textarea']").css({width: '90%'});
For Simple Direct Media Layer 2 (SDL2), after installing it on Ubuntu 16.04 via:
sudo apt-get install libsdl2-dev
I used the header:
#include <SDL2/SDL.h>
and the compiler linker command:
-lSDL2main -lSDL2
Additionally, you may also want to install:
apt-get install libsdl2-image-dev
apt-get install libsdl2-mixer-dev
apt-get install libsdl2-ttf-dev
With these headers:
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
and the compiler linker commands:
-lSDL2_image
-lSDL2_ttf
-lSDL2_mixer
Yes you can do that by just creating a BroadcastReceiver
that calls your Service
when your Application boots. Here is a complete answer given by me.
Android - Start service on boot
If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Just declare your Service
as declared normally.
Another option as of 2017 is to use Date.parse()
. MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
You want to include <string>
and use std::string
:
#include <string>
#include <iostream>
int main()
{
std::string s = "a string";
std::cout << s << std::endl;
}
But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for information online.
You would use an MvcHtmlString
if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.
One obvious advantage of artificial neural networks over support vector machines is that artificial neural networks may have any number of outputs, while support vector machines have only one. The most direct way to create an n-ary classifier with support vector machines is to create n support vector machines and train each of them one by one. On the other hand, an n-ary classifier with neural networks can be trained in one go. Additionally, the neural network will make more sense because it is one whole, whereas the support vector machines are isolated systems. This is especially useful if the outputs are inter-related.
For example, if the goal was to classify hand-written digits, ten support vector machines would do. Each support vector machine would recognize exactly one digit, and fail to recognize all others. Since each handwritten digit cannot be meant to hold more information than just its class, it makes no sense to try to solve this with an artificial neural network.
However, suppose the goal was to model a person's hormone balance (for several hormones) as a function of easily measured physiological factors such as time since last meal, heart rate, etc ... Since these factors are all inter-related, artificial neural network regression makes more sense than support vector machine regression.
using System.Reflection;
string myExeDir = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.ToString();
If the table is compressed this will work:
alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);
update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;
update EVAPP_FEES set AMOUNT = null;
alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);
update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;
alter table EVAPP_FEES move nocompress;
alter table EVAPP_FEES drop column AMOUNT_TEMP;
alter table EVAPP_FEES compress;
protocol//[hosts][/database][?properties]
If you don't have any properties ignore it then it will be like
jdbc:mysql://127.0.0.1:3306/test
jdbc:mysql is the protocol 127.0.0.1: is the host and 3306 is the port number test is the database
For the issue of getting a NullPointerException
when we change the Tabs in a FragmentTabHost
you just need to add this code to your class which has the TabHost
. I mean the class where you initialize the tabs. This is the code :
/**** Fix for error : Activity has been destroyed, when using Nested tabs
* We are actually detaching this tab fragment from the `ChildFragmentManager`
* so that when this inner tab is viewed back then the fragment is attached again****/
import java.lang.reflect.Field;
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
echo $a | grep -bo cat | sed 's/:.*$//'
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies
Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.
http://www.bettersolutions.com/excel/EED883/YI416010881.htm
Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales
This should fix your problem.
>>> test = [1,23,4,6,7,8]
>>> from itertools import izip_longest
>>> for e in izip_longest(test, reversed(test)):
print e
(1, 8)
(23, 7)
(4, 6)
(6, 4)
(7, 23)
(8, 1)
Another option
>>> test = [1,23,4,6,7,8]
>>> start, end = iter(test), reversed(test)
>>> try:
while True:
print map(next, [start, end])
except StopIteration:
pass
[1, 8]
[23, 7]
[4, 6]
[6, 4]
[7, 23]
[8, 1]
You can use the SqlDependency Class
. Its intended use is mostly for ASP.NET pages (low number of client notifications).
ALTER DATABASE UrDb SET ENABLE_BROKER
Implement the OnChange
event to get notified:
void OnChange(object sender, SqlNotificationEventArgs e)
And in code:
SqlCommand cmd = ...
cmd.Notification = null;
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += OnChange;
It uses the Service Broker
(a message-based communication platform) to receive messages from the database engine.
Have your tried json-io (https://github.com/jdereg/json-io)?
This library allows you to serialize / deserialize any Java object graph, including object graphs with cycles in them (e.g., A->B, B->A). It does not require your classes to implement any particular interface or inherit from any particular Java class.
In addition to serialization of Java to JSON (and JSON to Java), you can use it to format (pretty print) JSON:
String niceFormattedJson = JsonWriter.formatJson(jsonString)
Use a packet sniffer like Wireshark to look at what happens. You need to see a SYN-flagged packet outgoing, a SYN+ACK-flagged incoming and then a ACK-flagged outgoing. After that, the port is considered open on the local side.
If you only see the first packet and the error message comes after several seconds of waiting, the other side is not answering at all (like in: unplugged cable, overloaded server, misguided packet was discarded) and your local network stack aborts the connection attempt. If you see RST packets, the host actually denies the connection. If you see "ICMP Port unreachable" or host unreachable packets, a firewall or the target host inform you of the port actually being closed.
Of course you cannot expect the service to be available at all times (consider all the points of failure in between you and the data), so you should try again later.
For creating real UML class diagrams:
In Visual Studio 2013 Ultimate you can do this without any external tools.
You will have a empty UMLClassDiagram.classdiagram.
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.AccountManagement;
class WindowsCred
{
private const string SPLIT_1 = "\\";
public static bool ValidateW(string UserName, string Password)
{
bool valid = false;
string Domain = "";
if (UserName.IndexOf("\\") != -1)
{
string[] arrT = UserName.Split(SPLIT_1[0]);
Domain = arrT[0];
UserName = arrT[1];
}
if (Domain.Length == 0)
{
Domain = System.Environment.MachineName;
}
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain))
{
valid = context.ValidateCredentials(UserName, Password);
}
return valid;
}
}
Kashif Mushtaq Ottawa, Canada
You can't directly edit your path to execute of a service. For that you can use sc command,
SC CONFIG ServiceName binPath= "Path of your file"
Eg:
sc config MongoDB binPath="I:\Programming\MongoDB\MongoDB\bin\mongod.exe --config I:\Programming\MongoDB\MongoDB\bin\mongod.cfg --service"
One place where I use @import is when I'm doing two versions of a page, English and French. I'll build out my page in English, using a main.css. When I build out the French version, I'll link to a French stylesheet (main_fr.css). At the top of the French stylesheet, I'll import the main.css, and then redefine specific rules for just the parts I need different in the French version.
The best and easy way to pass single or multiple variables to view from controller is to use compact() method.
For passing single variable to view,
return view("user/regprofile",compact('students'));
For passing multiple variable to view,
return view("user/regprofile",compact('students','teachers','others'));
And in view, you can easily loop through the variable,
@foreach($students as $student)
{{$student}}
@endforeach
I do not like java type names in query strings and handle it with a specific constructor. Spring JPA implicitly calls constructor with query result in HashMap parameter:
@Getter
public class SurveyAnswerStatistics {
public static final String PROP_ANSWER = "answer";
public static final String PROP_CNT = "cnt";
private String answer;
private Long cnt;
public SurveyAnswerStatistics(HashMap<String, Object> values) {
this.answer = (String) values.get(PROP_ANSWER);
this.count = (Long) values.get(PROP_CNT);
}
}
@Query("SELECT v.answer as "+PROP_ANSWER+", count(v) as "+PROP_CNT+" FROM Survey v GROUP BY v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
Code needs Lombok for resolving @Getter
Mac version. From terminal run:
open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files
Execute chmod 777 -R scripts/
, it worked fine for me ;)
Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve
How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).
The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:
EXPORTS main=_main
Borland compilers add an underscore to function names, and this exports the main()
function the way a VST host expects it. For more information about .def files, see the C++Builder help files.
This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:
In the constructor of your effect class, write
_control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
That should do the trick.
Here are some more useful sites:
http://www.steinberg.net/en/company/developer.html
how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.
Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)
More about fr units here.
.container{
width: 100vw;
height:100vh;
display: grid;
grid-template-columns: 1fr 3fr;
}
/*You don't need this*/
.div1{
background-color: yellow;
}
.div2{
background-color: red;
}
_x000D_
<div class='container'>
<div class='div1'>This is div 1</div>
<div class='div2'>This is div 2</div>
</div>
_x000D_
Assuming you really want an array of single-character strings (not a char[]
or Character[]
)
1. Using a regex:
public static String[] singleChars(String s) {
return s.split("(?!^)");
}
The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.
2. Using Guava:
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
// ...
public static String[] singleChars(String s) {
return
Lists.transform(Chars.asList(s.toCharArray()),
Functions.toStringFunction())
.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
int value = 3;
var array = Convert.ToString(value, 2).PadLeft(8, '0').ToArray();
Make sure you enter the full package name with application name:
com.domain.app
I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.
Here's the syntax and an abbreviated sample twitter document below.
This site was useful for testing:
The jsonpath filter expression:
.events[0].attributes[?(@.name=='screen_name')].value
Test document:
{
"title" : "test twitter",
"priority" : 5,
"events" : [ {
"eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
"eventDate" : "2015-03-27T09:07:48-0500",
"publisher" : "twitter",
"type" : "tweet",
"attributes" : [ {
"name" : "filter_level",
"value" : "low"
}, {
"name" : "screen_name",
"value" : "_ziadin"
}, {
"name" : "followers_count",
"value" : "406"
} ]
} ]
}
Try doing this:
adb kill-server && adb start-server
(that restarts adb) Also you can try to edit an adb config file .android/adb_usb.ini
and add a line 04e8
after the header. Restart adb required for changes to take effect.
https://cdn.rawgit.com is shutting down. Thus, one of the alternate options can be used. JSDeliver is a free cdn that can be used.
// load any GitHub release, commit, or branch
// note: we recommend using npm for projects that support it
https://cdn.jsdelivr.net/gh/user/repo@version/file
// load jQuery v3.2.1
https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js
// use a version range instead of a specific version
https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js
https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js
// omit the version completely to get the latest one
// you should NOT use this in production
https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js
// add ".min" to any JS/CSS file to get a minified version
// if one doesn't exist, we'll generate it for you
https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js
// add / at the end to get a directory listing
You can resize images using CSS just fine if you're modifying an image tag:
<img src="example.png" style="width:2em; height:3em;" />
You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size
.
What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background
You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI
as your collation. The one you specify in your question is explictly case sensitive.
You can see a list of collations here.
Yes, it is called Short-circuit Evaluation.
If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.
This is very important when some of the statements have side-effects.
Just:
$('#edit-submitted-first-name').removeAttr('required');?????
If you're interested in further reading take a look here.
ActiveXObject
is non-standard and only supported by Internet Explorer on Windows.
There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.
If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).
Don’t overthink what a Namespace is.
Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.
Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.
E.g:
// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;
if ($_SERVER['APP_DEBUG']) {
// So you can utilize the Debug class it in an elegant way
Debug::enable();
// Instead of this ugly one
// \Symfony\Component\Debug\Debug::enable();
}
If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:
fun1("who is who", 3, "jack")
What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
I do this:
var preloaderdiv = '<div class="thumbs_preloader">Loading...</div>';
$('#detail_thumbnails').html(preloaderdiv);
$.ajax({
async:true,
url:'./Ajaxification/getRandomUser?top='+ $(sender).css('top') +'&lef='+ $(sender).css('left'),
success:function(data){
$('#detail_thumbnails').html(data);
}
});
A simple way of doing this is via nargin
(N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.
It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b
and c
. Will exit if a
is not present.
function [ output_args ] = input_example( a, b, c )
if nargin < 1
error('input_example : a is a required input')
end
if nargin < 2
b = 20
end
if nargin < 3
c = 30
end
end
It sounds like you've got it the wrong way round. If your existing data is in MM/DD/YYYY format, then you want:
select to_date(date_column,'MM/DD/YYYY') from table;
to convert the existing data to DATE values. (I do wonder why they're not stored as dates, to be honest...)
If you want to perform the conversion in one step, you might want:
select to_char(to_date(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD') from table;
In other words, for each row, parse it in MM/DD/YYYY format, then reformat it to YYYY-MM-DD format.
(I'd still suggest trying to keep data in its "natural" type though, rather than storing it as text in the first place.)
Sol-1:
select
StartTime
, EndTime
, CONVERT(NVARCHAR,(EndTime-StartTime), 108) as TimeDiff
from
[YourTable]
Sol-2:
select
StartTime
, EndTime
, DATEDIFF(hh, StartTime, EndTime)
, DATEDIFF(mi, StartTime, EndTime) % 60
from
[YourTable]
Sol-3:
select
DATEPART(hour,[EndTime]-[StartTime])
, DATEPART(minute,[EndTime]-[StartTime])
from
[YourTable]
Datepart works the best
If you want to scroll with a smooth transition, you could use this!
(Vanilla JS)
const tabScroll = document.getElementById("tabScroll");
window.scrollTo({
'behavior': 'smooth',
'left': 0,
'top': tabScroll.offsetTop - 80
});
If your target users are Chrome and Firefox, then this is good! But unfortunately this method isn’t supported well enough on all browsers. Check Here
Hope this helps!!
I was able to resolve the issue by opening the script in Gedit and saving it with the proper Line Ending
option:
File > Save As...
In the bottom left of the Save As
prompt, there are drop-down menus for Character Encoding and Line Ending. Change the Line Ending from Windows
to Unix/Linux
then Save.
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();
Spring MVC and Spring Boot are exist for the different purpose. So, it is not wise to compare each other as the contenders.
What is Spring Boot?
Spring Boot is a framework for packaging the spring application with sensible defaults. What does this mean?. You are developing a web application using Spring MVC, Spring Data, Hibernate and Tomcat. How do you package and deploy this application to your web server. As of now, we have to manually write the configurations, XML files, etc. for deploying to web server.
Spring Boot does that for you with Zero XML configuration in your project. Believe me, you don't need deployment descriptor, web server, etc. Spring Boot is magical framework that bundles all the dependencies for you. Finally your web application will be a standalone JAR file with embeded servers.
If you are still confused how this works, please read about microservice framework development using spring boot.
What is Spring MVC?
It is a traditional web application framework that helps you to build web applications. It is similar to Struts framework.
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control, Dependency Injection.
A Spring MVC provides an elegant solution to use MVC in spring framework by the help of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request and maps it to the right resource such as controllers, models, and views.
I hope this helps you to understand the difference.
Based on everything else here, handles numerical indices + attributes via prefixing with @
, and could inject xml to existing nodes:
function simple_xmlify($arr, SimpleXMLElement $root = null, $el = 'x') {
// based on, among others http://stackoverflow.com/a/1397164/1037948
if(!isset($root) || null == $root) $root = new SimpleXMLElement('<' . $el . '/>');
if(is_array($arr)) {
foreach($arr as $k => $v) {
// special: attributes
if(is_string($k) && $k[0] == '@') $root->addAttribute(substr($k, 1),$v);
// normal: append
else simple_xmlify($v, $root->addChild(
// fix 'invalid xml name' by prefixing numeric keys
is_numeric($k) ? 'n' . $k : $k)
);
}
} else {
$root[0] = $arr;
}
return $root;
}//-- fn simple_xmlify
// lazy declaration via "queryparam"
$args = 'hello=4&var[]=first&var[]=second&foo=1234&var[5]=fifth&var[sub][]=sub1&var[sub][]=sub2&var[sub][]=sub3&var[@name]=the-name&var[@attr2]=something-else&var[sub][@x]=4.356&var[sub][@y]=-9.2252';
$q = array();
parse_str($val, $q);
$xml = simple_xmlify($q); // dump $xml, or...
$result = get_formatted_xml($xml); // see below
<?xml version="1.0"?>
<x>
<hello>4</hello>
<var name="the-name" attr2="something-else">
<n0>first</n0>
<n1>second</n1>
<n5>fifth</n5>
<sub x="4.356" y="-9.2252">
<n0>sub1</n0>
<n1>sub2</n1>
<n2>sub3</n2>
</sub>
</var>
<foo>1234</foo>
</x>
function get_formatted_xml(SimpleXMLElement $xml, $domver = null, $preserveWhitespace = true, $formatOutput = true) {
// http://stackoverflow.com/questions/1191167/format-output-of-simplexml-asxml
// create new wrapper, so we can get formatting options
$dom = new DOMDocument($domver);
$dom->preserveWhiteSpace = $preserveWhitespace;
$dom->formatOutput = $formatOutput;
// now import the xml (converted to dom format)
/*
$ix = dom_import_simplexml($xml);
$ix = $dom->importNode($ix, true);
$dom->appendChild($ix);
*/
$dom->loadXML($xml->asXML());
// print
return $dom->saveXML();
}//-- fn get_formatted_xml
To show NumberPicker
in AlertDialog
use this code :
final AlertDialog.Builder d = new AlertDialog.Builder(context);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.number_picker_dialog, null);
d.setTitle("Title");
d.setMessage("Message");
d.setView(dialogView);
final NumberPicker numberPicker = (NumberPicker) dialogView.findViewById(R.id.dialog_number_picker);
numberPicker.setMaxValue(50);
numberPicker.setMinValue(1);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
Log.d(TAG, "onValueChange: ");
}
});
d.setPositiveButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d(TAG, "onClick: " + numberPicker.getValue());
}
});
d.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = d.create();
alertDialog.show();
number_picker_dialog.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_horizontal">
<NumberPicker
android:id="@+id/dialog_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup
I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.
So you can open a new http-page with window.open(...)
and have that making the request for you (that is if the site is using CORS as well)
XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser
You put this proxy script on any http page
onmessage = evt => {
const port = evt.ports[0]
fetch(...evt.data).then(res => {
// the response is not clonable
// so we make a new plain object
const obj = {
bodyUsed: false,
headers: [...res.headers],
ok: res.ok,
redirected: res.redurected,
status: res.status,
statusText: res.statusText,
type: res.type,
url: res.url
}
port.postMessage(obj)
// Pipe the request to the port (MessageChannel)
const reader = res.body.getReader()
const pump = () => reader.read()
.then(({value, done}) => done
? port.postMessage(done)
: (port.postMessage(value), pump())
)
// start the pipe
pump()
})
}
Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)
window.popup = window.open(http://.../proxy.html)
create your utility function
function xfetch(...args) {
// tell the proxy to make the request
const ms = new MessageChannel
popup.postMessage(args, '*', [ms.port1])
// Resolves when the headers comes
return new Promise((rs, rj) => {
// First message will resolve the Response Object
ms.port2.onmessage = ({data}) => {
const stream = new ReadableStream({
start(controller) {
// Change the onmessage to pipe the remaning request
ms.port2.onmessage = evt => {
if (evt.data === true) // Done?
controller.close()
else // enqueue the buffer to the stream
controller.enqueue(evt.data)
}
}
})
// Construct a new response with the
// response headers and a stream
rs(new Response(stream, data))
}
})
}
And make the request like you normally do with the fetch api
xfetch('http://httpbin.org/get')
.then(res => res.text())
.then(console.log)
If table cols and values are variables then there are two ways:
With double quotes ""
the complete query:
$query = "INSERT INTO $table_name (id, $col1, $col2)
VALUES (NULL, '$val1', '$val2')";
Or
$query = "INSERT INTO ".$table_name." (id, ".$col1.", ".$col2.")
VALUES (NULL, '".$val1."', '".$val2."')";
With single quotes ''
:
$query = 'INSERT INTO '.$table_name.' (id, '.$col1.', '.$col2.')
VALUES (NULL, '.$val1.', '.$val2.')';
Use back ticks ``
when a column/value name is similar to a MySQL reserved keyword.
Note: If you are denoting a column name with a table name then use back ticks like this:
`table_name`
. `column_name`
<-- Note: exclude .
from back ticks.
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
You can use the onchange event:
<form name="myform" id="myform" action="action.php">
<input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
<input type="text" name="message" value="" />
<input type="submit" name="submit" onclick="DoSubmit()" />
</form>
Questions : how to check File is empty or not?
Ans: I have slove this issue using this Jquery code
//If your file Is Empty : _x000D_
if (jQuery('#videoUploadFile').val() == '') {_x000D_
$('#message').html("Please Attach File");_x000D_
}else {_x000D_
alert('not work');_x000D_
}_x000D_
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="videoUploadFile">_x000D_
<br>_x000D_
<br>_x000D_
<div id="message"></div>
_x000D_
Like others said, the simpliest solution is just call draggable()
function from jQuery UI just after showing modal:
$('#my-modal').modal('show')
.draggable({ handle: ".modal-header" });
But there is a several problems with compatibility between Bootstrap and jQuery UI so we need some addition fixes in css:
.modal
{
overflow: hidden;
}
.modal-dialog{
margin-right: 0;
margin-left: 0;
}
.modal-header{ /* not necessary but imo important for user */
cursor: move;
}
I assume you use Graphics.CopyFromScreen
to get the screenshot.
You can use P/Invoke to GetForegroundWindow (and then get its position and size) to determine which region you need to copy from.
Well, I can think of a CSS hack that will resolve this issue.
You could add the following line in your CSS file:
* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; }
The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.
I had massive problems with getting any of those scripts to work with sending mail in powershell. Turned out you need to create an app-password for your gmail-account to authenticate in the script. Now it works flawlessly!
window.open('http://www.kidzout.com', '_system');
Will work but only if you have the inappbrowser plugin installed. To install, using terminal, browse to the www folder in your project and type:
phonegap plugin add org.apache.cordova.inappbrowser
or
cordova plugin add org.apache.cordova.inappbrowser
Then it your link will open in the browser.
The selected answer using tableView :viewForHeaderInSection:
is correct.
Just to share a tip here.
If you are using storyboard/xib, then you could create another prototype cell and use it for your "section cell". The code to configure the header is similar to how you configure for row cells.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
static NSString *HeaderCellIdentifier = @"Header";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier];
}
// Configure the cell title etc
[self configureHeaderCell:cell inSection:section];
return cell;
}
You can use the .tostring() method with datetime format specifiers to format to whatever you need:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013
Similar to an earlier answer, this will handle positive and negative integer powers of a double nicely.
double intpow(double a, int b)
{
double r = 1.0;
if (b < 0)
{
a = 1.0 / a;
b = -b;
}
while (b)
{
if (b & 1)
r *= a;
a *= a;
b >>= 1;
}
return r;
}
SendKeys is straight, but you may dislike it (e.g. it opens the Immediate window if it was closed, and moves the focus).
The WinAPI + VBE way is really elaborate, but you may wish not to grant VBA access to VBE (might even be your company group policy not to).
Instead of clearing you can flush its content (or part of it...) away with blanks:
Debug.Print String(65535, vbCr)
Unfortunately, this only works if the caret position is at the end of the Immediate window (string is inserted, not appended). If you only post content via Debug.Print and don't use the window interactively, this will do the job. If you actively use the window and occasionally navigate to within the content, this does not help a lot.
This worked for me
In JSP, to view the image
<img src="${pageContext.request.contextPath}/resources/images/slide-are.jpg">
In dispatcher-servlet.xml
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
First a link to some documentation of fork()
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.
So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.
If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().
pid_t pid = fork()
if(pid == 0) {
printf("this is a child: my new unique pid is %d\n", getpid());
} else {
printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}
and below is some inline comments on your code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1 == 0){
/* This is child A */
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
/* This is parent A */
/* Child B and C will never reach this code */
pid3=fork(); /* D */
if(pid3==0) {
/* This is child D fork'ed from parent A */
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0)) {
/* pid1 will never be 0 here so this is dead code */
printf("Level 1\n");
}
if(pid1 !=0) {
/* This is always true for both parent and child E */
printf("Level 2\n");
}
if(pid2 !=0) {
/* This is parent E (same as parent A) */
printf("Level 3\n");
}
if(pid3 !=0) {
/* This is parent D (same as parent A) */
printf("Level 4\n");
}
}
return 0;
}
You can convert to an array and call array soring methods on it:
[...map].sort(/* etc */);
It really is an "it depends" kinda question. Some general points:
You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.
For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.
What the world needs is another monad blog post, but I think this is useful in identifying existing monads in the wild.
The above is a fractal called Sierpinski triangle, the only fractal I can remember to draw. Fractals are self-similar structure like the above triangle, in which the parts are similar to the whole (in this case exactly half the scale as parent triangle).
Monads are fractals. Given a monadic data structure, its values can be composed to form another value of the data structure. This is why it's useful to programming, and this is why it occurrs in many situations.
As stefanglase answered:
adding the following code to your build.gradle
(since version 1.1) works fine for output on passed, skipped and failed tests.
test {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
}
}
What I want to say additionally (I found out this is a problem for starters) is that the gradle test
command executes the test only one time per change.
So if you are running it the second time there will be no output on test results. You can also see this in the building output: gradle then says UP-TO-DATE on tests. So its not executed a n-th time.
Smart gradle!
If you want to force the test cases to run, use gradle cleanTest test
.
This is slightly off topic but I hope it will help some newbies.
edit
As sparc_spread stated in the comments:
If you want to force gradle to always run fresh tests (which might not always be a good idea) you can add outputs.upToDateWhen {false}
to testLogging { [...] }
. Continue reading here.
Peace.
You can change the 'template/popover/popover.html' in file 'ui-bootstrap-tpls-0.11.0.js' Write: "bind-html-unsafe" instead of "ng-bind"
It will show all popover with html. *its unsafe html. Use only if you trust the html.
Here's the simplest solution (Jibwa made it seem complicated in another answer), without having to generate indices yourself - just using the ShuffleSplit object to generate 1 split.
import numpy as np
from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit
sss = ShuffleSplit(n_splits=1, test_size=0.1)
data_size = 100
X = np.reshape(np.random.rand(data_size*2),(data_size,2))
y = np.random.randint(2, size=data_size)
sss.get_n_splits(X, y)
train_index, test_index = next(sss.split(X, y))
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
CreateImage(size, depth, channels)
https://opencv.willowgarage.com/documentation/python/core_operations_on_arrays.html#CreateImage
None of the above responses are working for error that has no body but still has some describing text. For me, it was SSL certificate problem: unable to get local issuer certificate
error. So I looked right into the code, because doc does't really say much, and did this (in Guzzle 7.1):
try {
// call here
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
// message is in $response->getReasonPhrase()
} else {
$response = $e->getHandlerContext();
if (isset($response['error'])) {
// message is in $response['error']
} else {
// Unknown error occured!
}
}
}
you can use sudo apt-get install python3-distutils
by root permission.
i believe it worked here
Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with
-----BEGIN CERTIFICATE-----
and end with
-----END CERTIFICATE-----
Finally, to check it is not corrupted, get hold of openssl and print its details using
openssl x509 -in cacerts.pem -text