Clean Solution and Build again In my case, whatever the previous settings were blocking due to mismatch. I imported a new project and build it, tried changing versions and all. clean the solutions and build worked for me.
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json
. If you do this, certain CommonJS variables can't be used, including require
.
To fix this, remove "type": "module"
from your package.json
and make sure you don't have any files ending with .mjs
.
As mentioned in other answers, you can use set
to list all the environment variables or use
set [environment_variable]
to get a specific variable with its value.
set [environment_variable]=
can be used to remove a variable from the workspace.
I faced this problem
Forbidden You don't have permission to access /phpmyadmin/ on this server
Some help about this:
First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.
Follow these steps.
EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>
. For example:
git stash push -m welcome_cart app/views/cart/welcome.thtml
OLD ANSWER:
You can do that using git stash --patch
(or git stash -p
) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n
to skip the files that you don't want to stash, y
when you encounter the one that you want to stash, and q
to quit and leave the remaining hunks unstashed. a
will stash the shown hunk and the rest of the hunks in that file.
Not the most user-friendly approach, but it gets the work done if you really need it.
Old post, but this zombie is hitting VS 2017 (I haven't dug into why it's just "some" projects). In this case, it's not user permissions, rather IIS Express process is still using the files.
You'll see the icon in your task tray
rebuild
without this annoying "permission denied" message.This is also why "restarting Visual Studio" will "fix" the issue. Doing so, stops IIS Express.
Hth...
for what it's worth:
if( document.addEventListener ){
alert("you got IE9 or greater");
}
This successfully targets IE 9+ because the addEventListener
method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("[email protected]", "gmail_password",
"[email protected]", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
is_numeric
returns true
for decimals and integers. So if your user lazily enters 1
instead of 1.00
it will still return true
:
echo is_numeric(1); // true
echo is_numeric(1.00); // true
You may wish to convert the integer to a decimal with PHP, or let your database do it for you.
Here's a clue why an onchange() call might not fire your bound function:
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"
Just to add some clarification to the registry queries. They only list the instances of the matching bitness (32 or 64) for the current instance.
The actual registry key for 32-bit SQL instances on a 64-bit OS is:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
You can query this on a 64-bit instance to get all 32-bit instances as well. The 32-bit instance seems restricted to the Wow6432Node so cannot read the 64-bit registry tree.
The above is fine (as I said in comment) unless your WSDL is accessible with https:// too.
Here is my workaround for this:
Set you SSLSocketFactory as default:
HttpsURLConnection.setDefaultSSLSocketFactory(...);
For Apache CXF which I use you need also add these lines to your config:
<http-conf:conduit name="*.http-conduit">
<http-conf:tlsClientParameters useHttpsURLConnectionDefaultSslSocketFactory="true" />
<http-conf:conduit>
The ANSI escape sequences you're looking for are the Select Graphic Rendition subset. All of these have the form
\033[XXXm
where XXX
is a series of semicolon-separated parameters.
To say, make text red, bold, and underlined (we'll discuss many other options below) in C you might write:
printf("\033[31;1;4mHello\033[0m");
In C++ you'd use
std::cout<<"\033[31;1;4mHello\033[0m";
In Python3 you'd use
print("\033[31;1;4mHello\033[0m")
and in Bash you'd use
echo -e "\033[31;1;4mHello\033[0m"
where the first part makes the text red (31
), bold (1
), underlined (4
) and the last part clears all this (0
).
As described in the table below, there are a large number of text properties you can set, such as boldness, font, underlining, &c. (Isn't it silly that StackOverflow doesn't allow you to put proper tables in answers?)
Code | Effect | Note |
---|---|---|
0 | Reset / Normal | all attributes off |
1 | Bold or increased intensity | |
2 | Faint (decreased intensity) | Not widely supported. |
3 | Italic | Not widely supported. Sometimes treated as inverse. |
4 | Underline | |
5 | Slow Blink | less than 150 per minute |
6 | Rapid Blink | MS-DOS ANSI.SYS; 150+ per minute; not widely supported |
7 | [[reverse video]] | swap foreground and background colors |
8 | Conceal | Not widely supported. |
9 | Crossed-out | Characters legible, but marked for deletion. Not widely supported. |
10 | Primary(default) font | |
11–19 | Alternate font | Select alternate font n-10 |
20 | Fraktur | hardly ever supported |
21 | Bold off or Double Underline | Bold off not widely supported; double underline hardly ever supported. |
22 | Normal color or intensity | Neither bold nor faint |
23 | Not italic, not Fraktur | |
24 | Underline off | Not singly or doubly underlined |
25 | Blink off | |
27 | Inverse off | |
28 | Reveal | conceal off |
29 | Not crossed out | |
30–37 | Set foreground color | See color table below |
38 | Set foreground color | Next arguments are 5;<n> or 2;<r>;<g>;<b> , see below |
39 | Default foreground color | implementation defined (according to standard) |
40–47 | Set background color | See color table below |
48 | Set background color | Next arguments are 5;<n> or 2;<r>;<g>;<b> , see below |
49 | Default background color | implementation defined (according to standard) |
51 | Framed | |
52 | Encircled | |
53 | Overlined | |
54 | Not framed or encircled | |
55 | Not overlined | |
60 | ideogram underline | hardly ever supported |
61 | ideogram double underline | hardly ever supported |
62 | ideogram overline | hardly ever supported |
63 | ideogram double overline | hardly ever supported |
64 | ideogram stress marking | hardly ever supported |
65 | ideogram attributes off | reset the effects of all of 60-64 |
90–97 | Set bright foreground color | aixterm (not in standard) |
100–107 | Set bright background color | aixterm (not in standard) |
You've got this already!
The standards implementing terminal colours began with limited (4-bit) options. The table below lists the RGB values of the background and foreground colours used for these by a variety of terminal emulators:
Using the above, you can make red text on a green background (but why?) using:
\033[31;42m
In their book "Basic Color Terms: Their Universality and Evolution", Brent Berlin and Paul Kay used data collected from twenty different languages from a range of language families to identify eleven possible basic color categories: white, black, red, green, yellow, blue, brown, purple, pink, orange, and gray.
Berlin and Kay found that, in languages with fewer than the maximum eleven color categories, the colors followed a specific evolutionary pattern. This pattern is as follows:
This may be why story Beowulf only contains the colours black, white, and red. It may also be why the Bible does not contain the colour blue. Homer's Odyssey contains black almost 200 times and white about 100 times. Red appears 15 times, while yellow and green appear only 10 times. (More information here)
Differences between languages are also interesting: note the profusion of distinct colour words used by English vs. Chinese. However, digging deeper into these languages shows that each uses colour in distinct ways. (More information)
Generally speaking, the naming, use, and grouping of colours in human languages is fascinating. Now, back to the show.
Technology advanced, and tables of 256 pre-selected colours became available, as shown below.
Using these above, you can make pink text like so:
\033[38;5;206m #That is, \033[38;5;<FG COLOR>m
And make an early-morning blue background using
\033[48;5;57m #That is, \033[48;5;<BG COLOR>m
And, of course, you can combine these:
\033[38;5;206;48;5;57m
The 8-bit colours are arranged like so:
0x00-0x07: standard colors (same as the 4-bit colours)
0x08-0x0F: high intensity colors
0x10-0xE7: 6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 = r, g, b = 5)
0xE8-0xFF: grayscale from black to white in 24 steps
Now we are living in the future, and the full RGB spectrum is available using:
\033[38;2;<r>;<g>;<b>m #Select RGB foreground color
\033[48;2;<r>;<g>;<b>m #Select RGB background color
So you can put pinkish text on a brownish background using
\033[38;2;255;82;197;48;2;155;106;0mHello
Support for "true color" terminals is listed here.
Much of the above is drawn from the Wikipedia page "ANSI escape code".
Since I'm often in the position of trying to remember what colours are what, I have a handy script called: ~/bin/ansi_colours
:
#!/usr/bin/python
print "\\033[XXm"
for i in range(30,37+1):
print "\033[%dm%d\t\t\033[%dm%d" % (i,i,i+60,i+60);
print "\033[39m\\033[39m - Reset colour"
print "\\033[2K - Clear Line"
print "\\033[<L>;<C>H OR \\033[<L>;<C>f puts the cursor at line L and column C."
print "\\033[<N>A Move the cursor up N lines"
print "\\033[<N>B Move the cursor down N lines"
print "\\033[<N>C Move the cursor forward N columns"
print "\\033[<N>D Move the cursor backward N columns"
print "\\033[2J Clear the screen, move to (0,0)"
print "\\033[K Erase to end of line"
print "\\033[s Save cursor position"
print "\\033[u Restore cursor position"
print " "
print "\\033[4m Underline on"
print "\\033[24m Underline off"
print "\\033[1m Bold on"
print "\\033[21m Bold off"
This prints
You can try below Procedure Sql:
Create Procedure sp_ADD_USER_EXTRANET_CLIENT_INDEX_PHY
(
@ParLngId int output
)
as
Begin
-- Min will return only 1 value, if 'Extranet Client' is found
-- IsNull will take care of 'Extranet Client' not found, returning 0 instead of Null
-- But T_Param must be a Master Table with ParStrNom having a Unique Index, if so Min is not reqd at all
-- But 'PHY', 'Extranet Client' suggests that Unique Key has 2 columns, not just ParStrNom
SET @ParLngId = IsNull((Select Min (ParLngId) from T_Param where ParStrNom = 'Extranet Client'), 0);
-- Nothing changed below
if (@ParLngId = 0)
Begin
Insert Into T_Param values ('PHY', 'Extranet Client', Null, Null, 'T', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL)
SET @ParLngId = @@IDENTITY
End
Return @ParLngId
End
NOTE: For glassfish Server login via admin console -> Configurations -> server-config -> JVM-settings. * Remember to check Enable checkbox for Debug. Now Note the address, this address will be used in port of eclipse Remote Java Application Debug.Check the snap shot in glassfish server here
This way is good and conventional:
17:04:59@itqx|~
qx>source <(curl -Ls http://192.168.80.154/cent74/just4Test) Lord Jesus Loves YOU
Remote script test...
Param size: 4
---------
17:19:31@node7|/var/www/html/cent74
arch>cat just4Test
echo Remote script test...
echo Param size: $#
You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.
std::vector
uses the heap. Geez, what a waste that would be just for the sake of a const
sanity-check. The point of std::vector
is dynamic growth at run-time, not any old syntax checking that should be done at compile-time. If you're not going to grow then create a class to wrap a normal array.
#include <stdio.h>
template <class Type, size_t MaxLength>
class ConstFixedSizeArrayFiller {
private:
size_t length;
public:
ConstFixedSizeArrayFiller() : length(0) {
}
virtual ~ConstFixedSizeArrayFiller() {
}
virtual void Fill(Type *array) = 0;
protected:
void add_element(Type *array, const Type & element)
{
if(length >= MaxLength) {
// todo: throw more appropriate out-of-bounds exception
throw 0;
}
array[length] = element;
length++;
}
};
template <class Type, size_t Length>
class ConstFixedSizeArray {
private:
Type array[Length];
public:
explicit ConstFixedSizeArray(
ConstFixedSizeArrayFiller<Type, Length> & filler
) {
filler.Fill(array);
}
const Type *Array() const {
return array;
}
size_t ArrayLength() const {
return Length;
}
};
class a {
private:
class b_filler : public ConstFixedSizeArrayFiller<int, 2> {
public:
virtual ~b_filler() {
}
virtual void Fill(int *array) {
add_element(array, 87);
add_element(array, 96);
}
};
const ConstFixedSizeArray<int, 2> b;
public:
a(void) : b(b_filler()) {
}
void print_items() {
size_t i;
for(i = 0; i < b.ArrayLength(); i++)
{
printf("%d\n", b.Array()[i]);
}
}
};
int main()
{
a x;
x.print_items();
return 0;
}
ConstFixedSizeArrayFiller
and ConstFixedSizeArray
are reusable.
The first allows run-time bounds checking while initializing the array (same as a vector might), which can later become const
after this initialization.
The second allows the array to be allocated inside another object, which could be on the heap or simply the stack if that's where the object is. There's no waste of time allocating from the heap. It also performs compile-time const checking on the array.
b_filler
is a tiny private class to provide the initialization values. The size of the array is checked at compile-time with the template arguments, so there's no chance of going out of bounds.
I'm sure there are more exotic ways to modify this. This is an initial stab. I think you can pretty much make up for any of the compiler's shortcoming with classes.
It's a bit old post but I recently ran into this issue. All I did was deleted all the nuget packages from packages folder and restored it. I was able to build the solution successfully. Hopefully helpful to someone.
If you want to bind to the redis port from your nodejs
container you will have to expose that port in the redis
container:
version: '2'
services:
nodejs:
build:
context: .
dockerfile: DockerFile
ports:
- "4000:4000"
links:
- redis
redis:
build:
context: .
dockerfile: Dockerfile-redis
expose:
- "6379"
The expose
tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.
https://docs.docker.com/compose/compose-file/#expose
The ports
tag will be mapping the host port with the container port HOST:CONTAINER
If your code is ES7 based (or upper versions):
channelArray.includes('three'); //will return true or false
If not, for example you are using IE with no babel transpile:
channelArray.indexOf('three') !== -1; //will return true or false
the indexOf
method will return the position the element has into the array, because of that we use !==
different from -1 if the needle is found at the first position.
The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.
To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:
String inlinedText = text.replaceAll("\\R", " ");
I have encountered the same problem and found out the solution.
You may look within the first server response and see if the server sent you a cookie.
To check if the server sent you a cookie, you can use HttpURLConnection#getHeaderFields() and look for headers named "Set-Cookie".
If existing, here's the solution for your problem. 100% Working for this case!
+1 if it worked for you.
In very simple terms, I like to think about it like this:
real
is the actual amount of time it took to run the command (as if you had timed it with a stopwatch)
user
and sys
are how much 'work' the CPU
had to do to execute the command. This 'work' is expressed in units of time.
Generally speaking:
user
is how much work the CPU
did to run to run the command's codesys
is how much work the CPU
had to do to handle 'system overhead' type tasks (such as allocating memory, file I/O, ect.) in order to support the running commandSince these last two times are counting 'work' done, they don't include time a thread might have spent waiting (such as waiting on another process or for disk I/O to finish).
real
, however, is a measure of actual runtime and not 'work', so it does include any time spent waiting.
I would like to mention that there's exception (not only) for 404 by default provided by Spring. See Spring documentation for details. So if you do not need your own exception you can simply do this:
@RequestMapping(value = "/**", method = RequestMethod.GET)
public ModelAndView show() throws NoSuchRequestHandlingMethodException {
if(something == null)
throw new NoSuchRequestHandlingMethodException("show", YourClass.class);
...
}
Using yaml folded style. The indention in each line will be ignored. A line break will be inserted at the end.
Key: >
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with only a single carriage return appended to the end.
http://symfony.com/doc/current/components/yaml/yaml_format.html
You can use the "block chomping indicator" to eliminate the trailing line break, as follows:
Key: >-
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with NO carriage returns.
In either case, each line break is replaced by a space.
There are other control tools available as well (for controlling indentation for example).
Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.
I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.
--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.
' **row** **Column1** **Column2**
' 1 Title1 Data 1 for title 1
' 2 Data 2 for title 1
' 3 Data 3 for title 1
' 4 Title2 Data 1 for title 2
' 5 Data 2 for title 2
' 6 Data 3 for title 2
' 7 Title 3 Data 1 for title 3
----- CopyDown code ----------
Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Set strtCell = ActiveCell
FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
' MsgBox Lastrow
Range(Lastrow).Formula = strtCell.Formula
Range(Lastrow).End(xlDown).Select
End Sub
this worked:
Date date = null;
String dateStr = rs.getString("doc_date");
if (dateStr != null) {
date = dateFormat.parse(dateStr);
}
using SimpleDateFormat.
They can't be initialised inside the class, but they can be initialised outside the class, in a source file:
// inside the class
class Thing {
static string RE_ANY;
static string RE_ANY_RELUCTANT;
};
// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";
Update
I've just noticed the first line of your question - you don't want to make those functions static
, you want to make them const
. Making them static
means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const
simply means that they can't modify any members, but can still access them.
If you want all of the values, use this:
dict_name_goes_here.values()
XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.
Replace version code with appropriate code of library version will solve your issue, like this:
<integer name="google_play_services_version"> <versioncode> </integer>
A simple addClass and removeClass will do the trick on what you need..
$('#change').on('click', function() {
$('div').each(function() {
if($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
});
Seee fiddle
I recommend you to learn jquery first before using.
public Point2D(Point2D point) : this(point.X, point.Y) { }
In addition to previous post you can have
<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />
Jsf 2.0
Well, this might be counter-intuitive but I solved this adding esnext
to my lib
.
{
"compilerOptions": {
"lib": [
"esnext"
],
"target": "es5",
}
}
The FIX, as suggested by the compiler is to
Try changing the
lib
compiler option to es2015 or later.
When you run the code on windows machine, firewall prompts it to allow network access, allow the network access and it will work, if it does not prompts, go to firewall settings > allow an app through firewall and select your python.exe and allow network access.
You don't need to parse the string, it's defined as a string already.
Just do:
private static String getStringInput (String prompt) {
String input = EZJ.getUserInput(prompt);
return input;
}
Remove style attribute from div using J query:
$("#TableDiv").removeAttr("style");
Add style to div using J query:
$("#TableDiv").attr("style", "display: none;");
Add style using html:
<div class="row" id="TableDiv" style="display: none;">
</div>
Hope it will helpful :)
I had the same error and just wanted to share my solution. In turned out that the minified version of popper had the code in the same line as the comment and so the entire code was commented out. I just pressed enter after the actual comment so the code was on a new line and then it worked fine.
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
The easy way is to use:
Random rand = new Random(System.currentTimeMillis());
This is the best way to generate Random
numbers.
Eager Execution is enabled by default, so just call .numpy()
on the Tensor object.
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
a.numpy()
# array([[1, 2],
# [3, 4]], dtype=int32)
b.numpy()
# array([[2, 3],
# [4, 5]], dtype=int32)
tf.multiply(a, b).numpy()
# array([[ 2, 6],
# [12, 20]], dtype=int32)
See NumPy Compatibility for more. It is worth noting (from the docs),
Numpy array may share memory with the Tensor object. Any changes to one may be reflected in the other.
Bold emphasis mine. A copy may or may not be returned, and this is an implementation detail based on whether the data is in CPU or GPU (in the latter case, a copy has to be made from GPU to host memory).
But why am I getting AttributeError: 'Tensor' object has no attribute 'numpy'
?.
A lot of folks have commented about this issue, there are a couple of possible reasons:
tf.compat.v1.enable_eager_execution()
to enable it, or see below.If Eager Execution is disabled, you can build a graph and then run it through tf.compat.v1.Session
:
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
out = tf.multiply(a, b)
out.eval(session=tf.compat.v1.Session())
# array([[ 2, 6],
# [12, 20]], dtype=int32)
See also TF 2.0 Symbols Map for a mapping of the old API to the new one.
Simplest way to delete a database say blog:
> use blog
switched to db blog
> db.dropDatabase();
{ "dropped" : "blog", "ok" : 1 }
SELECT * FROM employee
ORDER BY salary
DESC LIMIT 1 OFFSET 2;
The easy way to revert a group of commits on shared repository (that people use and you want to preserve the history) is to use git revert
in conjunction with git rev-list
. The latter one will provide you with a list of commits, the former will do the revert itself.
There are two ways to do that. If you want the revert multiple commits in a single commit use:
for i in `git rev-list <first-commit-sha>^..<last-commit-sha>`; do git revert --no-commit $i; done
this will revert a group of commits you need, but leave all the changes on your working tree, you should commit them all as usual afterward.
Another option is to have a single commit per reverted change:
for i in `git rev-list <first-commit-sha>^..<last-commit-sha>`; do git revert --no-edit -s $i; done
For instance, if you have a commit tree like
o---o---o---o---o---o--->
fff eee ddd ccc bbb aaa
to revert the changes from eee to bbb, run
for i in `git rev-list eee^..bbb`; do git revert --no-edit -s $i; done
Yes, it is valid.
As for making it work with functors as well, the usual solution is something like this instead:
template <typename F>
void doOperation(F f)
{
int temp=0;
f(temp);
std::cout << "Result is " << temp << std::endl;
}
which can now be called as either:
doOperation(add2);
doOperation(add3());
The problem with this is that if it makes it tricky for the compiler to inline the call to add2
, since all the compiler knows is that a function pointer type void (*)(int &)
is being passed to doOperation
. (But add3
, being a functor, can be inlined easily. Here, the compiler knows that an object of type add3
is passed to the function, which means that the function to call is add3::operator()
, and not just some unknown function pointer.)
My Problem was that I was not in the correct git directory that I just cloned.
You can use the DateTime.Add() method to add the time to the date.
DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);
You can also create your timespan by parsing a String, if that is what you need to do.
Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.
Look at the exception:
No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency
This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:
UserDaoImpl
with @Component
or @Repository
, and let the component scan do the work for you, exactly as you have done with UserService
.UserBoImpl
.Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.
To create a patch with both modified & new files (staged) you can run:
git diff HEAD > file_name.patch
You may try this, Following are few examples on how files are generated. Tool -- https://sourceforge.net/projects/csvtohive/?source=directory
Select a CSV file using Browse and set hadoop root directory ex: /user/bigdataproject/
Tool Generates Hadoop script with all csv files and following is a sample of generated Hadoop script to insert csv into Hadoop
#!/bin/bash -v
hadoop fs -put ./AllstarFull.csv /user/bigdataproject/AllstarFull.csv
hive -f ./AllstarFull.hive
hadoop fs -put ./Appearances.csv /user/bigdataproject/Appearances.csv
hive -f ./Appearances.hive
hadoop fs -put ./AwardsManagers.csv /user/bigdataproject/AwardsManagers.csv
hive -f ./AwardsManagers.hive
Sample of generated Hive scripts
CREATE DATABASE IF NOT EXISTS lahman;
USE lahman;
CREATE TABLE AllstarFull (playerID string,yearID string,gameNum string,gameID string,teamID string,lgID string,GP string,startingPos string) row format delimited fields terminated by ',' stored as textfile;
LOAD DATA INPATH '/user/bigdataproject/AllstarFull.csv' OVERWRITE INTO TABLE AllstarFull;
SELECT * FROM AllstarFull;
Thanks Vijay
Additionally, if you're building a ReSTful API, browser leakage and http referer issues are mostly mitigated as the client may not be a browser and you may not have people clicking links.
If this is the case I'd recommend oAuth2 login to obtain a bearer token. In which case the only sensitive data would be the initial credentials...which should probably be in a post request anyway
My proposal:
$dir="C:\temp\"
get-childitem $dir -file -Rec | group Directory | where Name -eq $dir | select Name, @{N='Size';E={(($_.Group.Length | measure -Sum).Sum / 1MB)}}
Currently, ExplorerCanvas is the only option to emulate HTML5 canvas for IE6, 7, and 8. You're also right about its performance, which is pretty poor.
I found a particle simulatior that benchmarks the difference between true HTML5 canvas handling in Google Chrome, Safari, and Firefox, vs ExplorerCanvas in IE. The results show that the major browsers that do support the canvas tag run about 20 to 30 times faster than the emulated HTML5 in IE with ExplorerCanvas.
I doubt that anyone will go through the effort of creating an alternative because 1) excanvas.js is about as cleanly coded as it gets and 2) when IE9 is released all of the major browsers will finally support the canvas object. Hopefully, We'll get IE9 within a year
Eric @ www.webkrunk.com
Using MAMP I changed the host=localhost
to host=127.0.0.1
. But a new issue came "connection refused"
Solved this by putting 'port' => '8889'
, in 'Datasources' => [
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client. In one of my xsd it was defined as below
<xs:import schemaLocation="" namespace="http://MultiChoice.PaymentService/DataContracts" />
Where the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.
<xs:import schemaLocation="multichoice.paymentservice.DataContracts.xsd" namespace="http://MultiChoice.PaymentService/DataContracts" />
In addition to the generic device (or "Any iOS Device" in newer versions of Xcode) mentioned in the other answers, it is possible that the "Archive" action is not selected for the current target in the scheme.
To view and edit at the current scheme, select Product > Schemes > Edit Scheme...
(Cmd+<), then make sure that the "Archive" action is checked in the line corresponding to the desired target.
In the image below, Archive
is not checked and the Archive
action is greyed out in the Product
menu. Checking the indicated checkbox fixed the issue for me.
I would be tempted to use grepl
, which should give all the lines with matches and can be generalised for arbitrary strings.
mydata_2 <- read.table(textConnection("
sex age height_seca1 height_chad1 height_DL weight_alog1
1 F 19 1800 1797 180 70.0
2 F 19 1682 1670 167 69.0
3 F 21 1765 1765 178 80.0
4 F 21 1829 1833 181 74.0
5 F 21 1706 1705 170 103.0
6 F 18 1607 1606 160 76.0
7 F 19 1578 1576 156 50.0
8 F 19 1577 1575 156 61.0
9 F 21 1666 1665 166 52.0
10 F 17 1710 1716 172 65.0
11 F 28 1616 1619 161 65.5
12 F 22 1648 1644 165 57.5
13 F 19 1569 1570 155 55.0
14 F 19 1779 1777 177 55.0
15 M 18 1773 1772 179 70.0
16 M 18 1816 1809 181 81.0
17 M 19 1766 1765 178 77.0
18 M 19 1745 1741 174 76.0
19 M 18 1716 1714 170 71.0
20 M 21 1785 1783 179 64.0
21 M 19 1850 1854 185 71.0
22 M 31 1875 1880 188 95.0
23 M 26 1877 1877 186 105.5
24 M 19 1836 1837 185 100.0
25 M 18 1825 1823 182 85.0
26 M 19 1755 1754 174 79.0
27 M 26 1658 1658 165 69.0
28 M 20 1816 1818 183 84.0
29 M 18 1755 1755 175 67.0"),
sep = " ", header = TRUE)
which(grepl(1578, mydata_2$height_seca1))
The output is:
> which(grepl(1578, mydata_2$height_seca1))
[1] 7
>
[Edit] However, as pointed out in the comments, this will capture much more than the string 1578 (e.g. it also matches for 21578 etc) and thus should be used only if you are certain that you the length of the values you are searching will not be larger than the four characters or digits shown here.
And subsetting as per the other answer also works fine:
mydata_2[mydata_2$height_seca1 == 1578, ]
sex age height_seca1 height_chad1 height_DL weight_alog1
7 F 19 1578 1576 156 50
>
If you're looking for several different values, you could put them in a vector and then use the %in%
operator:
look.for <- c(1578, 1658, 1616)
> mydata_2[mydata_2$height_seca1 %in% look.for, ]
sex age height_seca1 height_chad1 height_DL weight_alog1
7 F 19 1578 1576 156 50.0
11 F 28 1616 1619 161 65.5
27 M 26 1658 1658 165 69.0
>
Use find. Seriously, it is the best way because then you can really see what files it's operating on:
find . -name "*.sql" -exec grep -H "slow" {} \;
Note, the -H is mac-specific, it shows the filename in the results.
You need to read and write document.cookie
if (document.cookie.indexOf("visited=") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
To serve all requests from a Spring app as well as /favicon.ico and the JSP files from /WEB-INF/jsp/* that Spring's AbstractUrlBasedView will request you can just remap the jsp servlet and default servlet:
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/jsp/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/favicon.ico</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
We can't rely on the *.jsp url-pattern on the standard mapping for the jsp servlet because the path pattern '/*' is matched before any extension mapping is checked. Mapping the jsp servlet to a deeper folder means it's matched first. Matching '/favicon.ico' exactly happens before path pattern matching. Deeper path matches will work, or exact matches, but no extension matches can make it past the '/*' path match. Mapping '/' to default servlet doesn't appear to work. You'd think the exact '/' would beat the '/*' path pattern on springapp.
The above filter solution doesn't work for forwarded/included JSP requests from the application. To make it work I had to apply the filter to springapp directly, at which point the url-pattern matching was useless as all requests that go to the application also go to its filters. So I added pattern matching to the filter and then learned about the 'jsp' servlet and saw that it doesn't remove the path prefix like the default servlet does. That solved my problem, which was not exactly the same but common enough.
You can define your title programatically using setTitle
within your Activity
, this method can accept either a String
or an ID defined in your values/strings.xml
file. Example:
public class YourActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
setTitle(R.string.your_title);
setContentView(R.layout.main);
}
}
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
Like this :
var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
Here's a nice fun LINQ example.
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
That's the other way around. You should write:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
click: function() {
// Handle click...
}
}, "td");
//form/descendant::input[@type='submit']
For future reference, in Visual Studio you can try placing the cursor in the method name (for example, WriteLine) and press F1 to pull up help on that context. Digging around should then find you String.Format()
in this case, with lots of helpful information.
Note that highlighting a selection (for example, double-clicking or doing a drag-select) and hitting F1 only does a non-context string search (which tends to suck at finding anything helpful), so make sure you just position the cursor anywhere inside the word without highlighting it.
This is also helpful for documentation on classes and other types.
The Css vertical-align property should help you out here:
vertical-align: bottom;
is what you need for your smaller header :)
return false
in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
I have 3 fields to fetch from Oracle Database,Which is for Forex and Currency Application.
SELECT BUY.RATE FROM FRBU.CURRENCY WHERE CURRENCY.MARKET =10 AND CURRENCY.CODE IN (‘USD’, ’AUD’, ‘SGD’)
My problem and the solution
I have a 32 bit third party dll which i have installed in 2008 R2 machine which is 64 bit.
I have a wcf service created in .net 4.5 framework which calls the 32 bit third party dll for process. Now i have build property set to target 'any' cpu and deployed it to the 64 bit machine.
when i tried to invoke the wcf service got error "80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG"
Now i used ProcMon.exe to trace the com registry issue and identified that the process is looking for the registry entry at HKLM\CLSID and HKCR\CLSID where there is no entry.
Came to know that Microsoft will not register the 32 bit com components to the paths HKLM\CLSID, HKCR\CLSID in 64 bit machine rather it places the entry in HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID paths.
Now the conflict is 64 bit process trying to invoke 32 bit process in 64 bit machine which will look for the registry entry in HKLM\CLSID, HKCR\CLSID. The solution is we have to force the 64 bit process to look at the registry entry at HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID.
This can be achieved by configuring the wcf service project properties to target to 'X86' machine instead of 'Any'.
After deploying the 'X86' version to the 2008 R2 server got the issue "System.BadImageFormatException: Could not load file or assembly"
Solution to this badimageformatexception is setting the 'Enable32bitApplications' to 'True' in IIS Apppool properties for the right apppool.
I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.
I personally do this in my header files:
// class-declaration
// inline-method-declarations
I don't like mixing the code for the methods in with the class as I find it a pain to look things up quickly.
I would not put ALL of the methods in the header file. The compiler will (normally) not be able to inline virtual methods and will (likely) only inline small methods without loops (totally depends on the compiler).
Doing the methods in the class is valid... but from a readablilty point of view I don't like it. Putting the methods in the header does mean that, when possible, they will get inlined.
if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1}) Then
""
else
"and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}
An Alternative Solution to the above
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
color: Colors.white,
child: ...
)
You can use BorderRadius.only() to customize the corners you wish to manage.
Worked perfectly for me to calculate SQL database size in SQL Server 2012
exec sp_spaceused
If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces
still configured for eth0.
Diagnose:
ethtool -i eth0
Cannot get driver information: no such device
Find your interfaces:
ls /sys/class/net
eth1 eth2 lo
Fix it:
Edit /etc/networking/interfaces
and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)
:%s/eth0/eth2/g
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application
if you will just output the answer in the Range("E2")
.
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P
Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.
You can check the package leaps
and in particular the function regsubsets()
functions for model selection. As stated in the documentation:
Model selection by exhaustive search, forward or backward stepwise, or sequential replacement
Create an XML-file in a res/drawable
folder. For instance, "btn_image.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_state_1"
android:state_pressed="true"
android:state_selected="true"/>
<item android:drawable="@drawable/bg_state_2"
android:state_pressed="true"
android:state_selected="false"/>
<item android:drawable="@drawable/bg_state_selected"
android:state_selected="true"/>
<item android:drawable="@drawable/bg_state_deselected"/>
</selector>
You can combine those files you like, for instance, change "bg_state_1" to "bg_state_deselected" and "bg_state_2" to "bg_state_selected".
In any of those files you can write something like:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ccdd00"/>
<corners android:radius="5dp"/>
</shape>
Create in a layout file an ImageView or ImageButton with the following attributes:
<ImageView
android:id="@+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
android:adjustViewBounds="true"
android:background="@drawable/btn_image"
android:padding="10dp"
android:scaleType="fitCenter"
android:src="@drawable/star"/>
Later in code:
image.setSelected(!image.isSelected());
What version of jQuery-UI are you using? I've tested the following with 1.6r6, 1.7 and 1.7.1 and it works:
//Set DatePicker to October 3, 2008
$('#dateselector').datepicker("setDate", new Date(2008,9,03) );
Recommendations for resources in order to handle HTTP GET requests for /resources/** by offering static resources in the ${webappRoot}/resources directory is to simply add the following line in the configuration file:
<resources mapping="/resources/**" location="/resources/" />
It has worked for me.
Sources (Spring in Action book and http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html)
I wanted to add that if you are using a shared drive, enclose the path in double quotes and keep the backslashes. This is what worked for me:
$cd /path/to/"\\\share\users\username\My Documents\mydirectory\"
Some googling led me to the following post:
http://www.developerweb.net/forum/showthread.php?t=3434
The code provided in the post is in C, but it shouldn't be too hard to rewrite it to Java.
copy your certificates inside
/etc/pki/ca-trust/source/anchors/
then run the following command
update-ca-trust
Use 'this' keyword to access variable. This worked for me
var uemail = localStorage.getItem("useremail");
if (typeof this.uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
I think you can also use a scaffold to do the white background. Here's some piece of code that may help.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Testing',
home: new Scaffold(
//Here you can set what ever background color you need.
backgroundColor: Colors.white,
),
);
}
}
Hope this helps .
If you need to query on the list, then store it in a table.
If you always want the list, you could store it as a delimited list in a column. Even in this case, unless you have VERY specific reasons not to, store it in a lookup table.
If your model is called BlogPost, it would be:
BlogPost.all.map(&:destroy)
I had the same problem and I believe the answer really is no. See Miško's comment and some discussion in the group.
Angular can track that all of the function calls it makes to manipulate the DOM are complete, but since those functions could trigger async logic that's still updating the DOM after they return, Angular couldn't be expected to know about it. Any callback Angular gives might work sometimes, but wouldn't be safe to rely on.
We solved this heuristically with a setTimeout, as you did.
(Please keep in mind that not everyone agrees with me - you should read the comments on the links above and see what you think.)
I think what you need might be simply:
\d( \w)?
Note that your regex would have worked too if it was written as \d \w|\d
instead of \d|\d \w
.
This is because in your case, once the regex matches the first option, \d
, it ceases to search for a new match, so to speak.
function unique(arrayName)_x000D_
{_x000D_
var newArray=new Array();_x000D_
label: for(var i=0; i<arrayName.length;i++ )_x000D_
{ _x000D_
for(var j=0; j<newArray.length;j++ )_x000D_
{_x000D_
if(newArray[j]==arrayName[i]) _x000D_
continue label;_x000D_
}_x000D_
newArray[newArray.length] = arrayName[i];_x000D_
}_x000D_
return newArray;_x000D_
}_x000D_
_x000D_
var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);_x000D_
var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);_x000D_
var union = unique(arr1.concat(arr2));_x000D_
console.log(union);
_x000D_
I know this post is old, but if any of you still looking for a simpler solution.
#container .left,
#container .right {
display: inline-block;
}
#container .left {
width: 20%;
float: left;
}
#container .right {
width: 80%;
float: right;
}
You need to define height of ul or your div and set overflow equals to auto as below:
<ul style="width: 300px; height: 200px; overflow: auto">
<li>text</li>
<li>text</li>
you can also set environment variables in the script itself, rather than passing region_name parameter
os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'
case sensitivity may matter.
In my case the problem was I implemented the same library twice in my build.gradle file. Removing the duplicate entry worked for me. And did not even needed to clean, rebuild the project.
Permission denied
In order to run a script the file must have an executable permission bit set.
In order to fully understand Linux file permissions you can study the documentation for the chmod
command. chmod, an abbreviation of change mode, is the command that is used to change the permission settings of a file.
To read the chmod documentation for your local system , run man chmod
or info chmod
from the command line. Once read and understood you should be able to understand the output of running ...
ls -l foo.sh
... which will list the READ, WRITE and EXECUTE permissions for the file owner, the group owner and everyone else who is not the file owner or a member of the group to which the file belongs (that last permission group is sometimes referred to as "world" or "other")
Here's a summary of how to troubleshoot the Permission Denied error in your case.
$ ls -l foo.sh # Check file permissions of foo
-rw-r--r-- 1 rkielty users 0 2012-10-21 14:47 foo.sh
^^^
^^^ | ^^^ ^^^^^^^ ^^^^^
| | | | |
Owner| World | |
| | Name of
Group | Group
Name of
Owner
Owner has read and write access rw but the - indicates that the executable permission is missing
The chmod
command fixes that. (Group and other only have read permission set on the file, they cannot write to it or execute it)
$ chmod +x foo.sh # The owner can set the executable permission on foo.sh
$ ls -l foo.sh # Now we see an x after the rw
-rwxr-xr-x 1 rkielty users 0 2012-10-21 14:47 foo.sh
^ ^ ^
foo.sh is now executable as far as Linux is concerned.
Using sudo results in Command not found
When you run a command using sudo you are effectively running it as the superuser or root.
The reason that the root user is not finding your command is likely that the PATH
environment variable for root does not include the directory where foo.sh
is located. Hence the command is not found.
The PATH environment variable contains a list of directories which are searched for commands. Each user sets their own PATH variable according to their needs. To see what it is set to run
env | grep ^PATH
Here's some sample output of running the above env
command first as an ordinary user and then as the root user using sudo
rkielty@rkielty-laptop:~$ env | grep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
rkielty@rkielty-laptop:~$ sudo env | grep ^PATH
[sudo] password for rkielty:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin
Note that, although similar, in this case the directories contained in the PATH the non-privileged user (rkielty) and the super user are not the same.
The directory where foo.sh
resides is not present in the PATH variable of the root user, hence the command not found error.
I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html
Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.
NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using *
should be more future-proof.
Wrap the Like box with a div:
<div id="likebox-wrapper">
<iframe src="..."></iframe> <!-- likebox code -->
</div>
and add this to your css file:
#likebox-wrapper * {
width: 100% !important;
}
These are 2 methods that can be used to take a value from the selected row
/// <summary>
/// Take a value from a the selected row of a DataGrid
/// ATTENTION : The column's index is absolute : if the DataGrid is reorganized by the user,
/// the index must change
/// </summary>
/// <param name="dGrid">The DataGrid where we take the value</param>
/// <param name="columnIndex">The value's line index</param>
/// <returns>The value contained in the selected line or an empty string if nothing is selected</returns>
public static string getDataGridValueAt(DataGrid dGrid, int columnIndex)
{
if (dGrid.SelectedItem == null)
return "";
string str = dGrid.SelectedItem.ToString(); // Take the selected line
str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Delete useless characters
if (columnIndex < 0 || columnIndex >= str.Split(',').Length) // case where the index can't be used
return "";
str = str.Split(',')[columnIndex].Trim();
str = str.Split('=')[1].Trim();
return str;
}
/// <summary>
/// Take a value from a the selected row of a DataGrid
/// </summary>
/// <param name="dGrid">The DataGrid where we take the value.</param>
/// <param name="columnName">The column's name of the searched value. Be careful, the parameter must be the same as the shown on the dataGrid</param>
/// <returns>The value contained in the selected line or an empty string if nothing is selected or if the column doesn't exist</returns>
public static string getDataGridValueAt(DataGrid dGrid, string columnName)
{
if (dGrid.SelectedItem == null)
return "";
for (int i = 0; i < columnName.Length; i++)
if (columnName.ElementAt(i) == '_')
{
columnName = columnName.Insert(i, "_");
i++;
}
string str = dGrid.SelectedItem.ToString(); // Get the selected Line
str = str.Replace("}", "").Trim().Replace("{", "").Trim(); // Remove useless characters
for (int i = 0; i < str.Split(',').Length; i++)
if (str.Split(',')[i].Trim().Split('=')[0].Trim() == columnName) // Check if the searched column exists in the dataGrid.
return str.Split(',')[i].Trim().Split('=')[1].Trim();
return str;
}
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
Here is my experience:-
(Does not require any third-party library)
Short answer: You can't.
You will have to use border-image
property and a few images.
I'm running MacOS Mojave (10.14.6) and to get MySQL to recognize my config file, I had to place it in /usr/local/mysql-5.7.26-macos10.14-x86_64/etc/my.cnf. Also I have a symbolic link pointing to it from /usr/local/@mysql/etc/my.cnf .
I was trying to turn off sql_mode=only_full_group_by and setting that option in the config file was the only way I could get the setting to persist across sessions. The contents of the config file are:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION
I'm using the native install of MySQL, not the Homebrew set up.
I caught this error a few days ago.
IN my case it was because I was using a Transaction on a Singleton.
.Net does not work well with Singleton as stated above.
My solution was this:
public class DbHelper : DbHelperCore
{
public DbHelper()
{
Connection = null;
Transaction = null;
}
public static DbHelper instance
{
get
{
if (HttpContext.Current is null)
return new DbHelper();
else if (HttpContext.Current.Items["dbh"] == null)
HttpContext.Current.Items["dbh"] = new DbHelper();
return (DbHelper)HttpContext.Current.Items["dbh"];
}
}
public override void BeginTransaction()
{
Connection = new SqlConnection(Entity.Connection.getCon);
if (Connection.State == System.Data.ConnectionState.Closed)
Connection.Open();
Transaction = Connection.BeginTransaction();
}
}
I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class
I fixed it by removing the top-level __init__.py
in the parent folder of my sources.
When you have 'NA' values in the column, then
sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)
You could use grep to pull them out.
grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' file.txt
They're completely different things.
A join allows you to relate similar data in different tables.
A union returns the results of two different queries as a single recordset.
equals
if hashCode
differs.hashCode
if (obj1 == obj2)
.hashCode
and/or equals
just to iterate - you're not comparing objectsAnswer Given by rushUp Is correct but this will be more convenient
for (let [index, val] of array.entries() || []) {
// your code goes here
}
If you don't care about the path to the executable file -
ldd `which <executable>` # back quotes, not single quotes
I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;
SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;
Result: Paddy O'Reilly
This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file
There is a much easier way!
You can easily create an attached DocumentXaml
(or DocumentRTF
) property which will allow you to bind the RichTextBox
's document. It is used like this, where Autobiography
is a string property in your data model:
<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />
Voila! Fully bindable RichTextBox
data!
The implementation of this property is quite simple: When the property is set, load the XAML (or RTF) into a new FlowDocument
. When the FlowDocument
changes, update the property value.
This code should do the trick:
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
public class RichTextBoxHelper : DependencyObject
{
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
obj.SetValue(DocumentXamlProperty, value);
}
public static readonly DependencyProperty DocumentXamlProperty =
DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
PropertyChangedCallback = (obj, e) =>
{
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
var xaml = GetDocumentXaml(richTextBox);
var doc = new FlowDocument();
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)),
DataFormats.Xaml);
// Set the document
richTextBox.Document = doc;
// When the document changes update the source
range.Changed += (obj2, e2) =>
{
if (richTextBox.Document == doc)
{
MemoryStream buffer = new MemoryStream();
range.Save(buffer, DataFormats.Xaml);
SetDocumentXaml(richTextBox,
Encoding.UTF8.GetString(buffer.ToArray()));
}
};
}
});
}
The same code could be used for TextFormats.RTF or TextFormats.XamlPackage. For XamlPackage you would have a property of type byte[]
instead of string
.
The XamlPackage format has several advantages over plain XAML, especially the ability to include resources such as images, and it is more flexible and easier to work with than RTF.
It is hard to believe this question sat for 15 months without anyone pointing out the easy way to do this.
Can you not use like this?
@Query("SELECT DISTINCT name FROM people p (nolock) WHERE p.name NOT IN (:myparam)")
List<String> findNonReferencedNames(@Param("myparam")List<String> names);
P.S. I write queries in SQL Server 2012 a lot and using nolock
in server is a good practice, you can ignore nolock
if a local db is used.
Seems like your db name is not being mapped correctly (after you've updated your question)
You can also "sample" the same number of items in your data frame with something like this:
nr<-dim(M)[1]
random_M = M[sample.int(nr),]
To summarize what was mentioned by Breno above
Say you have a variable with a path to a file
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)
returns the string 'myfile.py'
and
os.path.dirname(path)
returns the string '/home/User/Desktop'
(without a trailing slash '/')
These functions are used when you have to get the filename/directory name given a full path name.
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'
you just have myfile.py
), os.path.dirname(path)
returns an empty string.
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (textBox1.Text == listBox1.Items[i].ToString())
{
jeElement = true;
break;
}
}
if (jeElement)
{
label1.Text = "je element";
}
else
{
label1.Text = "ni element";
}
textBox1.ResetText();
textBox1.Focus();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt == true && e.KeyCode == Keys.A)
{
buttonCheck.PerformClick();
}
}
}
Yet another option: https://github.com/stefanhaustein/expressionparser
I have implemented this to have a simple but flexible option to permit both:
The TreeBuilder linked above is part of a CAS demo package that does symbolic derivation. There is also a BASIC interpreter example and I have started to build a TypeScript interpreter using it.
One possible way is to use .map()
method:
var all = $(".mbox").map(function() {
return this.innerHTML;
}).get();
console.log(all.join());
DEMO: http://jsfiddle.net/Y4bHh/
N.B. Please don't use document.write
. For testing purposes console.log
is the best way to go.
Set
html, body {
height: 100%;
}
Wrap the entire content before the footer in a div.
.wrapper {
height:auto !important;
min-height:100%;
}
You can adjust min-height as you like based on how much of the footer you want to show in the bottom of the browser window. If set it to 90%, 10% of the footer will show before scrolling.
Wrapping your list of objects with another object containing a property that matches the name of the parameter which is expected by the MVC controller works. The important bit being the wrapper around the object list.
$(document).ready(function () {
var employeeList = [
{ id: 1, name: 'Bob' },
{ id: 2, name: 'John' },
{ id: 3, name: 'Tom' }
];
var Employees = {
EmployeeList: employeeList
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Employees/Process',
data: Employees,
success: function () {
$('#InfoPanel').html('It worked!');
},
failure: function (response) {
$('#InfoPanel').html(response);
}
});
});
public void Process(List<Employee> EmployeeList)
{
var emps = EmployeeList;
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
I'll second the notion of just using your own javascript, but for something a bit more sophisticated you might look at dojo data. Haven't used it but it looks like it gives you roughly the kind of query interface you're looking for.
$timestamp='2014-11-21 16:38:00';
list($date,$time)=explode(' ',$timestamp);
// just time
preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];
No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame()
with the parens).
Instead, to create a DataFrame where each series is a column,
series
, and df = pd.concat(series, axis=1)
Something like:
series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)
In ur script page...
$('.a-middle').css('margin-top', function () {
return ($(window).height() - $(this).height()) / 2
});
Use a-middle class in the Div...
<div class="a-middle">
char arr[3] = "bo";
The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.
For new MySQL 5.6 family you need to install php5-mysqlnd, not php5-mysql.
Remove this version of the mysql driver
sudo apt-get remove php5-mysql
And install this instead
sudo apt-get install php5-mysqlnd
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MAX_MEMORY_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer
And use <form enctype="multipart/form-data">
and use <input type="file">
in the html
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Use the latest version of Task Parallel Library (TPL), according to .Net version. Have to choose the correct modules of TPL for different purposes.
The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a HashMap<String,String>
and HashMap<Foo,Bar>
for any other Foo
and Bar
.
Use @SuppressWarnings("unchecked")
and hold your nose. Oh, and campaign for reified generics in Java :)
If you used the Visual Studio 2012 ASP.NET Web Forms Application template then you would have gotten that reference. I'm assuming it's the one you would get via Nuget instead of the framework System.Data.Entity reference.
As one would expect, WebKit's support of tel:
extends to the Android mobile browser as well - FYI
If you don't feel like aliassing you can also just prefix the tablenames.
This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need Furthermore, only explicitly name the fields you want to have.
SELECT
news.id, news.title, news.author, news.posted,
users.id, users.name, users.registered
FROM
news
LEFT JOIN
users
ON
news.user = user.id
I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.
But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.
But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.
For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.
Here is a simple video recording example using the MediaRecorder:
public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
private void initRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
}
It's from my book: Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets
Also, do not forget to include these permissions in manifest:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
There's also npm install https://github.com/{USER}/{REPO}/tarball/{BRANCH}
to use a different branch.
should you pass it in this way :
public ActionResult CreatePerson(int id) //controller
window.location.href = "@Url.Action("CreatePerson", "Person",new { @id = 1});
In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0
His
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")
Corrected
let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")
Update: Corrected map rendering algorithm, added more illustrations, changed formating.
Perhaps the advantage for the "zig-zag" technique for mapping the tiles to the screen can be said that the tile's x
and y
coordinates are on the vertical and horizontal axes.
"Drawing in a diamond" approach:
By drawing an isometric map using "drawing in a diamond", which I believe refers to just rendering the map by using a nested for
-loop over the two-dimensional array, such as this example:
tile_map[][] = [[...],...]
for (cellY = 0; cellY < tile_map.size; cellY++):
for (cellX = 0; cellX < tile_map[cellY].size cellX++):
draw(
tile_map[cellX][cellY],
screenX = (cellX * tile_width / 2) + (cellY * tile_width / 2)
screenY = (cellY * tile_height / 2) - (cellX * tile_height / 2)
)
Advantage:
The advantage to the approach is that it is a simple nested for
-loop with fairly straight forward logic that works consistently throughout all tiles.
Disadvantage:
One downside to that approach is that the x
and y
coordinates of the tiles on the map will increase in diagonal lines, which might make it more difficult to visually map the location on the screen to the map represented as an array:
However, there is going to be a pitfall to implementing the above example code -- the rendering order will cause tiles that are supposed to be behind certain tiles to be drawn on top of the tiles in front:
In order to amend this problem, the inner for
-loop's order must be reversed -- starting from the highest value, and rendering toward the lower value:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
for (j = tile_map[i].size; j >= 0; j--): // Changed loop condition here.
draw(
tile_map[i][j],
x = (j * tile_width / 2) + (i * tile_width / 2)
y = (i * tile_height / 2) - (j * tile_height / 2)
)
With the above fix, the rendering of the map should be corrected:
"Zig-zag" approach:
Advantage:
Perhaps the advantage of the "zig-zag" approach is that the rendered map may appear to be a little more vertically compact than the "diamond" approach:
Disadvantage:
From trying to implement the zig-zag technique, the disadvantage may be that it is a little bit harder to write the rendering code because it cannot be written as simple as a nested for
-loop over each element in an array:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
if i is odd:
offset_x = tile_width / 2
else:
offset_x = 0
for (j = 0; j < tile_map[i].size; j++):
draw(
tile_map[i][j],
x = (j * tile_width) + offset_x,
y = i * tile_height / 2
)
Also, it may be a little bit difficult to try to figure out the coordinate of a tile due to the staggered nature of the rendering order:
Note: The illustrations included in this answer were created with a Java implementation of the tile rendering code presented, with the following int
array as the map:
tileMap = new int[][] {
{0, 1, 2, 3},
{3, 2, 1, 0},
{0, 0, 1, 1},
{2, 2, 3, 3}
};
The tile images are:
tileImage[0] ->
A box with a box inside.tileImage[1] ->
A black box.tileImage[2] ->
A white box.tileImage[3] ->
A box with a tall gray object in it.A Note on Tile Widths and Heights
The variables tile_width
and tile_height
which are used in the above code examples refer to the width and height of the ground tile in the image representing the tile:
Using the dimensions of the image will work, as long as the image dimensions and the tile dimensions match. Otherwise, the tile map could be rendered with gaps between the tiles.
To do downcasting in Java, and avoid run-time exceptions, take a reference of the following code:
if (animal instanceof Dog) {
Dog dogObject = (Dog) animal;
}
Here, Animal is the parent class and Dog is the child class.
instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not.
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
Try
this.dataset.id
$("#list li").on('click', function() {_x000D_
alert( this.dataset.id );_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
<li data-id="id-40" class="win">_x000D_
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />_x000D_
</a>_x000D_
</li>_x000D_
</ul>
_x000D_
Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:
private string ComputeHash(Guid input)
{
byte[] source = input.ToByteArray();
var encoder = new SHA256Managed();
byte[] encoded = encoder.ComputeHash(source);
return Convert.ToBase64String(encoded);
}
In CreateAsync
:
var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());
ReceiveAsync
:
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Guid token;
if (Guid.TryParse(context.Token, out token))
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
{
context.SetTicket(ticket);
}
}
}
Here is to share something I found on __import__
and importlib
while trying to solve this problem.
I am using Python 3.7.3.
When I try to get to the class d
in module a.b.c
,
mod = __import__('a.b.c')
The mod
variable refer to the top namespace a
.
So to get to the class d
, I need to
mod = getattr(mod, 'b') #mod is now module b
mod = getattr(mod, 'c') #mod is now module c
mod = getattr(mod, 'd') #mod is now class d
If we try to do
mod = __import__('a.b.c')
d = getattr(mod, 'd')
we are actually trying to look for a.d
.
When using importlib
, I suppose the library has done the recursive getattr
for us. So, when we use importlib.import_module
, we actually get a handle on the deepest module.
mod = importlib.import_module('a.b.c') #mod is module c
d = getattr(mod, 'd') #this is a.b.c.d
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.
ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?
My approach would be:
/// <summary>
/// Appends CSS Class seprated by a space character
/// </summary>
/// <param name="control">Target control</param>
/// <param name="cssClass">CSS class name to append</param>
public static void AppendCss(HtmlGenericControl control, string cssClass)
{
// Ensure CSS class is definied
if (string.IsNullOrEmpty(cssClass)) return;
// Append CSS class
if (string.IsNullOrEmpty(control.Attributes["class"]))
{
// Set our CSS Class as only one
control.Attributes["class"] = cssClass;
}
else
{
// Append new CSS class with space as seprator
control.Attributes["class"] += (" " + cssClass);
}
}
It's just docker pull busybox
, are you using an up to date version of the docker
client. I think they stopped supporting clients lower than 1.5.
Incidentally that curl works for me:
$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]
Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.
Unfortunately, you're out of luck here.
There is inherit
to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).
You will have to revert style changes manually:
div { color: green; }
form div { color: red; }
form div div.content { color: green; }
If you have access to the markup, you can add several classes to style precisely what you need:
form div.sub { color: red; }
form div div.content { /* remains green */ }
Edit: The CSS Working Group is up to something:
div.content {
all: revert;
}
No idea, when or if ever this will be implemented by browsers.
Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)
Edit 3: default
was renamed to revert
.
I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint
DOM API to find the element that Selenium wanted me to click on instead:
element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
"return document.elementFromPoint(arguments[0], arguments[1]);",
loc['x'],
loc['y'])
element_to_click.click()
I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.
class elements_not_to_be_animated(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
elements = EC._find_elements(driver, self.locator)
# :animated is an artificial jQuery selector for things that are
# currently animated by jQuery.
return driver.execute_script(
'return !jQuery(arguments[0]).filter(":animated").length;',
elements)
except StaleElementReferenceException:
return False
Here is a minimal, contrived example.
console.log( window.location.href ); // whatever your current location href is
window.history.replaceState( {} , 'foo', '/foo' );
console.log( window.location.href ); // oh, hey, it replaced the path with /foo
There is more to replaceState()
but I don't know what exactly it is that you want to do with it.
Try looking at Double.TryParse() if you are using .NET 1.1/2.0/3.0/3.5/4.0/4.5
In addition to romkyns's great answer.. here is some relevant documentation/examples.
DOM Elements have a native .click()
method.
The
HTMLElement.click()
method simulates a mouse click on an element.When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an
<a>
element to initiate navigation as if a real mouse-click had been received. (mdn reference)
Relevant W3 documentation.
A few examples..
You can access a specific DOM element from a jQuery object: (example)
$('a')[0].click();
You can use the .get()
method to retrieve a DOM element from a jQuery object: (example)
$('a').get(0).click();
As expected, you can select the DOM element and call the .click()
method. (example)
document.querySelector('a').click();
It's worth pointing out that jQuery is not required to trigger a native .click()
event.
I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable
/*
Double click behaves as one single click
"It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable."
That way we have to check what is the event that is being executed at any sequence.
*/
var totalClicks = 1;
$('#elementId').on('click dblclick', function (e) {
if (e.type == "dblclick") {
console.log("e.type1: " + e.type);
return;
} else if (e.type == "click") {
if (totalClicks > 1) {
console.log("e.type2: " + e.type);
totalClicks = 1;
return;
} else {
console.log("e.type3: " + e.type);
++totalClicks;
}
//execute the code you want to execute
}
});
This worked for me:
tar -zcvf target.tar.gz target/ --exclude="target/backups" --exclude="target/cache"
I do not use github plugin, but from the introduction page, it is more or less like gerrit-trigger plugin.
You can install git plugin, which can help you checkout your projects, if you want to include multi-projects in one jenkins job, just add Repository into your job.
The way to do this without use of plugins is to make a subclass of google's OverlayView() method.
https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView
You make a custom function and apply it to the map.
function Label() {
this.setMap(g.map);
};
Now you prototype your subclass and add HTML nodes:
Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
this.MySpecialDiv = document.createElement('div');
this.MySpecialDiv.className = 'MyLabel';
this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers
}
you also have to implement remove and draw functions as stated in the API docs, or this won't work.
Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
$('.myLabel')
.css({
'top' : position.y + 'px',
'left' : position.x + 'px'
})
;
}
That's the gist of it, you'll have to do some more work in your specific implementation.
You can set the background color of a button using the getRed function.
Let's assume you have:
Then, place the following code in the function where you want to change the background color of your UIButton
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0)
if color.getRed(&r, green: &g, blue: &b, alpha: &a){
button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}
(\S*)\s*\((.*?)\)\s*(\*?)
(\S*) picks up anything which is NOT whitespace
\s* 0 or more whitespace characters
\( a literal open parenthesis
(.*?) anything, non-greedy so stops on first occurrence of...
\) a literal close parenthesis
\s* 0 or more whitespace characters
(\*?) 0 or 1 occurances of literal *
FWIW, Microsoft Visual C++ does support try,finally and it has historically been used in MFC apps as a method of catching serious exceptions that would otherwise result in a crash. For example;
int CMyApp::Run()
{
__try
{
int i = CWinApp::Run();
m_Exitok = MAGIC_EXIT_NO;
return i;
}
__finally
{
if (m_Exitok != MAGIC_EXIT_NO)
FaultHandler();
}
}
I've used this in the past to do things like save backups of open files prior to exit. Certain JIT debugging settings will break this mechanism though.
For me the issues was I had multiple clients in my project and I am pretty sure this is perfectly alright, but I deleted all the client for that project and created a new one and all started working for me ( Got this idea fro WP_SMTP plugin help support forum) I am not able to find out that link for reference
Move the -h and specify that mydir is a directory
attrib /S /D /L -H mydir\*.*
I fixed this issue by adding a slash
at the beginning to my relative path
clear()
will go through the underlying Array and set each entry to null;
removeAll(collection)
will go through the ArrayList checking for collection and remove(Object)
it if it exists.
I would imagine that clear()
is way faster then removeAll because it's not comparing, etc.
My minimal approach
For converting negative number to positive & vice-versa
var num = -24;_x000D_
num -= num*2;_x000D_
console.log(num)_x000D_
// result = 24
_x000D_
$number=1200.0000;
str_replace('.00', '',number_format($number, 2, '.', ''));
Output will be: 1200
Just to contribute,
there is a linecache
module in python, here is two links that can help.
linecache module documentation
linecache source code
In a sense, you can "dump" a whole file into its cache , and read it with linecache.cache data from class.
import linecache as allLines
## have in mind that fileName in linecache behaves as any other open statement, you will need a path to a file if file is not in the same directory as script
linesList = allLines.updatechache( fileName ,None)
for i,x in enumerate(lineslist): print(i,x) #prints the line number and content
#or for more info
print(line.cache)
#or you need a specific line
specLine = allLines.getline(fileName,numbOfLine)
#returns a textual line from that number of line
For additional info, for error handling, you can simply use
from sys import exc_info
try:
raise YourError # or some other error
except Exception:
print(exc_info() )
Similar answers:
Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview
app.directive("myDir", function($compile) {
return {
priority:1001, // compiles first
terminal:true, // prevent lower priority directives to compile after it
compile: function(el) {
el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
el.attr('ng-click', 'fxn()');
var fn = $compile(el);
return function(scope){
fn(scope);
};
}
};
});
ngClick
at all:A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview
app.directive("myDir", function($parse) {
return {
compile: function(tElm,tAttrs){
var exp = $parse('fxn()');
return function (scope,elm){
elm.bind('click',function(){
exp(scope);
});
};
}
};
});
var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();
W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".
Hence I assume you're testing on IE8 or below.
For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.
HTML:
<div class="myWickedClass">
<span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>
CSS:
.myWickedClass{
padding: 0 5px 0 0;
background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
font: normal 11px Verdana, Helvetica, sans-serif;
color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
padding-left: 6px;
background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
padding-right: 5px;
}
You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.
So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.
The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input>
to then use background images like in the previous example.
Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE
This code worked for me. Easy fix but probably not a preferred way.
public void onClick (View v) {
createdDialog(0).show(); // Instead of showDialog(0);
}
protected Dialog createdDialog(int id) {
// Your code
}
You can't use multiple structural directive on same element. Wrap your element in ng-template
and use one structural directive there
You can't format the Date
itself. You can only get the formatted result in String
. Use SimpleDateFormat
as mentioned by others.
Moreover, most of the getter methods in Date
are deprecated.
I was getting this error even though I already had (actually because I already had) Schema::defaultStringLength(191); in my AppServiceProvider.php file.
The reason is because I was trying to set a string value in one of my migrations to a value higher than 191:
Schema::create('order_items', function (Blueprint $table) {
$table->primary(['order_id', 'product_id', 'attributes']);
$table->unsignedBigInteger('order_id');
$table->unsignedBigInteger('product_id');
$table->string('attributes', 1000); // This line right here
$table->timestamps();
});
Removing the 1000 or setting it to 191 solved my issue.
Edit 2020: This does not work any more. It seems so, that the browser vendors patched this out. Because the most browsers rely on chromium, it might be in its core.
Old answer: You can also hook mouseenter (this event is fired after page reload, when the mousecursor is inside the page). Extending Corrupted's code should do the trick:
var x = null;_x000D_
var y = null;_x000D_
_x000D_
document.addEventListener('mousemove', onMouseUpdate, false);_x000D_
document.addEventListener('mouseenter', onMouseUpdate, false);_x000D_
_x000D_
function onMouseUpdate(e) {_x000D_
x = e.pageX;_x000D_
y = e.pageY;_x000D_
console.log(x, y);_x000D_
}_x000D_
_x000D_
function getMouseX() {_x000D_
return x;_x000D_
}_x000D_
_x000D_
function getMouseY() {_x000D_
return y;_x000D_
}
_x000D_
You can also set x and y to null on mouseleave-event. So you can check if the user is on your page with it's cursor.
Since the long history of Apache Solr, I think one strength of the Solr is its ecosystem. There are many Solr plugins for different types of data and purposes.
Search platform in the following layers from bottom to top:
Reference article : Enterprise search
Seems like regular UNIQUE CONSTRAINT :)
CREATE TABLE example (
a integer,
b integer,
c integer,
UNIQUE (a, c));
More here
The Connector 6.7.x does not integrate the native data provider anymore. For "Visual Studio 2012" or less, you have to install "MySQL for Visual Studio". If you are using "Visual Studio 2013" there is no possibility to integrate MySQL for the "Entity Framework" yet. A solution should be available on 10/2013!
This is also a possible solution
$relative = '/relative/path/to/script/';
$absolute = __DIR__. '/../' .$relative;
int[] a = { 2, 1, 3, 4, 5, 2 };
int[] b = { 2, 1, 3, 4, 5, 2 };
bool ans = true;
if(a.Length != b.Length)
{
ans = false;
}
else
{
for (int i = 0; i < a.Length; i++)
{
if( a[i] != b[i])
{
ans = false;
}
}
}
string str = "";
if(ans == true)
{
str = "Two Arrays are Equal";
}
if (ans == false)
{
str = "Two Arrays are not Equal";
}
//--------------Or You can write One line of Code-------------
var ArrayEquals = a.SequenceEqual(b); // returns true
I know it's an old thread, but I landed here several times via Google and think no given answer is really satisfying yet. Try using one of the following functions:
EDIT: As I'm getting some likes on this old thread, I wanna share an updated solution as well (basically putting my two previous functions together and automatically deciding whether it's a bar or hbar plot):
def label_bars(ax, bars, text_format, **kwargs):
"""
Attaches a label on every bar of a regular or horizontal bar chart
"""
ys = [bar.get_y() for bar in bars]
y_is_constant = all(y == ys[0] for y in ys) # -> regular bar chart, since all all bars start on the same y level (0)
if y_is_constant:
_label_bar(ax, bars, text_format, **kwargs)
else:
_label_barh(ax, bars, text_format, **kwargs)
def _label_bar(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
"""
max_y_value = ax.get_ylim()[1]
inside_distance = max_y_value * 0.05
outside_distance = max_y_value * 0.01
for bar in bars:
text = text_format.format(bar.get_height())
text_x = bar.get_x() + bar.get_width() / 2
is_inside = bar.get_height() >= max_y_value * 0.15
if is_inside:
color = "white"
text_y = bar.get_height() - inside_distance
else:
color = "black"
text_y = bar.get_height() + outside_distance
ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)
def _label_barh(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
Note: label always outside. otherwise it's too hard to control as numbers can be very long
"""
max_x_value = ax.get_xlim()[1]
distance = max_x_value * 0.0025
for bar in bars:
text = text_format.format(bar.get_width())
text_x = bar.get_width() + distance
text_y = bar.get_y() + bar.get_height() / 2
ax.text(text_x, text_y, text, va='center', **kwargs)
Now you can use them for regular bar plots:
fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)
or for horizontal bar plots:
fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)
Here is a simple wrapper solution for this:
var fs = require('fs')
function getFileRealPath(s){
try {return fs.realpathSync(s);} catch(e){return false;}
}
Usage:
Example:
var realPath,pathToCheck='<your_dir_or_file>'
if( (realPath=getFileRealPath(pathToCheck)) === false){
console.log('file/dir not found: '+pathToCheck);
} else {
console.log('file/dir exists: '+realPath);
}
Make sure you use === operator to test if return equals false. There is no logical reason that fs.realpathSync() would return false under proper working conditions so I think this should work 100%.
I would prefer to see a solution that does not does not generate an Error and resulting performance hit. From an API perspective, fs.exists() seems like the most elegant solution.
I just would like to add how it may happen that a reference breaks.
On my system (Windows 7 64-bit), when a BSOD happens, some of the stored reference files (most likely currently opened/being written into when BSOD happened) are overwritten with NULL
characters (ASCII 0).
As others mentioned, to fix it, it's enough to just delete those invalid reference files and re-fetch or re-pull the repository.
Error: cannot lock ref 'refs/remotes/origin/some/branch': unable to resolve reference 'refs/remotes/origin/some/branch': reference broken
Solution: delete the file %repo_root%/.git/refs/remotes/origin/some/branch
"Thinking in C++" by Bruce Eckel
When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p
flag to mkdir
... Please update your Dockerfile with
RUN mkdir -p ...
I tested this and it's correct.