To read some specific column I did something like this:
dpkcs.csv content:
FN,LN,EMAIL,CC
Name1,Lname1,[email protected],CC1
Nmae2,Lname2,[email protected],CC2
The function to read it:
private void getEMailRecepientList() {
List<EmailRecepientData> emailList = null;// Blank list of POJO class
Scanner scanner = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("dpkcs.csv"));
Map<String, Integer> mailHeader = new HashMap<String, Integer>();
// read file line by line
String line = null;
int index = 0;
line = reader.readLine();
// Get header from 1st row of csv
if (line != null) {
StringTokenizer str = new StringTokenizer(line, ",");
int headerCount = str.countTokens();
for (int i = 0; i < headerCount; i++) {
String headerKey = str.nextToken();
mailHeader.put(headerKey.toUpperCase(), new Integer(i));
}
}
emailList = new ArrayList<EmailRecepientData>();
while ((line = reader.readLine()) != null) {
// POJO class for getter and setters
EmailRecepientData email = new EmailRecepientData();
scanner = new Scanner(line);
scanner.useDelimiter(",");
//Use Specific key to get value what u want
while (scanner.hasNext()) {
String data = scanner.next();
if (index == mailHeader.get("EMAIL"))
email.setEmailId(data);
else if (index == mailHeader.get("FN"))
email.setFirstName(data);
else if (index == mailHeader.get("LN"))
email.setLastName(data);
else if (index == mailHeader.get("CC"))
email.setCouponCode(data);
index++;
}
index = 0;
emailList.add(email);
}
reader.close();
} catch (Exception e) {
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
} finally {
scanner.close();
}
System.out.println("list--" + emailList);
}
The POJO Class:
public class EmailRecepientData {
private String emailId;
private String firstName;
private String lastName;
private String couponCode;
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
@Override
public String toString() {
return "Email Id=" + emailId + ", First Name=" + firstName + " ,"
+ " Last Name=" + lastName + ", Coupon Code=" + couponCode + "";
}
}
Use this code:
switch($a) {
case 1:
case 2:
.......
.......
.......
break;
}
The block is called for both 1 and 2.
If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.
var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();
Then you'll be able to access it like:
nodes.Any(n => n.Checked);
Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.
nodes.Add(new { Checked = false, /* etc */ });
The arguments
object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...)
will not work because the arguments object does not have the slice method.
Arrays do have this method, and because the arguments
object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.
So why use Array.prototype
? The Array
is the object which we create new arrays from (new Array()
), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype
object. So, for efficiency sake, instead of accessing the slice method by (new Array()).slice.call()
or [].slice.call()
, we just get it straight from the prototype. This is so we don't have to initialise a new array.
But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.
At least the way I've done this is as follows:
If you have a nested src tree (say com.test.myclass.MyClass) and you are compiling from a root directory you need to do the following:
1) when you create the jar (usually put this in a script): jar -cvfm my.jar com/test/myclass/manifest.txt com/test/myclass/MyClass.class
2) The manifest should look like:
Mainfest-version: 1.0 Main-Class: com.test.myclass.MyClass Class-Path: . my.jar
3) Now you can run the jar from anywhere like this:
java -jar my.jar
Hope this helps someone
In newer browsers, you could do the following:
document.querySelectorAll( ":hover" );
That'll give you a NodeList of items that the mouse is currently over in document order. The last element in the NodeList is the most specific, each preceding one should be a parent, grandparent, and so on.
import sys
sys.version
will be getting answer like this
'2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]'
here 2.7.6 is version
This error will also occur if you call .ps1
file from a .bat
file and file path has spaces.
The fix is to make sure there are no spaces in the path of .ps1
file.
Replace
values = ",".join(value_list)
with
values = ','.join([str(i) for i in value_list])
OR
values = ','.join(str(value_list)[1:-1])
With > 4.0 of select2 I am using
$("select").select2({
dropdownAutoWidth: true
});
These others did not work:
This just allow positive integers.
^[0-9]*[1-9][0-9]*$
The answer using jQuery that everyone seems to like has a major flaw, which is it is not scalable (at least as it is written). I think Martin Hansen has the right idea, which is to use HTML5 data-*
attributes. And you can even use the apostrophe correctly:
html:
<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>
css:
div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }
output:
Joe's task - mop kitchen
Charles' task - vacuum hallway
Most SSL certificates are bound to the hostname of the machine and not the ip address.
You might get a better answer if you ask this question on serverfault.com
You can use this
 
or  
It works on Visual Studio
Can be done with pure Bootstrap code.
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
<label for="id" class="col-md-2 control-label">ID</label>_x000D_
<div class="input-group">_x000D_
<span class="input-group-btn">_x000D_
<select class="form-control" name="id" id="id">_x000D_
<option value="">_x000D_
</select>_x000D_
</span>_x000D_
<span class="input-group-btn">_x000D_
<select class="form-control" name="nr" id="nr">_x000D_
<option value="">_x000D_
</select>_x000D_
</span>_x000D_
</div> _x000D_
</div>
_x000D_
When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.
There's no need for LINQ here, just call Sort:
list.Sort();
Example code:
List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
Console.WriteLine(x);
}
Result:
3
5
7
To help guard against SQL injection, I normally try to use functions wherever possible. In this case, you could do:
...
SET @TableName = '<[db].><[schema].>tblEmployees'
SET @TableID = OBJECT_ID(TableName) --won't resolve if malformed/injected.
...
SET @SQLQuery = 'SELECT * FROM ' + OBJECT_NAME(@TableID) + ' WHERE EmployeeID = @EmpID'
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.
Also, I suspect a better way of doing it for debug purpose would be to do:
#ifdef DEBUG
// output to file
#endif
You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.
i say a lot simpler way would be using the break
command, like
import tkinter as tk
win=tk.Tk
def exit():
break
btn= tk.Button(win, text="press to exit", command=exit)
win.mainloop()
OR use sys.exit()
import tkinter as tk
import sys
win=tk.Tk
def exit():
sys.exit
btn= tk.Button(win, text="press to exit", command=exit)
win.mainloop()
there are many options that would change the height of an input box. padding, font-size, height would all do this. different combinations of these produce taller input boxes with different styles. I suggest just changing the font-size (and font-family for looks) and add some padding to make it even taller and also more appealing. I will give you an example of all three style though:
#signin input {
font-size:20px;
}
OR
#signin input {
padding:10px;
}
OR
#signin input {
height:24px;
}
This is the combination of the three that I recommend:
#signin input {
font-size:20px;font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300;
padding:10px;
}
As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'"
) or you can escape it inside single quotes ('\''
).
To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:
>>> "didn't".replace("'", "")
'didnt'
In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...
Update: this literally answers the question asked, but I think KurzedMetal's answer is really what you want.
Assuming that:
master
master
in origin
.... you could do:
# Do a pull as usual, but don't commit the result:
git pull --no-commit
# Overwrite config/config.php with the version that was there before the merge
# and also stage that version:
git checkout HEAD config/config.php
# Create the commit:
git commit -F .git/MERGE_MSG
You could create an alias for that if you need to do it frequently. Note that if you have uncommitted changes to config/config.php
, this would throw them away.
The only correct answer is not to join columns with null values. This can lead to unwanted behaviour very quickly.
e.g. isnull(b.colId,''): What happens if you have empty strings in your data? The join maybe duplicate rows which I guess is not intended in this case.
We used jquery trigger to onload have a script hit the button for us
$(".class_name").trigger('click');
I believe the get()
function immediately runs the select query and does not accept ORDER BY
conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:
$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get();
return $query->result();
I had same problem.then i set globally map variable e.g var map= null and then for display map i check
if(map==null)then map=new L.Map('idopenstreet').setView();
By this solution your map will be initialize only first time after that map will be fill by L.Map then it will not be null. so no error will be there like map container already initialize.
I have found the answer to my question.
client.DefaultRequestHeaders.Add("X-Version","1");
That should add a custom header to your request
.offset()
will return the offset position of an element as a simple object, eg:
var position = $(element).offset(); // position = { left: 42, top: 567 }
You can use this return value to position other elements at the same spot:
$(anotherElement).css(position)
Here is the App Bit Web Server (PHP,MySQL,PMA)
It can run a variety of CMS like Wordpress, Joomla, Drupal, Prestashop, etc. Besides CMS can also run PHP frameworks like Code Igniter, YII, CakePHP, etc. It is the same as WAMP or LAMP or XAMPP on your computer or laptop, but this is for android devices with lighttpd instead of apache.
Another method without WHERE, try this..
Will select both Empty and NULL values
SELECT ISNULL(NULLIF(fieldname,'')) FROM tablename
Extending Dale Ragan's answer, his example for reuse, create an ApplicationController class which derives from Controller, and in turn have all your other controllers derive from that ApplicationController class rather than Controller.
Example:
public class MyCustomApplicationController : Controller {}
public class HomeController : MyCustomApplicationController {}
On your new ApplicationController create a property named ExecutingAction with this signature:
protected ActionDescriptor ExecutingAction { get; set; }
And then in the OnActionExecuting method (from Dale Ragan's answer), simply assign the ActionDescriptor to this property and you can access it whenever you need it in any of your controllers.
string currentActionName = this.ExecutingAction.ActionName;
In the same spirit as https://stackoverflow.com/a/6943976/7154924:
cat -A
-A, --show-all
equivalent to -vET
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
-E, --show-ends
display $ at end of each line
-T, --show-tabs
display TAB characters as ^I
Alternatively, or at the same time, you can pipe to tr
to substitute arbitrary characters to the desired ones for display, before piping to a pager like less
if desired.
Shouldn't it be just the .list-group
? See below,
<ul class="list-group">
<li class="list-group-item active">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Morbi leo risus</li>
<li class="list-group-item">Porta ac consectetur ac</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
Reference: Bootstrap 4 Basic Example of a List group
I tried this in one of my databases.
To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.
Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.
to make it easier for you here is the code that i use :
w, h = image.shape
top=10
right=50
down=15
left=80
croped_image = image[top:((w-down)+top), right:((h-left)+right)]
plt.imshow(croped_image, cmap="gray")
plt.show()
Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?
using xl = Microsoft.Office.Interop.Excel;
xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;
Simple as that!
HTH, Z
Try this:
Custom formula is
=countif(A:A,A1)>1
(or change A
to your chosen column)A1:A100
).Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.
For locales using comma (,
) as a decimal separator, the argument separator is most likely a semi-colon (;
). That is, try: =countif(A:A;A1)>1
, instead.
For multiple columns, use countifs
.
You can do replace tabs with spaces in all project files by:
Ctrl+Shif+F
^\A(.*)$
Your dir
Replace by \1
This will cause all project files to be opened, with their buffer marked as dirty. With this, you can now optionally enable these next Sublime Text settings, to trim all files trailing white space and ensure a new line at the end of every file.
You can enabled these settings by going on the menu Preferences -> Settings
and adding these contents to your settings file:
"ensure_newline_at_eof_on_save": true,
"trim_trailing_white_space_on_save": true,
View -> Show Console (Ctrl+`)
and run the command:
import threading; threading.Thread( args=(set(),), target=lambda counterset: [ (view.run_command( "expand_tabs", {"set_translate_tabs": True} ), print( "Processing {:>5} view of {:>5}, view id {} {}".format( len( counterset ) + 1, len( window.views() ), view.id(), ( "Finished converting!" if len( counterset ) > len( window.views() ) - 2 else "" ) ) ), counterset.add( len( counterset ) ) ) for view in window.views() ] ).start()
File -> Save All
update 2 ::slotted
::slotted
is now supported by all new browsers and can be used with ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
update 1 ::ng-deep
/deep/
was deprecated and replaced by ::ng-deep
.
::ng-deep
is also already marked deprecated, but there is no replacement available yet.
When ViewEncapsulation.Native
is properly supported by all browsers and supports styling accross shadow DOM boundaries, ::ng-deep
will probably be discontinued.
original
Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using [innerHTML]
these classes are not added and the rewritten CSS doesn't match.
As a workaround try
/* :host /deep/ mySelector { */
:host ::ng-deep mySelector {
background-color: blue;
}
index.html
/* body /deep/ mySelector { */
body ::ng-deep mySelector {
background-color: green;
}
>>>
(and the equivalent/deep/
but /deep/
works better with SASS) and ::shadow
were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with encapsulation: ViewEncapsulation.Emulated
which is the default in Angular2. They probably also work with ViewEncapsulation.None
but are then only ignored because they are not necessary.
These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.
Another approach is to use
@Component({
...
encapsulation: ViewEncapsulation.None,
})
for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be all components in your application)
Update
Thanks, Bendin. I like your solution very much.
I changed it to work in reverse order, showing most recent changes first. Which is important with long standing code, maintained over several years. I usually pipe it into more.
svnhistory elements.py |more
I added -r to the sort. I removed spec. handling for 'first record'. It is it will error out on the last entry, as there is nothing to diff it with. Though I am living with it because I never get down that far.
#!/bin/bash
# history_of_file
#
# Bendin on Stack Overflow: http://stackoverflow.com/questions/282802
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
#
# Dlink
# Made to work in reverse order
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -nr | {
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
history_of_file $1
Simple example from: http://www.longtailvideo.com/blog/26517/using-the-browsers-new-html5-fullscreen-capabilities/
<script type="text/javascript">
function goFullscreen(id) {
// Get the element that we want to take into fullscreen mode
var element = document.getElementById(id);
// These function will not exist in the browsers that don't support fullscreen mode yet,
// so we'll have to check to see if they're available before calling them.
if (element.mozRequestFullScreen) {
// This is how to go into fullscren mode in Firefox
// Note the "moz" prefix, which is short for Mozilla.
element.mozRequestFullScreen();
} else if (element.webkitRequestFullScreen) {
// This is how to go into fullscreen mode in Chrome and Safari
// Both of those browsers are based on the Webkit project, hence the same prefix.
element.webkitRequestFullScreen();
}
// Hooray, now we're in fullscreen mode!
}
</script>
<img class="video_player" src="image.jpg" id="player"></img>
<button onclick="goFullscreen('player'); return false">Click Me To Go Fullscreen! (For real)</button>
Serialization is the process of turning a Java object into byte array and then back into object again with its preserved state. Useful for various things like sending objects over network or caching things to disk.
Read more from this short article which explains programming part of the process quite well and then move over to to Serializable javadoc. You may also be interested in reading this related question.
VSCode comes with in-built color themes which can be used to change the colors of the editor and the terminal.
ctrl+k+t
in windows/ubuntu or cmd+k+t
on mac.ctrl+shift+p
in windows/ubuntu or cmd+shift+p
on mac and type color
. Select preferences: color theme
from the options, to select your favourite color.category:themes
to install your favourite themes. (If you need to sort the themes by installs search category:themes @sort:installs
)Edit - for manually editing colors in terminal
VSCode team have removed customizing colors from user settings page. Currently using the themes is the only way to customize terminal colors in VSCode. For more information check out issue #6766
Download the source code, unzip it to and directory, and execute python setup.py install.
We tried a few applications, both trials of commercial products and freely available ones. Ultimately, it was the trial edition of the Team Test Load Agent software that we tried. It definitely works great and is fairly simple to use. In the long run, it bolstered our argument to move to Team Foundation Server and equip all parts of the department with the appropriate tooling.
The obvious downside, however, is the price.
Just if someone is interested in another option:
content=( $(cat test.txt) )
a=0
while [ $a -le ${#content[@]} ]
do
echo ${content[$a]}
a=$[a+1]
done
This question is very similar to:
Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.
namespace CancelSample
{
using System;
using System.Threading;
using System.Runtime.InteropServices;
internal class Program
{
/// <summary>
/// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
/// </summary>
/// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
/// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);
/// <summary>
/// The console close handler delegate.
/// </summary>
/// <param name="closeReason">
/// The close reason.
/// </param>
/// <returns>
/// True if cleanup is complete, false to run other registered close handlers.
/// </returns>
private delegate bool ConsoleCloseHandler(int closeReason);
/// <summary>
/// Event set when the process is terminated.
/// </summary>
private static readonly ManualResetEvent TerminationRequestedEvent;
/// <summary>
/// Event set when the process terminates.
/// </summary>
private static readonly ManualResetEvent TerminationCompletedEvent;
/// <summary>
/// Static constructor
/// </summary>
static Program()
{
// Do this initialization here to avoid polluting Main() with it
// also this is a great place to initialize multiple static
// variables.
TerminationRequestedEvent = new ManualResetEvent(false);
TerminationCompletedEvent = new ManualResetEvent(false);
SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
}
/// <summary>
/// The main console entry point.
/// </summary>
/// <param name="args">The commandline arguments.</param>
private static void Main(string[] args)
{
// Wait for the termination event
while (!TerminationRequestedEvent.WaitOne(0))
{
// Something to do while waiting
Console.WriteLine("Work");
}
// Sleep until termination
TerminationRequestedEvent.WaitOne();
// Print a message which represents the operation
Console.WriteLine("Cleanup");
// Set this to terminate immediately (if not set, the OS will
// eventually kill the process)
TerminationCompletedEvent.Set();
}
/// <summary>
/// Method called when the user presses Ctrl-C
/// </summary>
/// <param name="reason">The close reason</param>
private static bool OnConsoleCloseEvent(int reason)
{
// Signal termination
TerminationRequestedEvent.Set();
// Wait for cleanup
TerminationCompletedEvent.WaitOne();
// Don't run other handlers, just exit.
return true;
}
}
}
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Use this javascript function as an example on how to accomplish this.
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
The answers given here already may work in limited situations, but are certainly not the best way to go about it. Don't reinvent the wheel. The File System Object in the Microsoft Scripting Runtime library already has a method to do exactly this. It's called GetBaseName. It handles periods in the file name as is.
Public Sub Test()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
End Sub
Public Sub Test2()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName("MyFile.something.txt")
End Sub
Instructions for adding a reference to the Scripting Library
overflow:hidden
).For example:
<div style="width:200px;height:200px;overflow:hidden">
<img src="foo.png" />
</div>
The following code will read all emails & print the Subject, Body & Date.
<?php
$imap=imap_open("Mailbox","Email Address","Password");
if($imap){$fixMessages=1+imap_num_msg($imap); //Check no.of.msgs
/*
By adding 1 to "imap_num_msg($imap)" & starting at $count=1
the "Start" & "End" non-messages are ignored
*/
for ($count=1; $count<$fixMessages; $count++){
$objectOverview=imap_fetch_overview($imap,$count,0);
print '<br>$objectOverview: '; print_r($objectOverview);
print '<br>objectSubject ='.($objectOverview[0]->subject));
print '<br>objectDate ='.($objectOverview[0]->date);
$bodyMessage=imap_fetchbody($imap,$count,1);
print '<br>bodyMessage ='.$bodyMessage.'<br><br>';
} //for ($count=1; $count<$fixMessages; $count++)
} //if($imap)
imap_close($imap);
?>
This outputs the following:
$objectOverview: Array ( [0] => stdClass Object ( [subject] => Hello
[from] => Email Address [to] => Email Address [date] => Sun, 16 Jul 2017 20:23:18 +0100
[message_id] => [size] => 741 [uid] => 2 [msgno] => 2 [recent] => 0 [flagged] => 0
[answered] => 0 [deleted] => 0 [seen] => 1 [draft] => 0 [udate] => 1500232998 ) )
objectSubject =Hello
objectDate =Sun, 16 Jul 2017 20:23:18 +0100
bodyMessage =Test
Having struggled with various suggestions I have used trial & error to come up with this solution. Hope it helps.
for OrderedDict() you can access the elements by indexing by getting the tuples of (key,value) pairs as follows or using '.values()'
>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>>d.values()
odict_values(['python','spam'])
>>>list(d.values())
['python','spam']
Use this to simplify access in an Activity. Then you can directly refer to rootView
from the Activity, or activity.rootView
outside of it:
val Activity.rootView get() = window.decorView.rootView
If you'd like to add the same for Fragments for consistency, add:
val Fragment.rootView get() = view?.rootView
To show the full element (if it's possible with the current window size):
var element = $("#some_element");
var elementHeight = element.height();
var windowHeight = $(window).height();
var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);
You could use the TimeSpan constructor which takes a long for Ticks:
TimeSpan duration = new TimeSpan(endtime.Ticks - startTime.Ticks);
I've developed an almost flawless try & catch implementation in bash, that allows you to write code like:
try
echo 'Hello'
false
echo 'This will not be displayed'
catch
echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
You can even nest the try-catch blocks inside themselves!
try {
echo 'Hello'
try {
echo 'Nested Hello'
false
echo 'This will not execute'
} catch {
echo "Nested Caught (@ $__EXCEPTION_LINE__)"
}
false
echo 'This will not execute too'
} catch {
echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}
The code is a part of my bash boilerplate/framework. It further extends the idea of try & catch with things like error handling with backtrace and exceptions (plus some other nice features).
Here's the code that's responsible just for try & catch:
set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0
# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
__oo__insideTryCatch+=1; ( set -e;
trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "
Exception.Capture() {
local script="${BASH_SOURCE[1]#./}"
if [[ ! -f /tmp/stored_exception_source ]]; then
echo "$script" > /tmp/stored_exception_source
fi
if [[ ! -f /tmp/stored_exception_line ]]; then
echo "$1" > /tmp/stored_exception_line
fi
return 0
}
Exception.Extract() {
if [[ $__oo__insideTryCatch -gt 1 ]]
then
set -e
fi
__oo__insideTryCatch+=-1
__EXCEPTION_CATCH__=( $(Exception.GetLastException) )
local retVal=$1
if [[ $retVal -gt 0 ]]
then
# BACKWARDS COMPATIBILE WAY:
# export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
# export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
return 1 # so that we may continue with a "catch"
fi
}
Exception.GetLastException() {
if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
then
cat /tmp/stored_exception
cat /tmp/stored_exception_line
cat /tmp/stored_exception_source
else
echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
fi
rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
return 0
}
Feel free to use, fork and contribute - it's on GitHub.
It's been released - Get the MySQL connector for .Net v6.5 - this has support for [Entity Framework]
I was waiting for this the whole time, although the support is basic, works for most basic scenarios of db interaction. It also has basic Visual Studio integration.
UPDATE http://dev.mysql.com/downloads/connector/net/ Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Now that we can use dataFor()
to check if the binding has been applied, I would prefer check the data binding, rather than cleanNode()
and applyBindings()
.
Like this:
var koNode = document.getElementById('formEdit');
var hasDataBinding = !!ko.dataFor(koNode);
console.log('has data binding', hasDataBinding);
if (!hasDataBinding) { ko.applyBindings(vm, koNode);}
A lot of answers already!
First, let's say it is fairly common that we need to do the binding multiple times in a page. Say, I have a form inside the Bootstrap modal, which will be loaded again and again. Many of the form input have two-way binding.
I usually take the easy route: clearing the binding every time before the the binding.
var koNode = document.getElementById('formEdit');
ko.cleanNode(koNode);
ko.applyBindings(vm, koNode);
Just make sure here koNode
is required, for, ko.cleanNode()
requires a node element, even though we can omit it in ko.applyBinding(vm)
.
In Windows 10, Windows Defender has a feature of core isolation which uses virtualisation technology that will also interupt in working of HAXM. Disable it and try again. In my case disabling it solved my issue.
On a 32-bit system, kmalloc() returns the kernel logical address (its a virtual address though) which has the direct mapping (actually with constant offset) to physical address. This direct mapping ensures that we get a contiguous physical chunk of RAM. Suited for DMA where we give only the initial pointer and expect a contiguous physical mapping thereafter for our operation.
vmalloc() returns the kernel virtual address which in turn might not be having a contiguous mapping on physical RAM. Useful for large memory allocation and in cases where we don't care about that the memory allocated to our process is continuous also in Physical RAM.
RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]
(No space inside your website)
If you don't call the favicon, favicon.ico
, you can use that tag to specify the actual path (incase you have it in an images/
directory). The browser/webpage looks for favicon.ico
in the root directory by default.
Typically you model the enum itself as a class with the enum
stereotype
I solved this by adding email accounts in Cpanel and also adding that same email to the header from field like this
$header = 'From: XXXXXXXX <[email protected]>' . "\r\n";
You can't do this no. There is one attribute selector that matches exactly or partial until a - sign, but it wouldn't work here because you have multiple attributes. If the class name you are looking for would always be first, you could do this:
<html>
<head>
<title>Test Page</title>
<style type="text/css">
div[class|=status] { background-color:red; }
</style>
</head>
<body>
<div id='A' class='status-important bar-class'>A</div>
<div id='B' class='bar-class'>B</div>
<div id='C' class='status-low-priority bar-class'>C</div>
</body>
</html>
Note that this is just to point out which CSS attribute selector is the closest, it is not recommended to assume class names will always be in front since javascript could manipulate the attribute.
Use isinstance
, nothing else:
if isinstance(x, pd.DataFrame):
... # do something
PEP8 says explicitly that isinstance
is the preferred way to check types
No: type(x) is pd.DataFrame
No: type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)
And don't even think about
if obj.__class__.__name__ = 'DataFrame':
expect_problems_some_day()
isinstance
handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str
or unicode
), because they derive from basestring
)
if isinstance(obj, basestring):
i_am_string(obj)
Specifically for pandas
DataFrame
objects:
import pandas as pd
isinstance(var, pd.DataFrame)
Yes, you can reference any image from the image
element. And you can use data URIs to make the SVG self-contained. An example:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
...
<image
width="100" height="100"
xlink:href="data:image/png;base64,IMAGE_DATA"
/>
...
</svg>
The svg
element attribute xmlns:xlink
declares xlink
as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href
means.
The IMAGE_DATA
is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.
Here's a full example from the SVG testsuite.
There are two issues:
To get the coordinates you don't need the Internet. GPS is satellite-based. But to derive street/city information from the coordinates, you'd need either to implement the map and the corresponding algorithms yourself on the device (a lot of work!) or to rely on proven services, e.g. by Google, in which case you'd need an Internet connection.
As of recently, Google allows for caching the maps, which would at least allow you to show your current position on the map even without a data connection, provided, you had cached the map in advance, when you could access the Internet.
TEXT
c
bytes of disk space, where c
is the length of the stored string.VARCHAR(M)
M
charactersM
needs to be between 1 and 65535c
bytes (for M
≤ 255) or 2 + c
(for 256 ≤ M
≤ 65535) bytes of disk space where c
is the length of the stored stringTEXT
has a fixed max size of 2¹6-1 = 65535
characters.
VARCHAR
has a variable max size M
up to M = 2¹6-1
.
So you cannot choose the size of TEXT
but you can for a VARCHAR
.
The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT
column.
So if you want to have an index on the column, you have to use VARCHAR
. But notice that the length of an index is also limited, so if your VARCHAR
column is too long you have to use only the first few characters of the VARCHAR
column in your index (See the documentation for CREATE INDEX
).
But you also want to use VARCHAR
, if you know that the maximum length of the possible input string is only M
, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30)
instead of TINYTEXT
or TEXT
and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)
Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT
or LONGTEXT
, but be careful: MEDIUMTEXT
stores strings up to 16 MB, LONGTEXT
up to 4 GB. If you use LONGTEXT
and get the data via PHP (at least if you use mysqli
without store_result
), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.
However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.
Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30)
, VARCHAR(100)
and TINYTEXT
, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000)
or a TEXT
column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).
For more information have a look at the documentation.
Finally, I want to add a notice, that both, TEXT
and VARCHAR
are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR
. You can read more about this here.
I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you really need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's with
statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:
from contextlib import contextmanager
@contextmanager
def nested_break():
class NestedBreakException(Exception):
pass
try:
yield NestedBreakException
except NestedBreakException:
pass
Now you can use this context manager as follows:
with nested_break() as mylabel:
while True:
print "current state"
while True:
ok = raw_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": raise mylabel
if ok == "n" or ok == "N": break
print "more processing"
Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built Exception
subclass for each use of nested_break
; no need to declare your own Exception
subclass each time.
I got this fixed by setting the system time correctly.
Ensure the aws bucket region is right and your system time matches the aws region time
If you're only wanting the magnifing glass on hover then you can use
a:hover img { cursor: url(glass.cur); }
http://www.javascriptkit.com/dhtmltutors/csscursors.shtml
If you want it there permanently you should probably either have it included in the original thumnail, or add it using JavaScript rather than adding it to the HTML (this is purely style and shouldn't be in the content).
Let me know if you want help on the JavaScript side.
Take a look at bash(1)
, you need a login shell to pickup the ~/.profile
, i.e. the -l
option.
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
Yes, you should always call base class __init__
explicitly as a good coding practice. Forgetting to do this can cause subtle issues or run time errors. This is true even if __init__
doesn't take any parameters. This is unlike other languages where compiler would implicitly call base class constructor for you. Python doesn't do that!
The main reason for always calling base class _init__
is that base class may typically create member variable and initialize them to defaults. So if you don't call base class init, none of that code would be executed and you would end up with base class that has no member variables.
Example:
class Base:
def __init__(self):
print('base init')
class Derived1(Base):
def __init__(self):
print('derived1 init')
class Derived2(Base):
def __init__(self):
super(Derived2, self).__init__()
print('derived2 init')
print('Creating Derived1...')
d1 = Derived1()
print('Creating Derived2...')
d2 = Derived2()
This prints..
Creating Derived1...
derived1 init
Creating Derived2...
base init
derived2 init
The default answer is to remove the item from whatever collection you're using as the GridView's DataSource.
If that option is undesirable then I recommend that you use the GridView's RowDataBound
event to selectively set the row's (e.Row
) Visible
property to false.
That means you must install simplejson
. On newer versions of python, it was included by default into python's distribution, and renamed to json
. So if you are on python 2.6+ you should change all instances of simplejson
to json
.
For a quick fix you could also edit the file and change the line:
import simplejson
to:
import json as simplejson
and hopefully things will work.
from pylab import *
import numpy as np
x1 = arange(data) #for example this is a list
y1 = arange(data) #for example this is a list
x=np.array(x) #this will convert a list in to an array
y=np.array(y)
m,b = polyfit(x, y, 1)
plot(x, y, 'yo', x, m*x+b, '--k')
show()
I think it has changed again.
For posting this works in Xcode 8.2.
NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)
in this scenario:
DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
aren't you missing the column you want to compare to? example:
DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.
There is also a really simple way to do this with the help of the RecursiveTreeIterator
class, answered here: https://stackoverflow.com/a/37548504/2032235
A simple option using plt.gca() to get current axes and set aspect
plt.gca().set_aspect('equal')
in place of your last line
You can use concat:
In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
Out[11]:
df1 df2
2014-01-01 NaN -0.978535
2014-01-02 -0.106510 -0.519239
2014-01-03 -0.846100 -0.313153
2014-01-04 -0.014253 -1.040702
2014-01-05 0.315156 -0.329967
2014-01-06 -0.510577 -0.940901
2014-01-07 NaN -0.024608
2014-01-08 NaN -1.791899
[8 rows x 2 columns]
The axis argument determines the way the DataFrames are stacked:
df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame(['a', 'b', 'c'])
pd.concat([df1, df2], axis=0)
0
0 1
1 2
2 3
0 a
1 b
2 c
pd.concat([df1, df2], axis=1)
0 0
0 1 a
1 2 b
2 3 c
In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml
), you can do so by just putting an array of mappings in the @WebFilter
annotation:
/**
* Filter implementation class LoginFilter
*/
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
...
And just as an FYI, this same thing works for servlets using the servlet annotation too:
/**
* Servlet implementation class LoginServlet
*/
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
...
The answer was given already by either Sivasubramaniam Arunachalam or ch3ka.
I am just adding a performances view of the answer.
dicttest={}
dicttest['ligne1']={'ligne1.1':'test','ligne1.2':'test8'}
%timeit dicttest['ligne1']['ligne1.1']
%timeit dicttest.get('ligne1').get('ligne1.1')
gives us :
112 ns ± 29.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
235 ns ± 9.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In addition to the accepted answer, there's a third option that can be useful in some cases:
You can make a hybrid between v1 & v4 by deliberately generating v1 UUIDs with a random broadcast MAC address (this is allowed by the v1 spec). The resulting v1 UUID is time dependant (like regular v1), but lacks all host-specific information (like v4). It's also much closer to v4 in it's collision-resistance: v1mc = 60 bits of time + 61 random bits = 121 unique bits; v4 = 122 random bits.
First place I encountered this was Postgres' uuid_generate_v1mc() function. I've since used the following python equivalent:
from os import urandom
from uuid import uuid1
_int_from_bytes = int.from_bytes # py3 only
def uuid1mc():
# NOTE: The constant here is required by the UUIDv1 spec...
return uuid1(_int_from_bytes(urandom(6), "big") | 0x010000000000)
(note: I've got a longer + faster version that creates the UUID object directly; can post if anyone wants)
In case of LARGE volumes of calls/second, this has the potential to exhaust system randomness. You could use the stdlib random
module instead (it will probably also be faster). But BE WARNED: it only takes a few hundred UUIDs before an attacker can determine the RNG state, and thus partially predict future UUIDs.
import random
from uuid import uuid1
def uuid1mc_insecure():
return uuid1(random.getrandbits(48) | 0x010000000000)
Generally it means:
127 - command not found
but it can also mean that the command is found,
but a library that is required by the command is NOT found.
I followed multiple answers from above and got my issue resolved.
Issue:
Javac was on 13 from jdk but java was using 1.8 from jre so java threw incompatible runtime error
Fix:
Under Control Panel -> Programs: I uninstalled 1.8 (named Java 8 runtime) and DID NOT touch the other one (named Java (TM) SE Development Kit 13)
Deleted java.exe, javac.exe and javawc.exe files from: a. C:\Windows\system32 b. C:\Windows\SysWOW64 c. C:\ProgramData\Oracle\Java\javapath
The environment variable JDK_HOME was pointing to 13 but JAVA_HOME was pointing to 1.8 so i pointed JAVA_HOME to also use 13 which was C:\Program Files\Java\jdk-13.0.1
There was a Path variable under both User variables and system variables sections. For the one in user variables section, i added the string %JDK_HOME% - which translated automatically to the physical path. For the one under system variables, I deleted the path C:\ProgramData\Oracle\Java\javapath and added C:\Program Files\Java\jdk-13.0.1\bin
All good now! Thanks to all the people who answered, you rock!
You can do it in JavaScript like so (Building off of @dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
How to implement:
import 'package:intl/intl.dart';
getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
// dateFormat = 'MM/dd/yy';
final DateTime docDateTime = DateTime.parse(givenDateTime);
return DateFormat(dateFormat).format(docDateTime);
}
How to call:
getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');
Result:
02/15/21
Above code solved my problem. I hope, this will also help you. Thanks for asking this question.
You can use the output value from stat_summary()
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
Just remove the double quote, this works in Windows 7:
start C:\ProgramFiles\folderName\app.exe
If you want to maximize the window, try this:
start /MAX C:\ProgramFiles\folderName\app.exe
Your command START "filepath"
will start a command prompt and change the command prompt title to filepath
.
Try to run start /?
in windows command prompt and you will get more info.
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
window.location.href, this as saved my life in webview from Android 5.1. The page don't reload with location.reload() in this version from Android.
Of course this will generate each pair twice as each for
loop will go through every item of the list.
You could use some itertools magic here to generate all possible combinations:
import itertools
for a, b in itertools.combinations(mylist, 2):
compare(a, b)
itertools.combinations
will pair each element with each other element in the iterable, but only once.
You could still write this using index-based item access, equivalent to what you are used to, using nested for
loops:
for i in range(len(mylist)):
for j in range(i + 1, len(mylist)):
compare(mylist[i], mylist[j])
Of course this may not look as nice and pythonic but sometimes this is still the easiest and most comprehensible solution, so you should not shy away from solving problems like that.
Just in case someone from Blogger arrives, I had this problem when using Beautify
extension in VSCode. Don´t use it, don´t beautify
it.
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
In Reactive forms. Binding can be done in the component file and usage of ngValue. For more details please go through the following link
https://angular.io/api/forms/SelectControlValueAccessor
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<select formControlName="state">
<option *ngFor="let state of states" [ngValue]="state">
{{ state.abbrev }}
</option>
</select>
</form>
<p>Form value: {{ form.value | json }}</p>
<!-- {state: {name: 'New York', abbrev: 'NY'} } -->
`,
})
export class ReactiveSelectComp {
states = [
{name: 'Arizona', abbrev: 'AZ'},
{name: 'California', abbrev: 'CA'},
{name: 'Colorado', abbrev: 'CO'},
{name: 'New York', abbrev: 'NY'},
{name: 'Pennsylvania', abbrev: 'PA'},
];
form = new FormGroup({
state: new FormControl(this.states[3]),
});
}
Have you escaped your forward slashes( / )? I've had trouble with those before
If your form does not have any id, but it has a class name like theForm, you can use the below statement to submit it:
document.getElementsByClassName("theForm")[0].submit();
What about:
//true if it doesn't contain letters
bool result = hello.Any(x => !char.IsLetter(x));
When I know the string is going to be reasonably short then I use the following one liner... (remember to escape backslashes)
// if str is C:\windows\file system\path\picture name.jpg
alert( str.split('\\').pop() );
alert pops up with picture name.jpg
It seems that your action needs k
but ModelBinder can not find it (from form, or request or view data or ..)
Change your action to this:
public ActionResult DetailsData(int? k)
{
EmployeeContext Ec = new EmployeeContext();
if (k != null)
{
Employee emp = Ec.Employees.Single(X => X.EmpId == k.Value);
return View(emp);
}
return View();
}
In my case I had to cd
(change directory) before calling the bat file, because inside the bat file was a copy operation that specified relative paths.
:: Copy file
cd "$(ProjectDir)files\build_scripts\"
call "copy.bat"
You manage the list of available compilers in the Window -> Preferences -> Java -> Installed JRE's tab
.
In the project build path configuration dialog, under the libraries tab, you can delete the entry for JRE System Library
, click on Add Library
and choose the installed JRE to compile with. Some compilers can be configured to compile at a back-level compiler version. I think that's why you're seeing the addition version options.
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
if you want to change the text of "input",use:
`$("#inputId").val("what you want to put")`
and if you want to change the text in "label","span","div", you can use
`$("#containerId").text("what you want to put")`
Here is a first try that's easy on the coder but hard on the CPU which prepends a random number to each line, sorts them and then strips the random number from each line. In effect, the lines are sorted randomly:
cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled
I'm using Visual Studio 2015 and finally ran across this post.
Yes in order to use
JavaScriptSerializer json = new JavaScriptSerializer();
You must right click on references and under Assemblies --> Framework choose
System.Web.Extensions
Then add in your reference
using System.Web.Script.Serialization;
We can implement by 3 Methods:
Note:
"automatic-scroll" => The particular element
"scrollable-div" => The scrollable area div
Method 1:
document.querySelector('.automatic-scroll').scrollIntoView({
behavior: 'smooth'
});
Method 2:
location.href = "#automatic-scroll";
Method 3:
$('#scrollable-div').animate({
scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top +
$('#scrollable-div').scrollTop()
})
Important notice: method 1 & method 2 will be useful if the scrollable area height is "auto". Method 3 is useful if we using the scrollable area height like "calc(100vh - 200px)".
Yes, but it depends on what you mean by 'embed'; as far as I can tell after reading through the docs, it seems like you have a couple of options if you want to get around using the iframe API. You can use the javascript and flash API's (https://developers.google.com/youtube/player_parameters) to embed a player, but that involves creating Flash objects in your code (something I personally avoid, but not necessarily something that you have to). Below are some helpful sections from the dev docs for the Youtube API.
If you really want to get around all these methods and include video without any sort of iframe, then your best bet might be creating an HTML5 video player/app that can connect to the Youtube Data API (https://developers.google.com/youtube/v3/). I'm not sure what the extent of your needs are, but this would be the way to go if you really want to get around using any iframes or flash objects.
Hope this helps!
Useful:
(https://developers.google.com/youtube/player_parameters)
IFrame embeds using the IFrame Player API
Follow the IFrame Player API instructions to insert a video player in your web page or application after the Player API's JavaScript code has loaded. The second parameter in the constructor for the video player is an object that specifies player options. Within that object, the playerVars property identifies player parameters.
The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.
...
IFrame embeds using tags
Define an tag in your application in which the src URL specifies the content that the player will load as well as any other player parameters you want to set. The tag's height and width parameters specify the dimensions of the player.
If you are creating the element yourself (rather than using the IFrame Player API to create it), you can append player parameters directly to the end of the URL. The URL has the following format:
...
AS3 object embeds
Object embeds use an tag to specify the player's dimensions and parameters. The sample code below demonstrates how to use an object embed to load an AS3 player that automatically plays the same video as the previous two examples.
If the toplevel folder is known you can just write something like this:
for dir in `ls $YOUR_TOP_LEVEL_FOLDER`;
do
for subdir in `ls $YOUR_TOP_LEVEL_FOLDER/$dir`;
do
$(PLAY AS MUCH AS YOU WANT);
done
done
On the $(PLAY AS MUCH AS YOU WANT); you can put as much code as you want.
Note that I didn't "cd" on any directory.
Cheers,
Slightly OT, but perhaps useful: On Mac Chrome, although you cannot copy the xpath out of the search box in the Dev tools panel (instead, copy grabs the node as HTML), you can drag and drop the text into an external editor.
In OpenSuse at least, the unrpm
command comes with the build
package.
In a suitable directory (because this is an archive bomb):
unrpm file.rpm
Some time we have more spaces in between quotes, then use this approach
a = " "
>>> bool(a)
True
>>> bool(a.strip())
False
if not a.strip():
print("String is empty")
else:
print("String is not empty")
you are missing fields.iteritems()
in your code.
You could also do it other way, where you get values using keys in the dictionary.
for key in fields:
value = fields[key]
To check are the following:
ssh -vvv [email protected]
to see debug logs. If thing goes well, github.com will be added to known_hosts.chmod 700 id_rsa
)After all checks, try ssh -vvv [email protected]
.
The design guidelines defines two sizes and unless there is a strong reason to deviate from using either, the size can be controlled with the fabSize
XML attribute of the FloatingActionButton
component.
Consider specifying using either app:fabSize="normal"
or app:fabSize="mini"
, e.g.:
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_done_white_24px"
app:fabSize="mini" />
In support to the excellent answers here, and for future convenience, there may be a case where you want to flip the truth values in the columns and have other values remain the same (nan values for instance)
In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series[series.notna()] #remove nan values
In[3]: series # without nan
Out[3]:
0 True
2 False
dtype: object
# Out[4] expected to be inverse of Out[3], pandas applies bitwise complement
# operator instead as in `lambda x : (-1*x)-1`
In[4]: ~series
Out[4]:
0 -2
2 -1
dtype: object
as a simple non-vectorized solution you can just, 1. check types2. inverse bools
In[1]: series = pd.Series([True, np.nan, False, np.nan])
In[2]: series = series.apply(lambda x : not x if x is bool else x)
Out[2]:
Out[2]:
0 True
1 NaN
2 False
3 NaN
dtype: object
On windows if you just did a clean install and you get this you need blow away your npm cache in \AppData\Roaming
here is the solution i use, with notes below:
@mixin transition($trans...) {
@if length($trans) < 1 {
$trans: all .15s ease-out;
}
-moz-transition: $trans;
-ms-transition: $trans;
-webkit-transition: $trans;
transition: $trans;
}
.use-this {
@include transition;
}
.use-this-2 {
@include transition(all 1s ease-out, color 2s ease-in);
}
on button click, first open the database, fetch the data and close the data base like this
public class cytaty extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galeria);
Button bLosuj = (Button) findViewById(R.id.button1);
bLosuj.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myDatabaseHelper = new DatabaseHelper(cytaty.this);
myDatabaseHelper.openDataBase();
String text = myDatabaseHelper.getYourData(); //this is the method to query
myDatabaseHelper.close();
// set text to your TextView
}
});
}
}
and your getYourData()
in database class would be like this
public String[] getAppCategoryDetail() {
final String TABLE_NAME = "name of table";
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
// get the data into array, or class variable
} while (cursor.moveToNext());
}
cursor.close();
return data;
}
To get left and right tabs (now also with sideways) support for Bootstrap 3, bootstrap-vertical-tabs component can be used.
you can try with awk:
awk '/blah/{getline; print}' logfile
def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4):
"""Rescale `image` to `target_height` (preserving aspect ratio)."""
w = int(round(target_height * image.shape[1] / image.shape[0]))
return cv2.resize(image, (w, target_height), interpolation=method)
def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4):
"""Rescale `image` to `target_width` (preserving aspect ratio)."""
h = int(round(target_width * image.shape[0] / image.shape[1]))
return cv2.resize(image, (target_width, h), interpolation=method)
In order to forcefully let the namenode leave safemode, following command should be executed:
bin/hadoop dfsadmin -safemode leave
You are getting Unknown command
error for your command as -safemode
isn't a sub-command for hadoop fs
, but it is of hadoop dfsadmin
.
Also after the above command, I would suggest you to once run hadoop fsck
so that any inconsistencies crept in the hdfs might be sorted out.
Update:
Use hdfs
command instead of hadoop
command for newer distributions. The hadoop
command is being deprecated:
hdfs dfsadmin -safemode leave
hadoop dfsadmin
has been deprecated and so is hadoop fs
command, all hdfs related tasks are being moved to a separate command hdfs
.
I think that Proguard is the best. It is also possible to integrate it with your IDE (for example NetBeans). However, consider that if you obfuscate your code it could be difficult to track problems in your logs..
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script>
function notify(){
if (Notification.permission !== "granted") {
Notification.requestPermission();
}
else{
var notification = new Notification('hello', {
body: "Hey there!",
});
notification.onclick = function () {
window.open("http://google.com");
};
}
}
</script>
</head>
<body>
<button onclick="notify()">Notify</button>
</body>
background-image
instead of background
This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}
You could do it like this :
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
background-size:20px 20px
}
Which works in FF5 and Opera but not in IE8.
Visit https://youtu.be/TQ32vqvMR80 OR
For example if parent contrainer has height: 200, then
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('url'),
fit: BoxFit.cover,
),
),
),
Basic subsetting:
album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
It Works , try out this :
InputStream in_s1 = TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
IntelliJ IDEA seems to have reorganized the configurations panel. Now one should go to Editor -> Color Scheme and click on the gears icon to import the theme they want from external .jar
files.
I look for a good way to deal with this issue and I am looking at the same question. Hopefully, this answer will be helping everyone who has the same problem likes me.
using (var client = new HttpClient())
{
var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetStringAsync(url);
// Parse JSON response.
....
}
reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi
Conda and pip install scikit-learn under ~/anaconda3/envs/$ENV/lib/python3.7/site-packages, however Jupyter notebook looks for the package under ~/anaconda3/lib/python3.7/site-packages.
Therefore, even when the environment is specified to conda, it does not work.
conda install -n $ENV scikit-learn # Does not work
pip 3 install the package under ~/anaconda3/lib/python3.7/site-packages.
After pip3, in a Jupyter notebook.
import sklearn
sklearn.__file__
~/anaconda3/lib/python3.7/site-packages/sklearn/init.py'
If you don't want to import anything, you can always write your own simple function as:
def RoundUP(num):
if num== int(num):
return num
return int(num + 1)
I've discovered that LEFT and RIGHT are not supported functions in Oracle. They are used in SQL Server, MySQL, and some other versions of SQL. In Oracle, you need to use the SUBSTR function. Here are simple examples:
LEFT ('Data', 2) = 'Da'
-> SUBSTR('Data',1,2) = 'Da'
RIGHT ('Data', 2) = 'ta'
-> SUBSTR('Data',-2,2) = 'ta'
Notice that a negative number counts back from the end.
As an alternative to using ExpectedException
attribute, I sometimes define two helpful methods for my test classes:
AssertThrowsException()
takes a delegate and asserts that it throws the expected exception with the expected message.
AssertDoesNotThrowException()
takes the same delegate and asserts that it does not throw an exception.
This pairing can be very useful when you want to test that an exception is thrown in one case, but not the other.
Using them my unit test code might look like this:
ExceptionThrower callStartOp = delegate(){ testObj.StartOperation(); };
// Check exception is thrown correctly...
AssertThrowsException(callStartOp, typeof(InvalidOperationException), "StartOperation() called when not ready.");
testObj.Ready = true;
// Check exception is now not thrown...
AssertDoesNotThrowException(callStartOp);
Nice and neat huh?
My AssertThrowsException()
and AssertDoesNotThrowException()
methods are defined on a common base class as follows:
protected delegate void ExceptionThrower();
/// <summary>
/// Asserts that calling a method results in an exception of the stated type with the stated message.
/// </summary>
/// <param name="exceptionThrowingFunc">Delegate that calls the method to be tested.</param>
/// <param name="expectedExceptionType">The expected type of the exception, e.g. typeof(FormatException).</param>
/// <param name="expectedExceptionMessage">The expected exception message (or fragment of the whole message)</param>
protected void AssertThrowsException(ExceptionThrower exceptionThrowingFunc, Type expectedExceptionType, string expectedExceptionMessage)
{
try
{
exceptionThrowingFunc();
Assert.Fail("Call did not raise any exception, but one was expected.");
}
catch (NUnit.Framework.AssertionException)
{
// Ignore and rethrow NUnit exception
throw;
}
catch (Exception ex)
{
Assert.IsInstanceOfType(expectedExceptionType, ex, "Exception raised was not the expected type.");
Assert.IsTrue(ex.Message.Contains(expectedExceptionMessage), "Exception raised did not contain expected message. Expected=\"" + expectedExceptionMessage + "\", got \"" + ex.Message + "\"");
}
}
/// <summary>
/// Asserts that calling a method does not throw an exception.
/// </summary>
/// <remarks>
/// This is typically only used in conjunction with <see cref="AssertThrowsException"/>. (e.g. once you have tested that an ExceptionThrower
/// method throws an exception then your test may fix the cause of the exception and then call this to make sure it is now fixed).
/// </remarks>
/// <param name="exceptionThrowingFunc">Delegate that calls the method to be tested.</param>
protected void AssertDoesNotThrowException(ExceptionThrower exceptionThrowingFunc)
{
try
{
exceptionThrowingFunc();
}
catch (NUnit.Framework.AssertionException)
{
// Ignore and rethrow any NUnit exception
throw;
}
catch (Exception ex)
{
Assert.Fail("Call raised an unexpected exception: " + ex.Message);
}
}
In 2020 I use Blob to make local copy of image, which browser will download as a file. You can test it on this site.
(function(global) {
const next = () => document.querySelector('.search-pagination__button-text').click();
const uuid = () => Math.random().toString(36).substring(7);
const toBlob = (src) => new Promise((res) => {
const img = document.createElement('img');
const c = document.createElement("canvas");
const ctx = c.getContext("2d");
img.onload = ({target}) => {
c.width = target.naturalWidth;
c.height = target.naturalHeight;
ctx.drawImage(target, 0, 0);
c.toBlob((b) => res(b), "image/jpeg", 0.75);
};
img.crossOrigin = "";
img.src = src;
});
const save = (blob, name = 'image.png') => {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.download = name;
a.click();
};
global.download = () => document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(async ({src}) => save(await toBlob(src), `${uuid()}.png`));
global.next = () => next();
})(window);
Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)
I am using jquery 1.7.2 while writing this.
here is one of the reference I found: http://bugs.jquery.com/ticket/8338
Here a full makefile example:
makefile
TARGET = prog
$(TARGET): main.o lib.a
gcc $^ -o $@
main.o: main.c
gcc -c $< -o $@
lib.a: lib1.o lib2.o
ar rcs $@ $^
lib1.o: lib1.c lib1.h
gcc -c -o $@ $<
lib2.o: lib2.c lib2.h
gcc -c -o $@ $<
clean:
rm -f *.o *.a $(TARGET)
explaining the makefile:
target: prerequisites
- the rule head$@
- means the target$^
- means all prerequisites$<
- means just the first prerequisitear
- a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
r
- replace files existing inside the archivec
- create a archive if not already existents
- create an object-file index into the archiveTo conclude: The static library under Linux is nothing more than a archive of object files.
main.c using the lib
#include <stdio.h>
#include "lib.h"
int main ( void )
{
fun1(10);
fun2(10);
return 0;
}
lib.h the libs main header
#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED
#include "lib1.h"
#include "lib2.h"
#endif
lib1.c first lib source
#include "lib1.h"
#include <stdio.h>
void fun1 ( int x )
{
printf("%i\n",x);
}
lib1.h the corresponding header
#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun1 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB1_H_INCLUDED */
lib2.c second lib source
#include "lib2.h"
#include <stdio.h>
void fun2 ( int x )
{
printf("%i\n",2*x);
}
lib2.h the corresponding header
#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun2 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB2_H_INCLUDED */
Using navigation controller to host a bar to dismiss the keyboard:
in the .h file:
UIBarButtonItem* dismissKeyboardButton;
in the .m file:
- (void)viewDidLoad {
dismissKeyboardButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyboard)];
}
-(void)textViewDidBeginEditing:(UITextView *)textView {
self.navigationItem.rightBarButtonItem = dismissKeyboardButton;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
self.navigationItem.rightBarButtonItem = dismissKeyboardButton;
}
-(void)dismissKeyboard {
[self.textField resignFirstResponder];
[self.textView resignFirstResponder];
//or replace this with your regular right button
self.navigationItem.rightBarButtonItem = nil;
}
If suppose the android device is not getting connected by android studio then download "PDANet+"(for all android devices).
Or also you can do these following steps:
Try this:
<add name="Access-Control-Allow-Origin" value="['URL1','URL2',...]" />
Try changing the security mode from "Transport" to "None".
<!-- Transport security mode requires IIS to have a
certificate configured for SSL. See readme for
more information on how to set this up. -->
<security mode="None">
>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']
To add to other answers. For me it was helpful to delete .mvn
directory and then add build.gradle
. New versions of IntelliJ will then automatically notice that you use Gradle.
Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.
$scope.printDiv = function (divName) {
var printContents = document.getElementById(divName).innerHTML;
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
popupWin.window.focus();
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
popupWin.onbeforeunload = function (event) {
popupWin.close();
return '.\n';
};
popupWin.onabort = function (event) {
popupWin.document.close();
popupWin.close();
}
} else {
var popupWin = window.open('', '_blank', 'width=800,height=600');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
popupWin.document.close();
}
popupWin.document.close();
return true;
}
If you want a pretty, multiline JSON with indentation then you can use JSON.stringify
with its 3rd argument:
JSON.stringify(value[, replacer[, space]])
For example:
var obj = {a:1,b:2,c:{d:3, e:4}};
JSON.stringify(obj, null, " ");
or
JSON.stringify(obj, null, 4);
will give you following result:
"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"
In a browser console.log(obj)
does even better job, but in a shell console (node.js) it doesn't.
I had a similar problem with Xcode 9.3, and setting "Module" under the "File Owner's" attribute inspector to the project module fixed this for me.
I've made a Python script for exporting Visual Studio Code settings into a single ZIP file:
https://gist.github.com/wonderbeyond/661c686b64cb0cabb77a43b49b16b26e
You can upload the ZIP file to external storage.
$ vsc-settings.py export
Exporting vsc settings:
created a temporary dump dir /tmp/tmpf88wo142
generating extensions list
copying /home/wonder/.config/Code/User/settings.json
copying /home/wonder/.config/Code/User/keybindings.json
copying /home/wonder/.config/Code/User/projects.json
copying /home/wonder/.config/Code/User/snippets
adding: snippets/ (stored 0%)
adding: snippets/go.json (deflated 56%)
adding: projects.json (deflated 67%)
adding: extensions.txt (deflated 40%)
adding: keybindings.json (deflated 81%)
adding: settings.json (deflated 59%)
VSC settings exported into /home/wonder/vsc-settings-2019-02-25-171337.zip
$ unzip -l /home/wonder/vsc-settings-2019-02-25-171337.zip
Archive: /home/wonder/vsc-settings-2019-02-25-171337.zip
Length Date Time Name
--------- ---------- ----- ----
0 2019-02-25 17:13 snippets/
942 2019-02-25 17:13 snippets/go.json
519 2019-02-25 17:13 projects.json
471 2019-02-25 17:13 extensions.txt
2429 2019-02-25 17:13 keybindings.json
2224 2019-02-25 17:13 settings.json
--------- -------
6585 6 files
PS: You may implement the vsc-settings.py import
subcommand for me.
Use forEach in combo with Object.entries().
const WALLPAPERS = [{
WALLPAPER_KEY: 'wallpaper.image',
WALLPAPER_VALID_KEY: 'wallpaper.image.valid',
}, {
WALLPAPER_KEY: 'lockscreen.image',
WALLPAPER_VALID_KEY: 'lockscreen.image.valid',
}];
WALLPAPERS.forEach((obj) => {
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} - ${value}`);
}
});
_x000D_
A alternative without glib dependency is pkg-config-lite.
Extract pkg-config.exe
from the archive and put it in your path.
Nowdays this package is available using chocolatey, then it could be installed whith
choco install pkgconfiglite
My similar issue was caused by having special characters (e.g. periods) in the selector.
The fix was to escape the special characters:
$("#dots\\.er\\.bad").val("mmmk");
This has been working for me:
If you try uploading the new file as a war file, with tomcat still running, it will attempt to expand it before it is all there. It will fail. Having failed, it will not try again. Thus, uploading a www file, then renaming it, allows the whole war file to be present before tomcat notices it.
Hint, don't forget to check that the war file's owner is tomcat (Use chown)
React / Latest JavaScript
onChange = { e => e.currentTarget.option[e.selectedIndex].text }
will give you exact value if values are inside a loop.
you can edit the javascrpit files dynamically in the Chrome debugger, under the Sources tab, however your changes will be lost if you refresh the page, to pause page loading before doing your changes, you will need to set a break point then reload the page and edit your changes and finally unpause the debugger to see your changes take effect.
Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar
or Activity
has it's own Toolbar, otherwise onCreateOptionsMenu
in fragment does not get called.
If you want to use standalone Toolbar
you either need to get activity and set your Toolbar
as support action bar with
(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)
which lets your fragment onCreateOptionsMenu to be called.
Other alternative is, you can inflate your Toolbar
's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU)
and item listener with
toolbar.setOnMenuItemClickListener {
// do something
true
}
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
It's Carriage Return
. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx
The following repeats the loop until the user has pressed the Return key.
while(ch!='\r')
{
ch=getche();
}
I still remember the first weeks of my programming courses and I totally understand how you feel. Here is the code that solves your problem. In order to learn from this answer, try to run it adding several 'print' in the loop, so you can see the progress of the variables.
import java.util.*;
import java.lang.*;
public class foo
{
public static void main(String[] args)
{
double[] alpha = new double[50];
int count = 0;
for (int i=0; i<50; i++)
{
// System.out.print("variable i = " + i + "\n");
if (i < 25)
{
alpha[i] = i*i;
}
else {
alpha[i] = 3*i;
}
if (count < 10)
{
System.out.print(alpha[i]+ " ");
}
else {
System.out.print("\n");
System.out.print(alpha[i]+ " ");
count = 0;
}
count++;
}
System.out.print("\n");
}
}
Edit 2019 (8 years later), Scala-IO being not very active, if any, Li Haoyi suggests his own library lihaoyi/os-lib
, that he presents below.
June 2019, Xavier Guihot mentions in his answer the library Using
, a utility for performing automatic resource management.
Edit (September 2011): since Eduardo Costa asks about Scala2.9, and since Rick-777 comments that scalax.IO commit history is pretty much non-existent since mid-2009...
Scala-IO has changed place: see its GitHub repo, from Jesse Eichar (also on SO):
The Scala IO umbrella project consists of a few sub projects for different aspects and extensions of IO.
There are two main components of Scala IO:
- Core - Core primarily deals with Reading and writing data to and from arbitrary sources and sinks. The corner stone traits are
Input
,Output
andSeekable
which provide the core API.
Other classes of importance areResource
,ReadChars
andWriteChars
.- File - File is a
File
(calledPath
) API that is based on a combination of Java 7 NIO filesystem and SBT PathFinder APIs.
Path
andFileSystem
are the main entry points into the Scala IO File API.
import scalax.io._
val output:Output = Resource.fromFile("someFile")
// Note: each write will open a new connection to file and
// each write is executed at the begining of the file,
// so in this case the last write will be the contents of the file.
// See Seekable for append and patching files
// Also See openOutput for performing several writes with a single connection
output.writeIntsAsBytes(1,2,3)
output.write("hello")(Codec.UTF8)
output.writeStrings(List("hello","world")," ")(Codec.UTF8)
Original answer (January 2011), with the old place for scala-io:
If you don't want to wait for Scala2.9, you can use the scala-incubator / scala-io library.
(as mentioned in "Why doesn't Scala Source close the underlying InputStream?")
See the samples
{ // several examples of writing data
import scalax.io.{
FileOps, Path, Codec, OpenOption}
// the codec must be defined either as a parameter of ops methods or as an implicit
implicit val codec = scalax.io.Codec.UTF8
val file: FileOps = Path ("file")
// write bytes
// By default the file write will replace
// an existing file with the new data
file.write (Array (1,2,3) map ( _.toByte))
// another option for write is openOptions which allows the caller
// to specify in detail how the write should take place
// the openOptions parameter takes a collections of OpenOptions objects
// which are filesystem specific in general but the standard options
// are defined in the OpenOption object
// in addition to the definition common collections are also defined
// WriteAppend for example is a List(Create, Append, Write)
file.write (List (1,2,3) map (_.toByte))
// write a string to the file
file.write("Hello my dear file")
// with all options (these are the default options explicitely declared)
file.write("Hello my dear file")(codec = Codec.UTF8)
// Convert several strings to the file
// same options apply as for write
file.writeStrings( "It costs" :: "one" :: "dollar" :: Nil)
// Now all options
file.writeStrings("It costs" :: "one" :: "dollar" :: Nil,
separator="||\n||")(codec = Codec.UTF8)
}
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
You can leverage Conditional Formatting
as follows.
H8
select Format > Conditional Formatting...=I8="Elementary"
Format...
and select the color you want etc.Add>>
and repeat steps 1 to 4Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?
If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.
The ON UPDATE
and ON DELETE
specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION
, CASCADE
, SET NULL
, and SET DEFAULT
.
If you delete one or more rows in the parent table, you can set one of the following actions:
ON DELETE NO ACTION
: SQL Server raises an error and rolls back the delete action on the row in the parent table.ON DELETE CASCADE
: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.ON DELETE SET NULL
: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.ON DELETE SET DEFAULT
: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified.
By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.If you update one or more rows in the parent table, you can set one of the following actions:
ON UPDATE NO ACTION
: SQL Server raises an error and rolls back the update action on the row in the parent table.ON UPDATE CASCADE
: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.ON UPDATE SET NULL
: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.ON UPDATE SET DEFAULT
: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.FOREIGN KEY (foreign_key_columns)
REFERENCES parent_table(parent_key_columns)
ON UPDATE <action>
ON DELETE <action>;
To iterate through the keys of an object, use a for .. in
loop:
for (var key in json_obj) {
if (json_obj.hasOwnProperty(key)) {
// do something with `key'
}
}
To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.
Removing a property of an object can be done by using the delete
keyword:
var someObj = {
"one": 123,
"two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }
Documentation:
You can simply add onended="myFunction()"
to your video tag.
<video onended="myFunction()">
...
Your browser does not support the video tag.
</video>
<script type='text/javascript'>
function myFunction(){
console.log("The End.")
}
</script>
The semantics of Having
To better understand having, you need to see it from a theoretical point of view.
A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.
The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.
Lets say your query is:
select a, b, count(*)
from Table
where c > 100
group by a, b
having count(*) > 10;
The evaluation of this query can be seen as the following steps:
You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).
In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:
SELECT list
FROM table
GROUP BY attrList
HAVING condition;
can be rewritten as:
SELECT list from (
SELECT listatt
FROM table
GROUP BY attrList) as Name
WHERE condition;
The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:
select a, b, count
from (select a, b, count(*) as count
from Table
where c > 100
group by a, b) as someName
where count > 10;
The solution you need
Your solution seems to be correct:
SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2
You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2
, which is that you wanted originally.
Best solution to your problem
I personally prefer a simpler cleaner solution:
SELECT sid, sname from
(SELECT sid from supplies
GROUP BY sid, pid
HAVING count(DISTINCT jid) >= 2
) AS T1
NATURAL JOIN
Supliers;
It will also be faster to execute, because the join is only done when needed, not all the times.
--dmg
Just adding the #include <math.h>
in c source file and -lm in Makefile at the end will work for me.
gcc -pthread -o p3 p3.c -lm
If you are using Eloquent the best solution is:
public function getFormattedPriceAttribute()
{
return number_format($this->attributes['price'], 2);
}
So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.
Nested classes are very useful for implementing internal details that should not be exposed. If you use Reflector to check classes like Dictionary<Tkey,TValue> or Hashtable you'll find some examples.
You could use the daff
package (which wraps the daff.js
library using the V8
package):
library(daff)
diff_data(data_ref = a2,
data = a1)
produces the following difference object:
Daff Comparison: ‘a2’ vs. ‘a1’
First 6 and last 6 patch lines:
@@ a b
1 ... ... ...
2 3 c
3 +++ 4 d
4 +++ 5 e
5 ... ... ...
6 ... ... ...
7 3 c
8 +++ 4 d
9 +++ 5 e
The tabular diff format is described here and should be pretty self-explanatory. The lines with +++
in the first column @@
are the ones which are new in a1
and not present in a2
.
The difference object can be used to patch_data()
, to store the difference for documentation purposes using write_diff()
or to visualize the difference using render_diff()
:
render_diff(
diff_data(data_ref = a2,
data = a1)
)
generates a neat HTML output:
This I guess may be self explanatory example:
function clickOn(elem /*bubble, cancelable*/) {
var bubble = (arguments.length > 1) ? arguments[1] : true;
var cancelable = (arguments.length == 3) ? arguments[2] : true;
var cle = document.createEvent("MouseEvent");
cle.initEvent("click", bubble, cancelable);
elem.dispatchEvent(cle);
}
Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.
One downside is that it is asynchronous.
Actually I want timestamp based shorter unique identifier, hence tried the below program.
It is guessable with nanosecond + ( endians.length * endians.length )
combinations.
public class TimStampShorterUUID {
private static final Character [] endians =
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
private static ThreadLocal<Character> threadLocal = new ThreadLocal<Character>();
private static AtomicLong iterator = new AtomicLong(-1);
public static String generateShorterTxnId() {
// Keep this as secure random when we want more secure, in distributed systems
int firstLetter = ThreadLocalRandom.current().nextInt(0, (endians.length));
//Sometimes your randomness and timestamp will be same value,
//when multiple threads are trying at the same nano second
//time hence to differentiate it, utilize the threads requesting
//for this value, the possible unique thread numbers == endians.length
Character secondLetter = threadLocal.get();
if (secondLetter == null) {
synchronized (threadLocal) {
if (secondLetter == null) {
threadLocal.set(endians[(int) (iterator.incrementAndGet() % endians.length)]);
}
}
secondLetter = threadLocal.get();
}
return "" + endians[firstLetter] + secondLetter + System.nanoTime();
}
public static void main(String[] args) {
Map<String, String> uniqueKeysTestMap = new ConcurrentHashMap<>();
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t3 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t4 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t5 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t6 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
Thread t7 = new Thread() {
@Override
public void run() {
while(true) {
String time = generateShorterTxnId();
String result = uniqueKeysTestMap.put(time, "");
if(result != null) {
System.out.println("failed! - " + time);
}
}
}
};
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
}
}
UPDATE: This code will work on single JVM, but we should think on distributed JVM, hence i am thinking two solutions one with DB and another one without DB.
with DB
Company name (shortname 3 chars) ---- Random_Number ---- Key specific redis COUNTER
(3 char) ------------------------------------------------ (2 char) ---------------- (11 char)
without DB
IPADDRESS ---- THREAD_NUMBER ---- INCR_NUMBER ---- epoch milliseconds
(5 chars) ----------------- (2char) ----------------------- (2 char) ----------------- (6 char)
will update you once coding is done.
Just add the attribute disabled
to the element (or use jQuery to do it for you). Disabled prevents the input from being focused or selected at all.
For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:
For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:
What you could do is to remove the default "extras" on the input
:
input.wide {display:block; width:100%;padding:0;border-width:0}
This will keep the input
inside its container.
Now if you do want the borders, wrap the input
in a div
, with the borders set on the div
(that way you can remove the display:block
from the input
too). Something like:
<div style="border:1px solid gray;">
<input type="text" class="wide" />
</div>
Edit:
Another option is to, instead of removing the style from the input
, compensate for it in the wrapped div
:
input.wide {width:100%;}
<div style="padding-right:4px;padding-left:1px;margin-right:2px">
<input type="text" class="wide" />
</div>
This will give you somewhat different results in different browsers, but they will not overlap the container. The values in the div depend on how large the border is on the input
and how much space you want between the input
and the border.
The cat <<EOF
syntax is very useful when working with multi-line text in Bash, eg. when assigning multi-line string to a shell variable, file or a pipe.
cat <<EOF
syntax usage in Bash:$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)
The $sql
variable now holds the new-line characters too. You can verify with echo -e "$sql"
.
$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF
The print.sh
file now contains:
#!/bin/bash
echo $PWD
echo /home/user
$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF
The b.txt
file contains bar
and baz
lines. The same output is printed to stdout
.
SELECT
B.Title, B.Edition, B.Year, B.Pages, B.Rating --from Books
, C.Category --from Categories
, P.Publisher --from Publishers
, W.LastName --from Writers
FROM Books B
JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID
If you want to initialize a vector with numeric values other than zero, use rep
n <- 10
v <- rep(0.05, n)
v
which will give you:
[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05
If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime()
.
pd.date_range('20110101','20110102',freq='H').to_pydatetime()
> [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
....
It also supports timezones:
pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()
[ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
datetime.datetime(2011, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
....
NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime()
on the entire series. You will need to call .to_pydatetime()
on each individual datetime64 using a list comprehension or something similar:
datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]
I made a simple implementation of this functionality using fontawesome, also taking advantage of the Select Extension, this covers select all, deselect some items, deselect all. https://codepen.io/pakogn/pen/jJryLo
HTML:
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>
<button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
<i class="far fa-square"></i>
</button>
</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>$320,800</td>
</tr>
<tr>
<td></td>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>$170,750</td>
</tr>
<tr>
<td></td>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>$86,000</td>
</tr>
<tr>
<td></td>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>$433,060</td>
</tr>
<tr>
<td></td>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>$162,700</td>
</tr>
<tr>
<td></td>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>$372,000</td>
</tr>
<tr>
<td></td>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>$137,500</td>
</tr>
<tr>
<td></td>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>$327,900</td>
</tr>
<tr>
<td></td>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>$205,500</td>
</tr>
<tr>
<td></td>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>$103,600</td>
</tr>
<tr>
<td></td>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>$90,560</td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
Javascript:
$(document).ready(function() {
let myTable = $('#example').DataTable({
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0,
}],
select: {
style: 'os', // 'single', 'multi', 'os', 'multi+shift'
selector: 'td:first-child',
},
order: [
[1, 'asc'],
],
});
$('#MyTableCheckAllButton').click(function() {
if (myTable.rows({
selected: true
}).count() > 0) {
myTable.rows().deselect();
return;
}
myTable.rows().select();
});
myTable.on('select deselect', function(e, dt, type, indexes) {
if (type === 'row') {
// We may use dt instead of myTable to have the freshest data.
if (dt.rows().count() === dt.rows({
selected: true
}).count()) {
// Deselect all items button.
$('#MyTableCheckAllButton i').attr('class', 'far fa-check-square');
return;
}
if (dt.rows({
selected: true
}).count() === 0) {
// Select all items button.
$('#MyTableCheckAllButton i').attr('class', 'far fa-square');
return;
}
// Deselect some items button.
$('#MyTableCheckAllButton i').attr('class', 'far fa-minus-square');
}
});
});
You're the victim of the classic deadlock. task.Wait()
or task.Result
is a blocking call in UI thread which causes the deadlock.
Don't block in the UI thread. Never do it. Just await it.
private async void Button_Click(object sender, RoutedEventArgs
{
var task = GetResponseAsync<MyObject>("my url");
var items = await task;
}
Btw, why are you catching the WebException
and throwing it back? It would be better if you simply don't catch it. Both are same.
Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse
method. StreamReader.ReadToEnd
is a blocking call --you should be using StreamReader.ReadToEndAsync
.
Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.
Your method should look something like the following when you've addressed all the above concerns.
public static async Task<List<T>> GetResponseAsync<T>(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
Stream stream = response.GetResponseStream();
StreamReader strReader = new StreamReader(stream);
string text = await strReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<List<T>>(text);
}
better solution is to use pool - ill handle this for you.
const pool = mysql.createPool({_x000D_
host: 'localhost',_x000D_
user: '--',_x000D_
database: '---',_x000D_
password: '----'_x000D_
});_x000D_
_x000D_
// ... later_x000D_
pool.query('select 1 + 1', (err, rows) => { /* */ });
_x000D_
A solution I tend to use more and more is this one:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # 1
for i, ax in enumerate(axs.ravel()): # 2
ax.set_title("Plot #{}".format(i)) # 3
axios.get
accepts a request config as the second parameter (not query string params).
You can use the params
config option to set query string params as follows:
axios.get('/api', {
params: {
foo: 'bar'
}
});
Floating will result in wrapping if space is not available.
You can use display:inline
and white-space:nowrap
to achieve this. Fiddle
<div id="container" style="white-space:nowrap">
<div id="image" style="display:inline;">
<img src="tree.png"/>
</div>
<div id="texts" style="display:inline; white-space:nowrap;">
A very long text(about 300 words)
</div>
</div>?
You need to have a rmiregistry
running before attempting to connect (register) a RMI service with it.
The LocateRegistry.createRegistry(2020)
method call creates and exports a registry on the specified port number.
See the documentation for LocateRegistry
//How about byte-ing it?
Number.prototype.isInt= function(){
return this== this>> 0;
}
I always feel kind of bad for bit operators in javascript-
they hardly get any exercise.
Well, the most likely difference is that you still have to do an actual lookup of localhost
somewhere.
If you use 127.0.0.1
, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname
will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.
Otherwise, the name has to be resolved. And there's no guarantee that your hosts
file will actually be used for that resolution (first, or at all) so localhost
may become a totally different IP address.
By that I mean that, on some systems, a local hosts
file can be bypassed. The host.conf
file controls this on Linux (and many other Unices).
I usually use this workaround:
try:
from .mymodule import myclass
except Exception: #ImportError
from mymodule import myclass
Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.