As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2))
.
If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
print $item->title;
}
For create circle button you are this codes:
.circle-right-btn {
display: block;
height: 50px;
width: 50px;
border-radius: 50%;
border: 1px solid #fefefe;
margin-top: 24px;
font-size:22px;
}
_x000D_
<input class="circle-right-btn" type="submit" value="<">
_x000D_
#sort dataframe by col
sort.df <- with(df, df[order(sortbythiscolumn) , ])
#can also sort by more than one variable: sort by col1 and then by col2
sort2.df <- with(df, df[order(col1, col2) , ])
#sort in reverse order
sort2.df <- with(df, df[order(col1, -col2) , ])
document.location.reload()
stores the position, see in the docs.
Add additional true
parameter to force reload, but without restoring the position.
document.location.reload(true)
MDN docs:
The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.
Download source code from here (Open Pdf from url in Android Programmatically)
MainActivity.java
package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressBar progressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
}
}
Thanks!
To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).
file://///server/path/to/file.txt
Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:
For security purposes, Mozilla applications block links to local files (and directories) from remote files.
And less directly, from Google:
Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.
The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.
Use jquery to add a style override in the <head>
:
$('<style>.someClass {color: red;} input::-webkit-outer-spin-button: {display: none;}</style>')
.appendTo('head');
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s
on a Unix terminal.
If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.
If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.
While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:
makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer
(^ = allow batch command-line to wrap line)
This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).
The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.
Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:
certutil -user -addstore Root MyCA.cer
makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
-sky signature ^
-ic MyCA.cer -iv MyCA.pvk ^
-sv MySPC.pvk MySPC.cer
It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).
We'll also want to convert the certificate and key into a PFX file:
pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx
If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.
signtool sign /v /f MySPC.pfx ^
/t http://timestamp.url MyExecutable.exe
(See why timestamps may matter)
If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:
signtool sign /v /n "Me" /s SPC ^
/t http://timestamp.url MyExecutable.exe
Some possible timestamp URLs for signtool /t
are:
http://timestamp.verisign.com/scripts/timstamp.dll
http://timestamp.globalsign.com/scripts/timstamp.dll
http://timestamp.comodoca.com/authenticode
For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1
). Your mileage may vary.
MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).
No luck with Code lens in Community editions.
Press Shift + F12 to find all references.
Press Ctrl+Shift+T in the code editor. It will show you popup with suggestion to create a test.
Mac OS: ? Cmd+Shift+T
Partially for the sake of summarization (excluding LINQ solution), here's two one-liners that address the int maxLength
caveat of allowing negative values and also the case of null string:
Substring
way (from Paul Ruane's answer):public static string Truncate(this string s, uint maxLength) =>
s?.Substring(0, Math.Min(s.Length, (int)maxLength));
Remove
way (from kbrimington's answer):public static string Truncate(this string s, uint maxLength) =>
s?.Length > maxLength ? s.Remove((int)maxLength) : s;
You can do this by using the --prefix
flag and the --global
* flag.
pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower
*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules
exists in PATH
.
Every configurable attribute of npm
can be set in any of six different places. In order of priority:
--prefix ./vendor/node_modules
NPM_CONFIG_PREFIX=./vendor/node_modules
$HOME/.npmrc
or userconfig
param$PREFIX/etc/npmrc
or userconfig
parampath/to/npm/itself/npmrc
By default, locally-installed packages go into ./node_modules
. global ones go into the prefix
config variable (/usr/local
by default).
You can run npm config list
to see your current config and npm config edit
to change it.
In general, npm
's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.
You may do:
a= [1,1,1,2,2,3]
delete_list = [1,3]
delete_list.each do |del|
a.delete_at(a.index(del))
end
result : [1, 1, 2, 2]
Use either COUNT(field)
or COUNT(*)
, and stick with it consistently, and if your database allows COUNT(tableHere)
or COUNT(tableHere.*)
, use that.
In short, don't use COUNT(1)
for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)
count(*)
for countingUse *
for all your queries that need to count everything, even for joins, use *
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But don't use COUNT(*)
for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Don't be fooled by those advising that when using *
in COUNT, it fetches entire row from your table, saying that *
is slow. The *
on SELECT COUNT(*)
and SELECT *
has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *
.
In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere)
the same semantics as COUNT(*)
. Example:
For counting rows we could have this:
SELECT COUNT(emp) FROM emp
And they could make it simpler:
SELECT COUNT() FROM emp
And for LEFT JOINs, we could have this:
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But they cannot do that (COUNT(tableNameHere)
) since SQL standard permits naming a field with the same name as its table name:
CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name,
and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)
And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit
field. This will not count all rows, it will only yield 3, not 4
SELECT count(fruit) FROM fruit
Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate
field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But that could cause confusion later if we will add a subordinate
field in the table, as it will count the field(which could be nullable), not the table rows.
So to be on the safe side, use:
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
count(1)
: The one-trick ponyIn particular to COUNT(1)
, it is a one-trick pony, it works well only on one table query:
SELECT COUNT(1) FROM tbl
But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
So what's the meaning of COUNT(1) here?
SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Is it this...?
-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Or this...?
-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
By careful thought, you can infer that COUNT(1)
is the same as COUNT(*)
, regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1)
to work as: COUNT(subordinate.boss_id)
, COUNT(subordinate.*)
So just use either of the following:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Works on Postgresql, it's clear that you want to count the cardinality of the set
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7
select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You cannot do this: http://www.sqlfiddle.com/#!1/98515/8
select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9
select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd
. E.g.
paramstr = paramstr.TrimEnd('&');
As non-root user ideally:
scp -r src $host:$path
If you already some of the content on $host consider using rsync with ssh as a tunnel.
/Allan
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
Using accumulators is the way to compute means and standard deviations in Boost.
accumulator_set<double, stats<tag::variance> > acc;
for_each(a_vec.begin(), a_vec.end(), bind<void>(ref(acc), _1));
cout << mean(acc) << endl;
cout << sqrt(variance(acc)) << endl;
This question comes up for a number of searches related to hex color so I will add a summary here.
Hex colors take the form RRGGBB
or AARRGGBB
(alpha, red, green, blue). In my experience, when using an int
directly, you need to use the full AARRGGBB
form. If you only have the RRGGBB
form then just prefix it with FF
to make the alpha (transparency) fully opaque. Here is how you would set it in code. Using 0x
at the beginning means it is hexadecimal and not base 10.
int myColor = 0xFF3F51B5;
myView.setBackgroundColor(myColor);
As others have noted, you can use Color.parseColor
like so
int myColor = Color.parseColor("#3F51B5");
myView.setBackgroundColor(myColor);
Note that the String must start with a #
. Both RRGGBB
and AARRGGBB
formats are supported.
You should actually be getting your colors from XML whenever possible. This is the recommended option because it makes it much easier to make color changes to your app. If you set a lot of hex colors throughout your code then it is a big pain to try to change them later.
Android material design has color palates with the hex values already configured.
These theme colors are used throughout your app and look like this:
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="primary">#3F51B5</color>
<color name="primary_dark">#303F9F</color>
<color name="primary_light">#C5CAE9</color>
<color name="accent">#FF4081</color>
<color name="primary_text">#212121</color>
<color name="secondary_text">#757575</color>
<color name="icons">#FFFFFF</color>
<color name="divider">#BDBDBD</color>
</resources>
If you need additional colors, a good practice to follow is to define your color in two steps in xml. First name the the hex value color and then name a component of your app that should get a certain color. This makes it easy to adjust the colors later. Again, this is in colors.xml.
<color name="orange">#fff3632b</color>
<color name="my_view_background_color">@color/orange</color>
Then when you want to set the color in code, do the following:
int myColor = ContextCompat.getColor(context, R.color.my_view_background_color);
myView.setBackgroundColor(myColor);
The Color class comes with a number of predefined color constants. You can use it like this.
int myColor = Color.BLUE;
myView.setBackgroundColor(myColor);
Other colors are
Color.BLACK
Color.BLUE
Color.CYAN
Color.DKGRAY
Color.GRAY
Color.GREEN
Color.LTGRAY
Color.MAGENTA
Color.RED
Color.TRANSPARENT
Color.WHITE
Color.YELLOW
public static object CopyObject(object input)
{
if (input != null)
{
object result = Activator.CreateInstance(input.GetType());
foreach (FieldInfo field in input.GetType().GetFields(Consts.AppConsts.FullBindingList))
{
if (field.FieldType.GetInterface("IList", false) == null)
{
field.SetValue(result, field.GetValue(input));
}
else
{
IList listObject = (IList)field.GetValue(result);
if (listObject != null)
{
foreach (object item in ((IList)field.GetValue(input)))
{
listObject.Add(CopyObject(item));
}
}
}
}
return result;
}
else
{
return null;
}
}
This way is a few times faster than BinarySerialization
AND this does not require the [Serializable]
attribute.
If someone needs a simpler way to do it, a tree is only a recursively nested list (since set is not hashable) :
[root, [child_1, [[child_11, []], [child_12, []]], [child_2, []]]]
Where each branch is a pair: [ object, [children] ]
and each leaf is a pair: [ object, [] ]
But if you need a class with methods, you can use anytree.
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
And an idea with a negative check.
/^(?!\d*$|[a-z]*$)[a-z\d]+$/i
^(?!
at start look ahead if string does not\d*$
contain only digits |
or[a-z]*$
contain only letters[a-z\d]+$
matches one or more letters or digits until $
end.Have a look at this regex101 demo
(the i
flag turns on caseless matching: a-z
matches a-zA-Z
)
That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:
setx ENV_VAR_NAME "DESIRED_PATH" /m
This will change it permanently and yes you can overwrite it by another batch script.
Example:
driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))
This one always works for me for any type of selectors. There is also the Actions class, but for this case, it is not so reliable.
My guess is that this could be more elegantly solved in this way:
m <- matrix(1:25, ncol = 5)
m[c(1, 6, 13, 25)] <- NA
df <- data.frame(m)
library(dplyr)
df %>%
filter_all(any_vars(is.na(.)))
#> X1 X2 X3 X4 X5
#> 1 NA NA 11 16 21
#> 2 3 8 NA 18 23
#> 3 5 10 15 20 NA
Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.
From the ANSI C draft (3.3.5):
If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
So watch out with negative numbers when you are stuck with a C89 compiler.
It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.
I haven't tested the email part of this (my test box does not send email) but I think it will work.
<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s
{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>
Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.
In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command
MYSQLDUMP -uuser -p --all-databases > file_name.sql
and than transfer that file from remote server to your machine using Linux SCP Command
scp user@remote_ip:~/mysql_dump_file_name.sql ./
In all these years, nobody has actually mentioned this one. A trick I learned from the awesome ApprovalTests project. The trick is that you use the debugging information in the assembly to find the original directory.
This will not work in RELEASE mode, nor with optimizations enabled, nor on a machine different from the one it was compiled on.
But this will get you paths that are relative to the location of the source code file you call it from
public static class PathUtilities
{
public static string GetAdjacentFile(string relativePath)
{
return GetDirectoryForCaller(1) + relativePath;
}
public static string GetDirectoryForCaller()
{
return GetDirectoryForCaller(1);
}
public static string GetDirectoryForCaller(int callerStackDepth)
{
var stackFrame = new StackTrace(true).GetFrame(callerStackDepth + 1);
return GetDirectoryForStackFrame(stackFrame);
}
public static string GetDirectoryForStackFrame(StackFrame stackFrame)
{
return new FileInfo(stackFrame.GetFileName()).Directory.FullName + Path.DirectorySeparatorChar;
}
}
# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]
# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]
I/P : The cat sat on the mat
O/P : The cat slept on the mat
'hg forget
' is just shorthand for 'hg remove -Af
'. From the 'hg remove
' help:
...and -Af can be used to remove files from the next revision without deleting them from the working directory.
Bottom line: 'remove
' deletes the file from your working copy on disk (unless you uses -Af
) and 'forget
' doesn't.
Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45
unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));
The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.
Strangely, rbenv
version did not set the .rbenv
file.
Check with: ls -ltra
--> to see that a rbenv
was written.
I think this comes from from the waterfall development days, where the actual development phase of a project could be as little as 20-30% of the total project time. Take the total lines of code and divide by the entire project time and you'll get around 10 lines/day. Divide by just the coding period, and you'll get closer to what people are quoting.
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
A modified python version of @danack's PHP generate script. It generates all files & folders that live inside of build/
to the parent directory, replacing all {{placeholder}}
matches. You need to cd
into build/
before running the script.
File structure
build/
-- (files/folders you want to generate)
-- build.py
sites-available/...
sites-enabled/...
nginx.conf
...
build.py
import os, re
# Configurations
target = os.path.join('.', '..')
variables = {
'placeholder': 'your replacement here'
}
# Loop files
def loop(cb, subdir=''):
dir = os.path.join('.', subdir);
for name in os.listdir(dir):
file = os.path.join(dir, name)
newsubdir = os.path.join(subdir, name)
if name == 'build.py': continue
if os.path.isdir(file): loop(cb, newsubdir)
else: cb(subdir, name)
# Update file
def replacer(subdir, name):
dir = os.path.join(target, subdir)
file = os.path.join(dir, name)
oldfile = os.path.join('.', subdir, name)
with open(oldfile, "r") as fin:
data = fin.read()
for key, replacement in variables.iteritems():
data = re.sub(r"{{\s*" + key + "\s*}}", replacement, data)
if not os.path.exists(dir):
os.makedirs(dir)
with open(file, "w") as fout:
fout.write(data)
# Start variable replacements.
loop(replacer)
I did
msgbox "TEXT HERE",3,"TITLE HERE"
If Yes=true then
(result)
else
msgbox "Closing..."
I was having this same problem too, I while multiple canvas elements with position:absolute does the job, if you want to save the output into an image, that's not going to work.
So I went ahead and did a simple layering "system" to code as if each layer had its own code, but it all gets rendered into the same element.
https://github.com/federicojacobi/layeredCanvas
I intend to add extra capabilities, but for now it will do.
You can do multiple functions and call them in order to "fake" layers.
For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:
http://thecodeplayer.com/walkthrough/css3-family-tree
<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li>
<a href="#">Child</a>
<ul>
<li>
<a href="#">Grand Child</a>
</li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li>
<a href="#">Grand Child</a>
<ul>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
</ul>
</li>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
* {margin: 0; padding: 0;}
.tree ul {
padding-top: 20px; position: relative;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
.tree li {
float: left; text-align: center;
list-style-type: none;
position: relative;
padding: 20px 5px 0 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*We will use ::before and ::after to draw the connectors*/
.tree li::before, .tree li::after{
content: '';
position: absolute; top: 0; right: 50%;
border-top: 1px solid #ccc;
width: 50%; height: 20px;
}
.tree li::after{
right: auto; left: 50%;
border-left: 1px solid #ccc;
}
/*We need to remove left-right connectors from elements without
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
display: none;
}
/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}
/*Remove left connector from first child and
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
border-right: 1px solid #ccc;
border-radius: 0 5px 0 0;
-webkit-border-radius: 0 5px 0 0;
-moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
border-radius: 5px 0 0 0;
-webkit-border-radius: 5px 0 0 0;
-moz-border-radius: 5px 0 0 0;
}
/*Time to add downward connectors from parents*/
.tree ul ul::before{
content: '';
position: absolute; top: 0; left: 50%;
border-left: 1px solid #ccc;
width: 0; height: 20px;
}
.tree li a{
border: 1px solid #ccc;
padding: 5px 10px;
text-decoration: none;
color: #666;
font-family: arial, verdana, tahoma;
font-size: 11px;
display: inline-block;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
transition: all 0.5s;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
}
/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after,
.tree li a:hover+ul li::before,
.tree li a:hover+ul::before,
.tree li a:hover+ul ul::before{
border-color: #94a0b4;
}
PS: apart from the code, I also like the way the site shows it in action... really innovative.
This should do it:
declare
v_count integer;
begin
for r in (select table_name, owner from all_tables
where owner = 'SCHEMA_NAME')
loop
execute immediate 'select count(*) from ' || r.table_name
into v_count;
INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
VALUES (r.table_name,r.owner,v_count,SYSDATE);
end loop;
end;
I removed various bugs from your code.
Note: For the benefit of other readers, Oracle does not provide a table called STATS_TABLE
, you would need to create it.
You can move from one scene to another programmatically using below code :
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let objSomeViewController = storyBoard.instantiateViewControllerWithIdentifier(“storyboardID”) as! SomeViewController
// If you want to push to new ViewController then use this
self.navigationController?.pushViewController(objSomeViewController, animated: true)
// ---- OR ----
// If you want to present the new ViewController then use this
self.presentViewController(objSomeViewController, animated:true, completion:nil)
Here storyBoardID is value that you set to scene using Interface Builder. This is shown below :
Intel HD Graphics is usually the on-CPU graphics chip in newer Core i3/i5/i7 processors.
As far as I know it doesn't support CUDA (which is a proprietary NVidia technology), but OpenCL is supported by NVidia, ATi and Intel.
/**
* searches a simple as well as multi dimension array
* @param type $needle
* @param type $haystack
* @return boolean
*/
public static function in_array_multi($needle, $haystack){
$needle = trim($needle);
if(!is_array($haystack))
return False;
foreach($haystack as $key=>$value){
if(is_array($value)){
if(self::in_array_multi($needle, $value))
return True;
else
self::in_array_multi($needle, $value);
}
else
if(trim($value) === trim($needle)){//visibility fix//
error_log("$value === $needle setting visibility to 1 hidden");
return True;
}
}
return False;
}
I got the same problem with @ManyToOne
column. It was solved... in stupid way. I had all other annotations for public getter methods, because they were overridden from parent class. But last field was annotated for private variable like in all other classes in my project. So I got the same MappingException
without the reason.
Solution: I placed all annotations at public getter methods. I suppose, Hibernate can't handle cases, when annotations for private fields and public getters are mixed in one class.
We can achieve thread safety by using ConcurrentHashMap and synchronisedHashmap and Hashtable. But there is a lot of difference if you look at their architecture.
Both will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to acquire the lock first. At the same time, other threads are not allowed to perform any operation. So at a time, only one thread can operate on this. So the waiting time will increase here. We can say that performance is relatively low when you comparing with ConcurrentHashMap.
It will maintain the lock at segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it.
If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time.
So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap and Hashtable.
You can just use an a
selector in your stylesheet to define all states of an anchor/hyperlink. For example:
a {
color: blue;
}
Would override all link styles and make all the states the colour blue.
The query to use with Oracle is:
String sqlStr="select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='"+_db+".users' and COLUMN_NAME not in ('password','version','id')"
Never heard of HQL for such queries. I assume it doesn't make sense for ORM implementations to deal with it. ORM is an Object Relational Mapping, and what you're looking for is metadata mapping... You wouldn't use HQL, rather use API methods for this purpose, or direct SQL. For instance, you can use JDBC DatabaseMetaData.
I think tablespace has nothing to do with schema. AFAIK tablespaces are mainly used for logical internal technical purposes which should bother DBAs. For more information regarding tablespaces, see Oracle doc.
You can commit on your online repo (or commit on your local repo and then push to your online repo), then send pull request.
Project manager can accept it to get your changes in his main online version.
As a developer who spends most of his time in the embedded programming world, I would argue that assembly is far from a dead/obsolete language. There is a certain close-to-the-metal level of coding (for example, in drivers) that sometimes cannot be expressed as accurately or efficiently in a higher-level language. We write nearly all of our hardware interface routines in assembler.
That being said, this assembly code is wrapped such that it can be called from C code and is treated like a library. We don't write the entire program in assembly for many reasons. First and foremost is portability; our code base is used on several products that use different architectures and we want to maximize the amount of code that can be shared between them. Second is developer familiarity. Simply put, schools don't teach assembly like they used to, and our developers are far more productive in C than in assembly. Also, we have a wide variety of "extras" (things like libraries, debuggers, static analysis tools, etc) available for our C code that aren't available for assembly language code. Even if we wanted to write a pure-assembly program, we would not be able to because several critical hardware libraries are only available as C libs. In one sense, it's a chicken/egg problem. People are driven away from assembly because there aren't as many libraries and development/debug tools available for it, but the libs/tools don't exist because not enough people use assembly to warrant the effort creating them.
In the end, there is a time and a place for just about any language. People use what they are most familiar and productive with. There will probably always be a place in a programmer's repertoire for assembly, but most programmers will find that they can write code in a higher-level language that is almost as efficient in far less time.
Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.
0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.
I had the same problem with Android Studio - adb server version (37) doesn't match this client (39)
. I fixed by the following solution :
In Android Studio go to Tools -> Android -> SDK Manager
In the SDK Tools tab untick Android SDK Platform-Tools, click Apply to uninstall.
I then renamed the folder Platform-Tools
to Platform-ToolsOld
Then back in the SDK Manager re-tick the Platform-Tools to re-install.
There are a few alternate ways to figure out the currently used python in Linux is:
which python
command.command -v python
commandtype python
commandSimilarly On Windows with Cygwin will also result the same.
kuvivek@HOSTNAME ~
$ which python
/usr/bin/python
kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4 /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz
kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3
kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python
kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)
If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.
>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>
If you are not sure of the actual path of the python command and is available in your system, Use the following command.
pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $
JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");
The above solutions fix the project or work around the problem in some way. Sometimes you just don't want to fix the project and just hide the warning instead.
To do that, configure the contents of the warning panel and make sure to toggle-off the "build path"->"JRE System Path Problem" category. The UI for this dialog is a bit complex/weird/usability challenged so you might have to fiddle with a few of the options to make it do what you want.
You have to add CORS on the server side:
If you are using nodeJS then:
First you need to install cors
by using below command :
npm install cors --save
Now add the following code to your app starting file like ( app.js or server.js
)
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
require('./router/index')(app);
ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go
I don't know if it's entirely possible to do your ideal pattern. But I found a way to do your first way: CountIF
+-------+-------------------+
| A | B |
+-------+-------------------+
| GL15 | =COUNTIF(A:A, A1) |
+-------+-------------------+
| GL15 | =COUNTIF(A:A, A2) |
+-------+-------------------+
| GL15 | =COUNTIF(A:A, A3) |
+-------+-------------------+
| GL16 | =COUNTIF(A:A, A4) |
+-------+-------------------+
| GL17 | =COUNTIF(A:A, A5) |
+-------+-------------------+
| GL17 | =COUNTIF(A:A, A6) |
+-------+-------------------+
Are you talking about code within <script>
tags, or in the HTML tag attributes, like this?
<a href="#" onclick="alert('this is inline JS');return false;">Click</a>
Either way, the debugger
keyword like this will work:
<a href="#" onclick="debugger; alert('this is inline JS');return false;">Click</a>
N.B. Chrome won't pause at debugger
s if the dev tools are not open.
You can also set property breakpoints in JS files and <script>
tags:
this works: select * from table where column like '%(hit enter)%'
Ignore the brackets and hit enter to introduce new line.
There's a new web framework, called Scala Web Pages. From the site:
The Scala Pages web framework is likely to appeal to web programmers who come from a Java background and want to program web applications in Scala. The emphasis is on OOP rather than functional programming.
$variable
and <?scp-instruction?>
select convert(varchar(10), GETDATE(), 108)
returned 17:36:56
when I ran it a few moments ago.
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
You could use code like this:
if (n is IConvertible)
return ((IConvertible) n).ToDouble(CultureInfo.CurrentCulture);
else
// Cannot be converted.
If your object is an Int32
, Single
, Double
etc. it will perform the conversion. Also, a string implements IConvertible
but if the string isn't convertible to a double then a FormatException
will be thrown.
Check that there are no missing references - to do this, go to the database window and click on "Modules", then "Design", then select the menu "Tools" and then "References". Or try doing a compile and see if it compiles fully (go to the Debug menu then select Compile) - it might tell you of a missing reference e.g. Microsoft Office 11.0 Object Library. Select References from the Tools menu again and see if any references are ticked and say "MISSING:". In some cases you can select a different version from the list, if 11.0 is missing, look for version 12.0 then recompile. That usually does the trick for me.
Using the builtin Date.parse
function which accepts input in ISO8601 format and directly returns the desired integer return value:
var dates_as_int = dates.map(Date.parse);
1. A client downloads javascript code MyCode.js from http://siteA - the origin.
The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)
2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.
no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.
Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.
Make sure all same source library have same version number. In my case I was using different google api versions. I was using 11.6.0 for all google libraries but 10.4.0 for google place api. After updating google place api to 11.6.0, problem fixed.
Please note that my multidex is also enabled for the project.
I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.
The only thing that worked for me was updating my video drivers.
I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.
The direct answer to your question is String.Join
as others have mentioned.
However, if you need some manipulations, you can use Aggregate
:
List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");
string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();
Suggestions:
getGraphics()
on a component as the Graphics object obtained will be transient.paintComponent()
method.Key tutorial links:
image.ScaleToFit(500f,30f);
this method keeps the aspect ratio of the image
Let us assume you hit a url as www.example.com/test/111 . Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using @PathVariable as follows :
@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}
SO the variable value is retrieved from the url
The using statement refers to a namespace, not a project.
Make sure that you have the appropriately named namespace in your referenced project:
namespace PrjTest
{
public class Foo
{
// etc...
}
}
Read more about namespaces on MSDN:
I had also same symptoms but has been caused by different thing.
I was not able to:
git checkout app.js //did nothing
git rm app.js //did nothing
rm -rf app.js //did nothing
even on
git rm --cached app.js
it signs as deleted and in untracked files I could see app.js. But when I tried rm -rf app.js
and peform git status
again it still shows me the file in 'untracked'.
After couple of tries with colleague we found out, that it has been caused by Grunt!
As the Grunt
has been turned on, and because app.js has been generated from couple of other js files we found out that after each operation with js files (also this app.js) grunt recreate app.js again.
They are found on either one of the below locations depending on how chrome was installed
~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions
/Library/Application\ Support/Google/Chrome/Default/Extensions
On the Form Move Event add this:
private void Frm_Move (object sender, EventArgs e)
{
Top = 0; Left = 0;
Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}
You could use input type image.
<input type="image" src="http://example.com/path/to/image.png" />
It works as a button and can have the event handlers attached to it.
Alternatively, you can use css to style your button with a background image, and set the borders, margins and the like appropriately.
<button style="background: url(myimage.png)" ... />
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
For people using *nix (Linux, OS X, etc.), there's no reason to do it via a second export command, you can chain it as part of the invoking command:
NODE_ENV=development node server.js
Easier, no? :)
I'd like to supplement BalusC's answer with the mapping rules and an example.
Mapping rules from Servlet 2.5 specification:
In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello
To map http://host:port/context/hello.jsp
You can get mac address:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();
Set Permission in Menifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
You need reinstall VS.
Language Pack Support in Visual Studio 2017 RC
Issue:
This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.
Workaround:
These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.
Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016
I've added some code to my project, so it's more convenient.
HtmlExtensions.cs:
namespace System.Web.Mvc.Html
{
public static class HtmlExtensions
{
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post, new { id = formId });
}
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formId, FormMethod method)
{
return htmlHelper.BeginForm(null, null, method, new { id = formId });
}
}
}
MySignupForm.cshtml:
@using (Html.BeginForm("signupform"))
{
@* Some fields *@
}
Your code should be something like
require_once('class.twitter.php');
$t = new twitter;
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
The test Resource files(src/test/resources) are loaded to target/test-classes sub folder. So we can use the below code to load the test resource files.
String resource = "sample.txt";
File file = new File(getClass().getClassLoader().getResource(resource).getFile());
System.out.println(file.getAbsolutePath());
Note : Here the sample.txt file should be placed under src/test/resources folder.
For more details refer options_to_load_test_resources
I found the best way to handle this (for me) is to use the following:
Dim MyString as String
MyString = Application.ThisCell.Address
Range(MyString).Select
Hope this helps.
CSS has different pseudo selector by which you can achieve such effect. In your case you can use
:active : if you want background color only when the button is clicked and don't want to persist.
:focus: if you want background color untill the focus is on the button.
button:active{
background:olive;
}
and
button:focus{
background:olive;
}
P.S.: Please don't give the number in Id
attribute of html elements.
That's how GROUP BY works. It takes several rows and turns them into one row. Because of this, it has to know what to do with all the combined rows where there have different values for some columns (fields). This is why you have two options for every field you want to SELECT : Either include it in the GROUP BY clause, or use it in an aggregate function so the system knows how you want to combine the field.
For example, let's say you have this table:
Name | OrderNumber
------------------
John | 1
John | 2
If you say GROUP BY Name, how will it know which OrderNumber to show in the result? So you either include OrderNumber in group by, which will result in these two rows. Or, you use an aggregate function to show how to handle the OrderNumbers. For example, MAX(OrderNumber)
, which means the result is John | 2
or SUM(OrderNumber)
which means the result is John | 3
.
awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
print
will insert a newline by default. You dont want that to happen, hence use printf
instead.
To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c)
.
For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.
The logic for dimming is thus:
NOT IsFocused AND (IsDefocused OR NOT Enabled)
To implement this logic, I made a generic IMultiValueConverter
named (awkwardly) to match my logic
// 'P' represents a parenthesis
// ! a && ( b || ! c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
// redacted [...] for brevity
public object Convert(object[] values, ...)
{
bool a = System.Convert.ToBoolean(values[0]);
bool b = System.Convert.ToBoolean(values[1]);
bool c = System.Convert.ToBoolean(values[2]);
return !a && (b || !c);
}
...
}
In the XAML I use this in a MultiDataTrigger
in a <Style><Style.Triggers>
resource
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!-- when the equation is TRUE ... -->
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
<!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
<Binding Path="IsFocus"/>
<Binding Path="IsDefocused" />
<Binding Path="Enabled" />
</MultiBinding>
</Condition.Binding>
</Condition>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!-- ... show the 'dim-out' overlay -->
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
And for completeness sake, my converter is defined in a ResourceDictionary
<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
<conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>
Here's an pretty useless function that return values wrapped by specific characters. :)
jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/
function getValsWrappedIn(str,c1,c2){
var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g");
return str.match(rg);
}
var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results = getValsWrappedIn(exampleStr,"(",")")
// Will return array ["5","19","thingy"]
console.log(results)
Build lists of matched lines - several flavors:
def lines_that_equal(line_to_match, fp):
return [line for line in fp if line == line_to_match]
def lines_that_contain(string, fp):
return [line for line in fp if string in line]
def lines_that_start_with(string, fp):
return [line for line in fp if line.startswith(string)]
def lines_that_end_with(string, fp):
return [line for line in fp if line.endswith(string)]
Build generator of matched lines (memory efficient):
def generate_lines_that_equal(string, fp):
for line in fp:
if line == string:
yield line
Print all matching lines (find all matches first, then print them):
with open("file.txt", "r") as fp:
for line in lines_that_equal("my_string", fp):
print line
Print all matching lines (print them lazily, as we find them)
with open("file.txt", "r") as fp:
for line in generate_lines_that_equal("my_string", fp):
print line
Generators (produced by yield) are your friends, especially with large files that don't fit into memory.
For anyone looks for a shorthand way, to add transition for all properties except for one specific property with delay, be aware of there're differences among even modern browsers.
A simple demo below shows the difference. Check out full code
div:hover {
width: 500px;
height: 500px;
border-radius: 0;
transition: all 2s, border-radius 2s 4s;
}
Chrome will "combine" the two animation (which is like I expect), like below:
While Safari "separates" it (which may not be expected):
A more compatible way is that you assign the specific transition for specific property, if you have a delay for one of them.
The standard MIME type is application/pdf
. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.
MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.
The use of x-pdf
predates the standardization of the MIME type for PDF. MIME types in the x-
namespace are considered experimental, just as those in the vnd.
namespace are considered vendor-specific. x-pdf
might be used for compatibility with old software.
push()
is for arrays, not objects, so use the right data structure.
var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
if ( data[index].Status == "Valid" ) {
tempData.push( data );
}
}
data = tempData;
Thiago answer is correct, adding sample more specific to question, @ElementCollection will create new table in your database, but without mapping two tables, It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a collection of embeddable elements (class annotated with @Embeddable).
Here is the sample to persist list of String
@ElementCollection
private Collection<String> options = new ArrayList<String>();
Here is the sample to persist list of Custom object
@Embedded
@ElementCollection
private Collection<Car> carList = new ArrayList<Car>();
For this case we need to make class Embeddable
@Embeddable
public class Car {
}
have at look at the static methods DateTime.Parse()
and DateTime.TryParse()
. They will allow you to pass in your date string and a format string, and get a DateTime object in return.
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
I have created a custom regex to deal with names:
I have tried these types of names and found working perfect
My RegEx looks like this:
^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)
MVC4 Model:
[RegularExpression("^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)", ErrorMessage = "Valid Charactors include (A-Z) (a-z) (' space -)") ]
Please note the double \\
for escape characters
For those of you that are new to RegEx I thought I'd include a explanation.
^ // start of line
[a-zA-Z]{2,} // will except a name with at least two characters
\s // will look for white space between name and surname
[a-zA-Z]{1,} // needs at least 1 Character
\'?-? // possibility of **'** or **-** for double barreled and hyphenated surnames
[a-zA-Z]{2,} // will except a name with at least two characters
\s? // possibility of another whitespace
([a-zA-Z]{1,})? // possibility of a second surname
Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.
HTML
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
</a></div>
CSS
.navbar-toggle, .icon-bar {
border:1px solid orange;
}
BOOM...
import random
random.shuffle(array)
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err
to errors.txt
file.
The following code were written in ES6 and it will work in most of the browsers without an issue.
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
One of the reason I found for this error is 'Packet Size=xxxxx' in connection string. if the value of xxxx is too large, we will see this error. Either remove this value and let SQL server handle it or keep it low, depending on the network capabilities.
If you just want to execute the shell command in your c program, you could use,
#include <stdlib.h>
int system(const char *command);
In your case,
system("pwd");
The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.
What do you mean by this? You should be able to find the mentioned packages in /bin/
sudo find / -executable -name pwd
sudo find / -executable -name echo
I know this is an old question, but I faced the same problem recently in Laravel 7 application.
To make renaming columns work I used a tip from this answer where instead of composer require doctrine/dbal
I have issued composer require doctrine/dbal:^2.12.1
because the latest version of doctrine/dbal still throws an error.
Just keep in mind that if you already use a higher version, this answer might not be appropriate for you.
Here's the filter that I ended up using for strftime in Jinja2 and Flask
@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt=None):
date = dateutil.parser.parse(date)
native = date.replace(tzinfo=None)
format='%b %d, %Y'
return native.strftime(format)
And then you use the filter like so:
{{car.date_of_manufacture|strftime}}
Visual Studio 2015 doesn't install C++ by default. You have to rerun the setup, select Modify and then check Programming Language -> C++
Close Sublime. Run this command. It will uninstall it. You won't lose your prefs. Then run it again. It will automatically bind subl
.
brew install Caskroom/cask/sublime-text
I can't remember where I found this method, but it's pretty simple and works well.
HTML:
<nav role="navigation">
<ul>
<li ui-sref-active="selected" class="inactive"><a ui-sref="tab-01">Tab 01</a></li>
<li ui-sref-active="selected" class="inactive"><a ui-sref="tab-02">Tab 02</a></li>
</ul>
</nav>
CSS:
.selected {
background-color: $white;
color: $light-blue;
text-decoration: none;
border-color: $light-grey;
}
Use the Chocolatey packet manager. It's a command-line tool similar to npm. Once you have installed it, use
choco install openjdk
in an elevated command prompt to install OpenJDK.
To update an installed version to the latest version, type
choco upgrade openjdk
Pretty simple to use and especially helpful to upgrade to the latest version. No manual fiddling with path environment variables.
If you want a HTML only solution, we can just use the pre
tag. It defines "preformatted text" which means that it does not format word-wrapping. Here is a quick example to explain:
div {
width: 200px;
height: 200px;
padding: 20px;
background: #adf;
}
pre {
width: 200px;
height: 200px;
padding: 20px;
font: inherit;
background: #fda;
}
_x000D_
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
_x000D_
I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.
From the curl man page:
-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.
Below the examples:
curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"
Using custom headers
curl -s -H "Accept: application/json" "http://host:8080/some/resource")
Using POST method with a header
curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'
You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:
curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"
Add this code into the css file:
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
This will help.
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
TikZ can do this.
A quick demo:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
[scale=.8,auto=left,every node/.style={circle,fill=blue!20}]
\node (n6) at (1,10) {6};
\node (n4) at (4,8) {4};
\node (n5) at (8,9) {5};
\node (n1) at (11,8) {1};
\node (n2) at (9,6) {2};
\node (n3) at (5,5) {3};
\foreach \from/\to in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
\draw (\from) -- (\to);
\end{tikzpicture}
\end{document}
produces:
More examples @ http://www.texample.net/tikz/examples/tag/graphs/
More information about TikZ: http://sourceforge.net/projects/pgf/ where I guess an installation guide will also be present.
I had the same issue, I added the component in the index.ts of a=of the folder and did a export. Still the undefined error was popping. But the IDE pop our any red squiggly lines
Then as suggested changed from
import { SearchComponent } from './';
to
import { SearchComponent } from './search/search.component';
This answer is similar to @PaulMcG's answer but doesn't require sorting the input.
For those into functional programming, groupBy
can be written in one line (not including imports!), and unlike itertools.groupby
it doesn't require the input to be sorted:
from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict
def groupBy(key, seq):
return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))
(The reason for ... or grp
in the lambda
is that for this reduce()
to work, the lambda
needs to return its first argument; because list.append()
always returns None
the or
will always return grp
. I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)
This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order. For the OP's example, calling this as groupBy(lambda pair: pair[1], input)
will return this dict:
{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}
And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension. So this will do it:
result = {key: [pair[0] for pair in values],
for key, values in groupBy(lambda pair: pair[1], input).items()}
You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -
, like script.ps1 -server http://devserver
Then you handle them in param
section in the beginning of the file.
You can also assign default values to your params, read them from console if not available or stop script execution:
param (
[string]$server = "http://defaultserver",
[Parameter(Mandatory=$true)][string]$username,
[string]$password = $( Read-Host "Input password, please" )
)
Inside the script you can simply
write-output $server
since all parameters become variables available in script scope.
In this example, the $server
gets a default value if the script is called without it, script stops if you omit the -username
parameter and asks for terminal input if -password
is omitted.
Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.
The keyword for that is [switch]
parameter type:
param (
[string]$server = "http://defaultserver",
[string]$password = $( Read-Host "Input password, please" ),
[switch]$force = $false
)
Inside the script then you would work with it like this:
if ($force) {
//deletes a file or does something "bad"
}
Now, when calling the script you'd set the switch/flag parameter like this:
.\yourscript.ps1 -server "http://otherserver" -force
If you explicitly want to state that the flag is not set, there is a special syntax for that
.\yourscript.ps1 -server "http://otherserver" -force:$false
Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):
You can do like this in more natural way,
case expression
when condtion1
function
when condition2
function
else
function
end
<hr>
is not from struts. It is just an HTML tag.
So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.
mode: 'no-cors'
won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course you almost never want that.
What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin
is in a response, then browsers will relax that blocking and allow your code to access the response.
But if a site sends no Access-Control-Allow-Origin
in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors'
(in fact that’ll ensure your frontend code can’t access the response contents).
However, one thing that will work: if you send your request through a CORS proxy.
You can also easily deploy your own proxy to Heroku in literally just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/
.
Prefix your request URL with your proxy URL; for example:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:
https://example.com
.https://example.com
.Access-Control-Allow-Origin
header to the response.The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin
response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS
request, because in that case, the proxy also sends back the Access-Control-Allow-Headers
and Access-Control-Allow-Methods
headers needed to make the preflight successful.
I can hit this endpoint,
http://catfacts-api.appspot.com/api/facts?number=99
via Postman
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why it is that even though you can access the response with Postman, browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin
response header.
http://catfacts-api.appspot.com/api/facts?number=99 has no Access-Control-Allow-Origin
response header, so there’s no way your frontend code can access the response cross-origin.
Your browser can get the response fine and you can see it in Postman and even in browser devtools—but that doesn’t mean browsers will expose it to your code. They won’t, because it has no Access-Control-Allow-Origin
response header. So you must instead use a proxy to get it.
The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin
response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin
header added is what the browser sees, so the browser lets your frontend code actually access the response.
So I am trying to pass in an object, to my Fetch which will disable CORS
You don’t want to do that. To be clear, when you say you want to “disable CORS” it seems you actually mean you want to disable the same-origin policy. CORS itself is actually a way to do that — CORS is a way to loosen the same-origin policy, not a way to restrict it.
But anyway, it’s true you can — in just your local environment — do things like give your browser runtime flags to disable security and run insecurely, or you can install a browser extension locally to get around the same-origin policy, but all that does is change the situation just for you locally.
No matter what you change locally, anybody else trying to use your app is still going to run into the same-origin policy, and there’s no way you can disable that for other users of your app.
You most likely never want to use mode: 'no-cors'
in practice except in a few limited cases, and even then only if you know exactly what you’re doing and what the effects are. That’s because what setting mode: 'no-cors'
actually says to the browser is, “Block my frontend JavaScript code from looking into the contents of the response body and headers under all circumstances.” In most cases that’s obviously really not what you want.
As far as the cases when you would want to consider using mode: 'no-cors'
, see the answer at What limitations apply to opaque responses? for the details. The gist of it is that the cases are:
In the limited case when you’re using JavaScript to put content from another origin into a <script>
, <link rel=stylesheet>
, <img>
, <video>
, <audio>
, <object>
, <embed>
, or <iframe>
element (which works because embedding of resources cross-origin is allowed for those) — but for some reason you don’t want to or can’t do that just by having the markup of the document use the resource URL as the href
or src
attribute for the element.
When the only thing you want to do with a resource is to cache it. As alluded to in the answer What limitations apply to opaque responses?, in practice the scenario that applies to is when you’re using Service Workers, in which case the API that’s relevant is the Cache Storage API.
But even in those limited cases, there are some important gotchas to be aware of; see the answer at What limitations apply to opaque responses? for the details.
I have also tried to pass in the object
{ mode: 'opaque'}
There is no mode: 'opaque'
request mode — opaque
is instead just a property of the response, and browsers set that opaque property on responses from requests sent with the no-cors
mode.
But incidentally the word opaque is a pretty explicit signal about the nature of the response you end up with: “opaque” means you can’t see it.
Simple Copy this text and put on the before </body>
function disableselect(e) {
return false
}
function reEnable() {
return true
}
document.onselectstart = new Function ("return false")
if (window.sidebar) {
document.onmousedown = disableselect
document.onclick = reEnable
}
You can't really talk about slowness based on the data you provided in a question. And I don't think you should even worry too much about performance at this stage of developement. It's called premature optimization.
However, I'd suggest that you'd include Tag_ID column in the Tags table. It's usually a good practice that every table has an ID column.
Another solution if the list contains static values.
eg: checking for a valid value from a list of valid values:
func IsValidCategory(category string) bool {
switch category {
case
"auto",
"news",
"sport",
"music":
return true
}
return false
}
Here the code to use your app.js
input specifies file name
res.download(__dirname+'/'+input);
*In all instances the # refers to the cell number
You really don't need the datedif functions; for example:
I'm working on a spreadsheet that tracks benefit eligibility for employees.
I have their hire dates in the "A" column and in column B is =(TODAY()-A#)
And you just format the cell to display a general number instead of date.
It also works very easily the other way: I also converted that number into showing when the actual date is that they get their benefits instead of how many days are left, and that is simply
=(90-B#)+TODAY()
Just make sure you're formatting cells as general numbers or dates accordingly.
Hope this helps.
pandas
uses matplotlib
for basic dataframe plots. So, if you are using pandas
for basic plot you can use matplotlib for plot customization. However, I propose an alternative method here using seaborn
which allows more customization of the plot while not going into the basic level of matplotlib
.
Working Code:
import pandas as pd
import seaborn as sns
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'],
index=['Index 1', 'Index 2'])
ax= sns.lineplot(data=df2, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='Video streaming dropout by category')
As many here have already mentioned, I also prefer using .hpp for header-only libraries that use template classes/functions. I prefer to use .h for header files accompanied by .cpp source files or shared or static libraries.
Most of the libraries I develop are template based and thus need to be header only, but when writing applications I tend to separate declaration from implementation and end up with .h and .cpp files
This seems to be an efficient way to list vars with column number:
cbind(names(df))
Output:
[,1]
[1,] "A"
[2,] "B"
[3,] "C"
Sometimes I like to copy variables with position into my code so I use this function:
varnums<- function(x) {w=as.data.frame(c(1:length(colnames(x))),
paste0('# ',colnames(x)))
names(w)= c("# Var/Pos")
w}
varnums(df)
Output:
# Var/Pos
# A 1
# B 2
# C 3
I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...
You can specify 12/25/2010 4:58 PM by using
DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");
OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:
DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);
The ExistingTime.Date
will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.
The abort
function does this. For example:
abort("Message goes here")
Note: the abort
message will be written to STDERR
as opposed to puts
which will write to STDOUT
.
From Unix.SE: A simple command-line utility called gpustat
now exists: https://github.com/wookayin/gpustat.
It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi
.
Your modification of sys.path
assumes the current working directory is always in main/
. This is not the case. Instead, just add the parent directory to sys.path
:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib
Don't forget to include a file __init__.py
in gen_py and lib - otherwise, they won't be recognized as Python modules.
I took Crystalonics' answer and turned them into extension methods. I hope someone else will find them useful:
public static byte[] SerializeToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
public static T Deserialize<T>(this byte[] byteArray) where T : class
{
if (byteArray == null)
{
return null;
}
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(byteArray, 0, byteArray.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = (T)binForm.Deserialize(memStream);
return obj;
}
}
Update 2018 (as of Bootstrap 4.1)
Yes, pull-left
and pull-right
have been replaced with float-left
and float-right
in Bootstrap 4.
However, floats will not work in all cases since Bootstrap 4 is now flexbox.
To align flexbox children to the right, use auto-margins (ie: ml-auto
) or the flexbox utils (ie: justify-content-end
, align-self-end
, etc..).
Navs:
<ul class="nav">
<li><a href class="nav-link">Link</a></li>
<li><a href class="nav-link">Link</a></li>
<li class="ml-auto"><a href class="nav-link">Right</a></li>
</ul>
Breadcrumbs:
<ul class="breadcrumb">
<li><a href="/">Home</a></li>
<li class="active"><a href="/">Link</a></li>
<li class="ml-auto"><a href="/">Right</a></li>
</ul>
https://www.codeply.com/go/6ITgrV7pvL
Grid:
<div class="row">
<div class="col-3">Left</div>
<div class="col-3 ml-auto">Right</div>
</div>
some people talk very well about PyInstaller
Try the below Code:
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
This does it:
Do
c = c + 1
Loop While Cells(c, "A").Value <> ""
'prints the last empty row
Debug.Print c
when you want to access images which are in public/images folder and if you want to access it without using laravel functions, use as follows:
<img src={{url('/images/photo.type')}} width="" height="" alt=""/>
This works fine.
You can't disable a link (in a portable way). You can use one of these techniques (each one with its own benefits and disadvantages).
This should be the right way (but see later) to do it when most of browsers will support it:
a.disabled {
pointer-events: none;
}
It's what, for example, Bootstrap 3.x does. Currently (2016) it's well supported only by Chrome, FireFox and Opera (19+). Internet Explorer started to support this from version 11 but not for links however it's available in an outer element like:
span.disable-links {
pointer-events: none;
}
With:
<span class="disable-links"><a href="#">...</a></span>
We, probably, need to define a CSS class for pointer-events: none
but what if we reuse the disabled
attribute instead of a CSS class? Strictly speaking disabled
is not supported for <a>
but browsers won't complain for unknown attributes. Using the disabled
attribute IE will ignore pointer-events
but it will honor IE specific disabled
attribute; other CSS compliant browsers will ignore unknown disabled
attribute and honor pointer-events
. Easier to write than to explain:
a[disabled] {
pointer-events: none;
}
Another option for IE 11 is to set display
of link elements to block
or inline-block
:
<a style="pointer-events: none; display: inline-block;" href="#">...</a>
Note that this may be a portable solution if you need to support IE (and you can change your HTML) but...
All this said please note that pointer-events
disables only...pointer events. Links will still be navigable through keyboard then you also need to apply one of the other techniques described here.
In conjunction with above described CSS technique you may use tabindex
in a non-standard way to prevent an element to be focused:
<a href="#" disabled tabindex="-1">...</a>
I never checked its compatibility with many browsers then you may want to test it by yourself before using this. It has the advantage to work without JavaScript. Unfortunately (but obviously) tabindex
cannot be changed from CSS.
Use a href
to a JavaScript function, check for the condition (or the disabled attribute itself) and do nothing in case.
$("td > a").on("click", function(event){
if ($(this).is("[disabled]")) {
event.preventDefault();
}
});
To disable links do this:
$("td > a").attr("disabled", "disabled");
To re-enable them:
$("td > a").removeAttr("disabled");
If you want instead of .is("[disabled]")
you may use .attr("disabled") != undefined
(jQuery 1.6+ will always return undefined
when the attribute is not set) but is()
is much more clear (thanks to Dave Stewart for this tip). Please note here I'm using the disabled
attribute in a non-standard way, if you care about this then replace attribute with a class and replace .is("[disabled]")
with .hasClass("disabled")
(adding and removing with addClass()
and removeClass()
).
Zoltán Tamási noted in a comment that "in some cases the click event is already bound to some "real" function (for example using knockoutjs) In that case the event handler ordering can cause some troubles. Hence I implemented disabled links by binding a return false handler to the link's touchstart
, mousedown
and keydown
events. It has some drawbacks (it will prevent touch scrolling started on the link)" but handling keyboard events also has the benefit to prevent keyboard navigation.
Note that if href
isn't cleared it's possible for the user to manually visit that page.
Clear the href
attribute. With this code you do not add an event handler but you change the link itself. Use this code to disable links:
$("td > a").each(function() {
this.data("href", this.attr("href"))
.attr("href", "javascript:void(0)")
.attr("disabled", "disabled");
});
And this one to re-enable them:
$("td > a").each(function() {
this.attr("href", this.data("href")).removeAttr("disabled");
});
Personally I do not like this solution very much (if you do not have to do more with disabled links) but it may be more compatible because of various way to follow a link.
Add/remove an onclick
function where you return false
, link won't be followed. To disable links:
$("td > a").attr("disabled", "disabled").on("click", function() {
return false;
});
To re-enable them:
$("td > a").removeAttr("disabled").off("click");
I do not think there is a reason to prefer this solution instead of the first one.
Styling is even more simple, whatever solution you're using to disable the link we did add a disabled
attribute so you can use following CSS rule:
a[disabled] {
color: gray;
}
If you're using a class instead of attribute:
a.disabled {
color: gray;
}
If you're using an UI framework you may see that disabled links aren't styled properly. Bootstrap 3.x, for example, handles this scenario and button is correctly styled both with disabled
attribute and with .disabled
class. If, instead, you're clearing the link (or using one of the others JavaScript techniques) you must also handle styling because an <a>
without href
is still painted as enabled.
Do not forget to also include an attribute aria-disabled="true"
together with disabled
attribute/class.
Use the Javascript string split() function.
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
This seems to work.
{{ form.fields.email.initial }}
purple.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you
Suggestions:
for example,
type
functionname( arguments )
{
if (something)
{
do stuff
}
else
{
do other stuff
}
switch (value)
{
case 'a':
astuff
break;
case 'b':
bstuff
//fallthrough //always comment fallthrough as intentional
case 'c':
break;
default: //always consider default, and handle it explicitly
break;
}
while ( the lights are on )
{
if ( something happened )
{
run around in circles
if ( you are scared ) //yeah, much more than 3-4 levels of indent are too many!
{
scream and shout
}
}
}
return typevalue; //always return something, you'll thank me later
}
With seconds!
$('.Timestamp').datetimepicker({
format: 'DD/MM/YYYY HH:mm:ss'
});
To skip future dates:
$(function () {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datetimepicker,#datetimepicker1').datetimepicker({
pickTime: false,
format: "DD-MM-YYYY",
maxDate: new Date(currentYear, currentMonth, currentDate + 1)
});
});
I used the approach with the custom converter:
public static class MapEntryConverter implements Converter {
public boolean canConvert(Class clazz) {
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
AbstractMap map = (AbstractMap) value;
for (Object obj : map.entrySet()) {
Entry entry = (Entry) obj;
writer.startNode(entry.getKey().toString());
context.convertAnother(entry.getValue());
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
// dunno, read manual and do it yourself ;)
}
}
But i changed the the serialization of the maps value to delegate to the MarshallingContext. This should improve the solution to work for composite map values and nested maps as well.
You could do:
if($('.input1').length && $('.input1').val().length)
length
evaluates to false
in a condition, when the value is 0
.
I think Octave only return one value which is the first return value, in your case, 'array'.
And Octave print it as "ans".
Others, 'listp','freep' were not printed.
Because it showed up within the function.
Try this out:
[ A, B, C] = initialize( 4 )
And the 'array','listp','freep' will print as A, B and C.
A possible reason for an empty $_POST
is that the request is not POST
, or not POST
anymore... It may have started out as post, but encountered a 301
or 302
redirect somewhere, which is switched to GET
!
Inspect $_SERVER['REQUEST_METHOD']
to check if this is the case.
See https://stackoverflow.com/a/19422232/109787 for a good discussion of why this should not happen but still does.
A complete working example from the code above.... for C++11:
#include <stdlib.h>
#include <stdio.h>
#include <functional>
#if __cplusplus <= 199711L
#error This file needs at least a C++11 compliant compiler, try using:
#error $ g++ -std=c++11 ..
#endif
using namespace std;
class EventHandler {
public:
void addHandler(std::function<void(int)> callback) {
printf("\nHandler added...");
// Let's pretend an event just occured
callback(1);
}
};
class MyClass
{
public:
MyClass(int);
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
EventHandler *pHandler;
int private_x;
};
MyClass::MyClass(int value) {
using namespace std::placeholders; // for `_1`
pHandler = new EventHandler();
private_x = value;
pHandler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x) {
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
printf("\nResult:%d\n\n", (x+private_x));
}
// Main method
int main(int argc, char const *argv[]) {
printf("\nCompiler:%ld\n", __cplusplus);
new MyClass(5);
return 0;
}
// where $1 is your .cpp file name... this is the command used:
// g++ -std=c++11 -Wall -o $1 $1.cpp
// chmod 700 $1
// ./$1
Output should be:
Compiler:201103
Handler added...
Result:6
You can use the contenteditable attribute on the cells, rows, or table in question.
Updated for IE8 compatibility
<table>
<tr><td><div contenteditable>I'm editable</div></td><td><div contenteditable>I'm also editable</div></td></tr>
<tr><td>I'm not editable</td></tr>
</table>
Just note that if you make the table editable, in Mozilla at least, you can delete rows, etc.
You'd also need to check whether your target audience's browsers supported this attribute.
As far as listening for the changes (so you can send to the server), see contenteditable change events
Use .env file to define dynamic values in docker-compse.yml. Be it port or any other value.
Sample docker-compose:
testcore.web:
image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
volumes:
- c:/logs:c:/logs
ports:
- ${TEST_CORE_PORT}:80
environment:
- CONSUL_URL=http://${CONSUL_IP}:8500
- HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}
Inside .env file you can define the value of these variables:
CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002
For completeness, in Numpy there are four maximum related functions. They fall into two different categories:
np.amax/np.max
, np.nanmax
: for single array order statisticsnp.maximum
, np.fmax
: for element-wise comparison of two arraysNaNs propagator np.amax/np.max
and its NaN ignorant counterpart np.nanmax
.
np.max
is just an alias of np.amax
, so they are considered as one function.
>>> np.max.__name__
'amax'
>>> np.max is np.amax
True
np.max
propagates NaNs while np.nanmax
ignores NaNs.
>>> np.max([np.nan, 3.14, -1])
nan
>>> np.nanmax([np.nan, 3.14, -1])
3.14
NaNs propagator np.maximum
and its NaNs ignorant counterpart np.fmax
.
Both functions require two arrays as the first two positional args to compare with.
# x1 and x2 must be the same shape or can be broadcast
np.maximum(x1, x2, /, ...);
np.fmax(x1, x2, /, ...)
np.maximum
propagates NaNs while np.fmax
ignores NaNs.
>>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([ nan, nan, 2.72])
>>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
array([-inf, 3.14, 2.72])
The element-wise functions are np.ufunc
(Universal Function), which means they have some special properties that normal Numpy function don't have.
>>> type(np.maximum)
<class 'numpy.ufunc'>
>>> type(np.fmax)
<class 'numpy.ufunc'>
>>> #---------------#
>>> type(np.max)
<class 'function'>
>>> type(np.nanmax)
<class 'function'>
And finally, the same rules apply to the four minimum related functions:
np.amin/np.min
, np.nanmin
; np.minimum
, np.fmin
.I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.
Here's a snippet of the code that worked for me:
int pageSize = 4;
int pageNumber = (page ?? 1);
//Used the following two formulas so that it doesn't round down on the returned integer
decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));
ViewBag.TotalPages = Math.Ceiling(totalPages);
//These next two functions could maybe be reduced to one function....would require some testing and building
viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
ViewBag.OnePageofTeachers = viewModel.Teachers;
ViewBag.PageNumber = pageNumber;
return View(viewModel);
I added
using.PagedList;
to my controller as the tutorial states.
Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.
@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.
Page @ViewBag.PageNumber of @ViewBag.TotalPages
@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))
Hope that works for you. Let me know if it works!!
Use npm outdated
to see Current and Latest version of all packages.
Then npm i packageName@versionNumber
to install specific version : example npm i [email protected]
.
Or npm i packageName@latest
to install latest version : example npm i browser-sync@latest
.
Keep in mind that search spiders don't index JS code. So, if you put your URL
inside JS code and make sure to also include it inside a traditional HTML link elsewhere on the page.
That is, if you want the linked pages to be indexed by Google, etc.
If any of these characters, '>', '<', '|' or '*', are used, a single or double quotes must be used
conda install [-y] package">=version"
conda install [-y] package'>=low_version, <=high_version'
conda install [-y] "package>=low_version, <high_version"
conda install -y torchvision">=0.3.0"
conda install openpyxl'>=2.4.10,<=2.6.0'
conda install "openpyxl>=2.4.10,<3.0.0"
where option -y, --yes Do not ask for confirmation.
Here is a summary:
Format Sample Specification Results
Exact qtconsole==4.5.1 4.5.1
Fuzzy qtconsole=4.5 4.5.0, 4.5.1, ..., etc.
>=, >, <, <= "qtconsole>=4.5" 4.5.0 or higher
qtconsole"<4.6" less than 4.6.0
OR "qtconsole=4.5.1|4.5.2" 4.5.1, 4.5.2
AND "qtconsole>=4.3.1,<4.6" 4.3.1 or higher but less than 4.6.0
Potion of the above information credit to Conda Cheat Sheet
Tested on conda 4.7.12
session_start();
echo session_id();
I'm using a simplyfied version (just using position relative) based on @SimonEast answer:
li:before {
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
position: relative;
margin-right: 10px;
top: 3px;
color: #ccc;
}
I just spent several days checking parameters because I have to pass 60 to a stored procedure. It turns out that the one of the variable names (which I load into a list and pass to the Oracle Write method I created) had a space in the name at the end. When comparing to the variables in the stored procedure they were the same, but in the editor I used to compare them, I didnt notice the extra space. Drove me crazy for the last 4 days trying everything I could find, and changing even the .net Oracle driver. Just wanted to throw that out here so it can help someone else. We tend to concentrate on the characters and ignore the spaces. . .
\b
matches at word boundaries (without actually matching any characters), so the following should do what you want:
\bstackoverflow\b
<bindings>
<wsHttpBinding>
<binding name="wsHttpBinding_Username" maxReceivedMessageSize="20000000" maxBufferPoolSize="20000000">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" establishSecurityContext="false"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint
binding="wsHttpBinding"
bindingConfiguration="wsHttpBinding_Username"
contract="Exchange.Exweb.ExchangeServices.ExchangeServicesGenericProxy.ExchangeServicesType"
name="ServicesFacadeEndpoint" />
</client>
If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.
Also, this is the same in a slightly smaller footprint:
if(borrar() !== !1)
class ex1 {
public static void main(String args[]){
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("c = " + c);
}
}
// Output
javac ex1.java
java ex1 10 20
c = 30
Best that works for me:
.left{
width:140px;
float:left;
height:100%;
}
.right{
margin-left:140px;
}
create table test_table(
id integer not null auto_increment primary key,
stamp_created timestamp default '0000-00-00 00:00:00',
stamp_updated timestamp default now() on update now()
);
source: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/
We Can override the blue color in to our custom color It works for Internet Explorer, Firefox and Chrome:
By using this below following CSS:
option: checked, option: hover {
Color: #ffffff;
background: #614767 repeat url("data:image/gif;base64,R0lGODlh8ACgAPAAAGFGZQAAACH5BAAAAAAALAAAAADwAKAAAAL+hI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+QkaKjpKWmp6ipqqusra6voKGys7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NXW19jZ2tvc3d7f0NHi4+Tl5ufo6err7O3u7+Dh8vP09fb3+Pn6+/z9/v/w8woMCBBAsaPIgwocKFDBs6fAgxosSJFCtavIhRVgEAOw");
}
Combining answers by Petr and Sarfraz, I arrive at the following.
On page1.html:
<a href="page2.html#elementID">Jump</a>
On page2.html:
<script type="text/javascript">
$(document).ready(function() {
$('html, body').hide();
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0);
}
else {
$('html, body').show();
}
});
</script>
On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.
But, What if you want to destroy the token on the Node server -
The problem with JWT package is that it doesn't provide any method or way to destroy the token.
So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT
This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method
it works in this way :
1) Install jwt-redis from npm
2) To Create -
var redis = require('redis');
var JWTR = require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);
jwtr.sign(payload, secret)
.then((token)=>{
// your code
})
.catch((error)=>{
// error handling
});
3) To verify -
jwtr.verify(token, secret);
4) To Destroy -
jwtr.destroy(token)
Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.
Use The Below code:
func filterContentForSearchText(searchText:NSString, scopes scope:NSString)
{
//var searchText = ""
var resultPredicate : NSPredicate = NSPredicate(format: "name contains[c]\(searchText)", nil)
//var recipes : NSArray = NSArray()
var searchResults = recipes.filteredArrayUsingPredicate(resultPredicate)
}
Sincerely asking, what is a word? If your assumption is that a word consists of alphabetic characters only, you are wrong since words such as can't
will be destroyed into pieces (such as can
and t
) if you remove punctuation before tokenisation, which is very likely to affect your program negatively.
Hence the solution is to tokenise and then remove punctuation tokens.
import string
from nltk.tokenize import word_tokenize
tokens = word_tokenize("I'm a southern salesman.")
# ['I', "'m", 'a', 'southern', 'salesman', '.']
tokens = list(filter(lambda token: token not in string.punctuation, tokens))
# ['I', "'m", 'a', 'southern', 'salesman']
...and then if you wish, you can replace certain tokens such as 'm
with am
.
I Encounter this problem before. I suspect that is some of ur cells are link towards other sheet, which the other sheets is returning #NAME? which ends up the current sheets is not working on calculation.
Try solve ur other sheets that is linked
Best: min(d, key=d.get)
-- no reason to interpose a useless lambda
indirection layer or extract items or keys!
You may get this error when trying to browse an ASP.NET application.
The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."
However, this error occurs primarily out of two scenarios.
To resolve it, right click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.
web.config
of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point). Mostly, we have the practice of adding web.config
in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).
If you need to trigger a specific event you can override the method addClass() to fire a custom event called 'classadded'.
Here how:
(function() {
var ev = new $.Event('classadded'),
orig = $.fn.addClass;
$.fn.addClass = function() {
$(this).trigger(ev, arguments);
return orig.apply(this, arguments);
}
})();
$('#myElement').on('classadded', function(ev, newClasses) {
console.log(newClasses + ' added!');
console.log(this);
// Do stuff
// ...
});
<h1 id="foo">Foo Title</h1>
is what should be used. Don't use an anchor unless you want a link.
I've had the same problem when was doing fragment transaction while activity creation.
The core problem is what Nick has already pointed out - view tree has not been inflated yet. But his solution didn't work - the same exception in onResume, onPostCreate etc.
The solution is to add callback to container fragment to signal when it's ready:
public class MyContainerFragment extends Fragment {
public static interface Callbacks {
void onMyContainerAttached();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "--- onAttach");
((Callbacks) activity).onMyContainerAttached();
}
//... rest of code
}
And then in activity:
public class MainActivity extends Activity
implements MyContainerFragment.Callbacks
{
@Override
public void onMyContainerAttached() {
getFragmentManager()
.beginTransaction()
.replace(R.id.containerFrame, new MyFragment())
.commit();
}
//...
}
For those interested in the details - you can see what's inside the public key file (generated as explained above), by doing this:-
openssl rsa -noout -text -inform PEM -in key.pub -pubin
or for the private key file, this:-
openssl rsa -noout -text -in key.private
which outputs as text on the console the actual components of the key (modulus, exponents, primes, ...)
I wouldn't bother doing it in Linq2SQL. Create a stored Procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.
It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:
my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
for i in range(my_strings.count(undesirable_string)):
my_strings.remove(undesirable_string)
which changes my_strings to ['a', 'c', 'e']
If you are on windows, what i suppose you need to do set the PATH like this:
SET PATH=%M2%
furthermore i assume you need to set your path to something like C:...\apache-maven-3.0.3\ cause this is the default folder for the windows archive. On the other i assume you need to add the path of maven to your and not set it to only maven so you setting should look like this:
SET PATH=%PATH%;%M2%
I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping
For example
@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}
It may help others
If you like to get a list of all values of checked checkboxes (e.g. to send them as a list in one AJAX call to the server), you could get that list with:
var list = $("input[name='bla[]']:checked").map(function () {
return this.value;
}).get();
settings.json
:{}
icon at the top right corner to open the settings.json
:
Add excluded folders to files.exclude
. Also check out search.exclude
and files.watcherExclude
as they might be useful too. This snippet contains their explanations and defaults:
{
// Configure glob patterns for excluding files and folders.
// For example, the files explorer decides which files and folders to show
// or hide based on this setting.
// Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true
},
// Configure glob patterns for excluding files and folders in searches.
// Inherits all glob patterns from the `files.exclude` setting.
// Read more about glob patterns [here](https://code.visualstudio.com/docs/editor/codebasics#_advanced-search-options).
"search.exclude": {
"**/node_modules": true,
"**/bower_components": true
},
// Configure glob patterns of file paths to exclude from file watching.
// Patterns must match on absolute paths
// (i.e. prefix with ** or the full path to match properly).
// Changing this setting requires a restart.
// When you experience Code consuming lots of cpu time on startup,
// you can exclude large folders to reduce the initial load.
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/*/**": true
}
}
For more details on the other settings, see the official settings.json
reference.
try this:
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)
document.write(a);
function Test(a,b)
{
return a > b ? true : false;
}
Using the java.time package in Java 8:
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end));
Output is in ISO 8601 Duration format: PT1M3.553S
(1 minute and 3.553 seconds).
There are actually two accepted best practices:
func New() YourTyp
or if you have several such types in your package functions func NewYourType1() YourType1
and so on.Document if a zero value of your type is usable or not (in which case it has to be set up by one of the New...
functions. (For the "traditionalist" oops: Someone who does not read the documentation won't be able to use your types properly, even if he cannot create objects in undefined states.)
Someone might find this (git show-branch
--current
) helpful. The current branch is shown with a * mark.
host-78-65-229-191:idp-mobileid user-1$ git show-branch --current
! [CICD-1283-pipeline-in-shared-libraries] feat(CICD-1283): Use latest version of custom release plugin.
* [master] Merge pull request #12 in CORES/idp-mobileid from feature/fix-schema-name to master
--
+ [CICD-1283-pipeline-in-shared-libraries] feat(CICD-1283): Use latest version of custom release plugin.
+ [CICD-1283-pipeline-in-shared-libraries^] feat(CICD-1283): Used the renamed AWS pipeline.
+ [CICD-1283-pipeline-in-shared-libraries~2] feat(CICD-1283): Point to feature branches of shared libraries.
-- [master] Merge pull request #12 in CORES/idp-mobileid from feature/fix-schema-name to master
Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:
var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
if (item != null)
{
TheValue = item.Value;
}
I fixed it by changing line 10 of:
/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js
from:
bson = require('../build/Release/bson');
to:
bson = require('bson');
You can modify the output format:
>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
I had the same problem. The problem, by some strange reason Chrome turned himself as the default tool to open a mailto: link. The solution, put your mail client as the default app to open it. How to : http://windows.microsoft.com/en-nz/windows/change-default-programs#1TC=windows-7
Good luck
This is a good approach to show animation in and out using jQuery
$(document).ready(function() {
// show the alert
$(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
$(this).remove();
});
});
Per the docs, the exception types you may need to catch are:
GuzzleHttp\Exception\ClientException
for 400-level errorsGuzzleHttp\Exception\ServerException
for 500-level errorsGuzzleHttp\Exception\BadResponseException
for both (it's their superclass)Code to handle such errors thus now looks something like this:
$client = new GuzzleHttp\Client;
try {
$client->get('http://google.com/nosuchpage');
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
you can redirect stderr.
more explanation here, but having a command like:
MyCommand >log.txt 2>errors.txt
should grab the data you are looking for.
Also, as a trick, Windows bypasses that limitation if the path is prefixed with \\?\
(msdn)
Another trick if you have a root or destination that starts with a long path, perhaps SUBST
will help:
SUBST Q: "C:\Documents and Settings\MyLoginName\My Documents\MyStuffToBeCopied"
Xcopy Q:\ "d:\Where it needs to go" /s /e
SUBST Q: /D
This should do the trick
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
then you enumerate over the controls like so
foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
// do something with tb here
}