Add the jar files to your library(if using netbeans) and modify your manifest's file classpath
as follows:
Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar
a similar answer exists here
The headers are entirely encrypted. The only information going over the network 'in the clear' is related to the SSL setup and D/H key exchange. This exchange is carefully designed not to yield any useful information to eavesdroppers, and once it has taken place, all data is encrypted.
UPDATE
You can use document.location.reload(true)
as mentioned below instead of the forced trick below.
Replace your HTML with this:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
background-image: url('../Images/Black-BackGround.gif');
background-repeat: repeat;
}
body td {
font-Family: Arial;
font-size: 12px;
}
#Nav a {
position:relative;
display:block;
text-decoration: none;
color:black;
}
</style>
<script type="text/javascript">
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 35000);
if ( window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
}
</script>
</head>
<body><!-- BODY CONTENT HERE --></body>
</html>
/* here is what works for me - set up as a class */
.button {
text-align: center;
display: block;
margin: 0 auto;
}
/* you can set padding and width to whatever works best */
Command to delete a branch is as follows:
svn delete -m "<your message>" <branch url>
If you wish to not fetch/checkout the entire repo, execute the following command on your terminal:
1) get the absolute path of the directory that will contain your working copy
> pwd
2) Start svn code checkout
> svn checkout <branch url> <absolute path from point 1>
The above steps will get you the files inside the branch folder and not the entire folder.
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
There is difference between collision and duplication. Collision means hashcode and bucket is same, but in duplicate, it will be same hashcode,same bucket, but here equals method come in picture.
Collision detected and you can add element on existing key. but in case of duplication it will replace new value.
The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command "set standard_conforming_strings=on;". Then use "E" before your string including backslashes that you want postgresql to intrepret.
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
Use these two commands (for Java 8):
sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment
Add a parameter of type UriComponentsBuilder
to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo
to point at a different controller using the same prefix).
Download Microsoft Rdlc Report Designer for Visual Studio from this link. https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftRdlcReportDesignerforVisualStudio-18001
Microsoft explain the steps in details:
The following steps summarizes the above article.
Adding the Report Viewer control to a new web project:
Create a new ASP.NET Empty Web Site or open an existing ASP.NET project.
Install the Report Viewer control NuGet package via the NuGet package manager console. From Visual Studio -> Tools -> NuGet Package Manager -> Package Manager Console
Install-Package Microsoft.ReportingServices.ReportViewerControl.WebForms
Add a new .aspx page to the project and register the Report Viewer control assembly for use within the page.
<%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
Add a ScriptManagerControl to the page.
Add the Report Viewer control to the page. The snippet below can be updated to reference a report hosted on a remote report server.
<rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
<ServerReport ReportPath="" ReportServerUrl="" /></rsweb:ReportViewer>
The final page should look like the following.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Sample" %>
<%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote">
<ServerReport ReportServerUrl="https://AContosoDepartment/ReportServer" ReportPath="/LatestSales" />
</rsweb:ReportViewer>
</form>
</body>
Assuming ruby interpreter is in your PATH (it should be), you simply run
ruby your_file.rb
For:
sqlcmd -s, -W -Q "set nocount on; select * from [DATABASE].[dbo].[TABLENAME]" | findstr /v /c:"-" /b > "c:\dirname\file.csv"
Where:
[DATABASE].[dbo].[TABLENAME]
is table to write.c:\dirname\file.csv
is file to write to (surrounded in quotes to handle a path with spaces).Note: I tend to avoid bcp
: it is legacy, it predates sqlcmd
by a decade, and it never seems to work without causing a whole raft of headaches.
-- Export table [DATABASE].[dbo].[TABLENAME] to .csv file c:\dirname\file.csv
exec master..xp_cmdshell 'sqlcmd -s, -W -Q "set nocount on; select * from [DATABASE].[dbo].[TABLENAME]" | findstr /v /c:"-" /b > "c:\dirname\file.csv"'
Troubleshoooting: must enable xp_cmdshell within MSSQL.
File: file.csv
:
ID,Name,Height
1,Bob,192
2,Jane,184
3,Harry,186
As fast as theoretically possible: same speed as bcp
, and many times faster than manually exporting from SSMS.
In sqlcmd
:
-s,
puts a comma between each column.-W
eliminates padding either side of the values.set nocount on
eliminates a garbage line at the end of the query.For findstr
:
--- ----- ---- ---- ----- --
./v /c:"-"
matches any line that starts with "-"./b
returns all other lines.In Excel:
In Python:
import pandas as pd
df_raw = pd.read_csv("c:\dirname\file.csv")
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.
Here's a function that acts as a thin wrapper around MutationObserver. The only requirement is that the browser support MutationObserver; there is no dependency on JQuery. Run the snippet below to see a working example.
function waitForMutation(parentNode, isMatchFunc, handlerFunc, observeSubtree, disconnectAfterMatch) {_x000D_
var defaultIfUndefined = function(val, defaultVal) {_x000D_
return (typeof val === "undefined") ? defaultVal : val;_x000D_
};_x000D_
_x000D_
observeSubtree = defaultIfUndefined(observeSubtree, false);_x000D_
disconnectAfterMatch = defaultIfUndefined(disconnectAfterMatch, false);_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
mutations.forEach(function(mutation) {_x000D_
if (mutation.addedNodes) {_x000D_
for (var i = 0; i < mutation.addedNodes.length; i++) {_x000D_
var node = mutation.addedNodes[i];_x000D_
if (isMatchFunc(node)) {_x000D_
handlerFunc(node);_x000D_
if (disconnectAfterMatch) observer.disconnect();_x000D_
};_x000D_
}_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
observer.observe(parentNode, {_x000D_
childList: true,_x000D_
attributes: false,_x000D_
characterData: false,_x000D_
subtree: observeSubtree_x000D_
});_x000D_
}_x000D_
_x000D_
// Example_x000D_
waitForMutation(_x000D_
// parentNode: Root node to observe. If the mutation you're looking for_x000D_
// might not occur directly below parentNode, pass 'true' to the_x000D_
// observeSubtree parameter._x000D_
document.getElementById("outerContent"),_x000D_
// isMatchFunc: Function to identify a match. If it returns true,_x000D_
// handlerFunc will run._x000D_
// MutationObserver only fires once per mutation, not once for every node_x000D_
// inside the mutation. If the element we're looking for is a child of_x000D_
// the newly-added element, we need to use something like_x000D_
// node.querySelector() to find it._x000D_
function(node) {_x000D_
return node.querySelector(".foo") !== null;_x000D_
},_x000D_
// handlerFunc: Handler._x000D_
function(node) {_x000D_
var elem = document.createElement("div");_x000D_
elem.appendChild(document.createTextNode("Added node (" + node.innerText + ")"));_x000D_
document.getElementById("log").appendChild(elem);_x000D_
},_x000D_
// observeSubtree_x000D_
true,_x000D_
// disconnectAfterMatch: If this is true the hanlerFunc will only run on_x000D_
// the first time that isMatchFunc returns true. If it's false, the handler_x000D_
// will continue to fire on matches._x000D_
false);_x000D_
_x000D_
// Set up UI. Using JQuery here for convenience._x000D_
_x000D_
$outerContent = $("#outerContent");_x000D_
$innerContent = $("#innerContent");_x000D_
_x000D_
$("#addOuter").on("click", function() {_x000D_
var newNode = $("<div><span class='foo'>Outer</span></div>");_x000D_
$outerContent.append(newNode);_x000D_
});_x000D_
$("#addInner").on("click", function() {_x000D_
var newNode = $("<div><span class='foo'>Inner</span></div>");_x000D_
$innerContent.append(newNode);_x000D_
});
_x000D_
.content {_x000D_
padding: 1em;_x000D_
border: solid 1px black;_x000D_
overflow-y: auto;_x000D_
}_x000D_
#innerContent {_x000D_
height: 100px;_x000D_
}_x000D_
#outerContent {_x000D_
height: 200px;_x000D_
}_x000D_
#log {_x000D_
font-family: Courier;_x000D_
font-size: 10pt;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h2>Create some mutations</h2>_x000D_
<div id="main">_x000D_
<button id="addOuter">Add outer node</button>_x000D_
<button id="addInner">Add inner node</button>_x000D_
<div class="content" id="outerContent">_x000D_
<div class="content" id="innerContent"></div>_x000D_
</div>_x000D_
</div>_x000D_
<h2>Log</h2>_x000D_
<div id="log"></div>
_x000D_
I use @gnarf's method, though I fall back on document.writeln
ing a <script>
tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:
if (horus.script.broken) {
document.writeln('<script type="text/javascript" src="'+script+'"></script>');
horus.script.loaded(script);
} else {
var s=document.createElement('script');
s.type='text/javascript';
s.src=script;
s.async=true;
if (horus.brokenDOM){
s.onreadystatechange=
function () {
if (this.readyState=='loaded' || this.readyState=='complete'){
horus.script.loaded(script);
}
}
}else{
s.onload=function () { horus.script.loaded(script) };
}
document.head.appendChild(s);
}
where horus.script.loaded()
notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).
It looks like Java is trying to convert an empty string into a number. Do you have an empty line at the end of the series of numbers?
You could probably fix the code like this
String s = in.readLine();
int i = 0;
while (s != null) {
// Skip empty lines.
s = s.trim();
if (s.length() == 0) {
continue;
}
tall[i] = Integer.parseInt(s); // This is line 19.
System.out.println(tall[i]);
s = in.readLine();
i++;
}
in.close();
When you get the error: implicit declaration of function
it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname
and look at the SYNOPSIS
section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search.
Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,
You are using a function for which the compiler has not seen a declaration ("prototype") yet.
ProgressBar bar;
private Handler progressBarHandler = new Handler();
GradientDrawable progressGradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, new int[]{
0xff1e90ff,0xff006ab6,0xff367ba8});
ClipDrawable progressClipDrawable = new ClipDrawable(
progressGradientDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
Drawable[] progressDrawables = {
new ColorDrawable(0xffffffff),
progressClipDrawable, progressClipDrawable};
LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);
int status = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.startup);
bar = (ProgressBar) findViewById(R.id.start_page_progressBar);
bar.setProgress(0);
bar.setMax(100);
progressLayerDrawable.setId(0, android.R.id.background);
progressLayerDrawable.setId(1, android.R.id.secondaryProgress);
progressLayerDrawable.setId(2, android.R.id.progress);
bar.setProgressDrawable(progressLayerDrawable);
}
This helped me to set a custom color to progressbar through code. Hope it helps
I would suggest to read up a bit on the syntax. See here.
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
getattr(x, 'y')
is equivalent to x.y
setattr(x, 'y', v)
is equivalent to x.y = v
delattr(x, 'y')
is equivalent to del x.y
If you turn things around, you can declare your base class abstract, and have descendants declare setUp and tearDown methods (without annotations) that are called in the base class' annotated setUp and tearDown methods.
I got tired of manually checking for plugin updates so created a tool to do it for me: https://github.com/dpa99c/cordova-check-plugins
Install it globally:
$ npm install -g cordova-check-plugins
Then run from the root of your Cordova project. You can optionally update outdated plugins interactively or automatically, e.g.
$ cordova-check-plugins --update=auto
In MacOS Catalina, run
sudo nano ~/.bash_profile
In bash_profile, add:
export JAVA_HOME=$(/usr/libexec/java_home)
source ~/.bash_profile
Verify by running java --version
<div>It's working fine.....</div>
div
{
height: calc(100vh - 8vw);
background: #000;
overflow:visible;
color: red;
}
Check here this css code right now support All browser without Opera
Live
A more concise--but not necessarily faster--method is to use DataFrame.isin()
and DataFrame.any()
In [27]: n = 10
In [28]: df = DataFrame(randint(4, size=(n, 2)), columns=list('ab'))
In [29]: df
Out[29]:
a b
0 0 0
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
7 3 0
8 1 1
9 2 2
[10 rows x 2 columns]
In [30]: df.isin([1, 2])
Out[30]:
a b
0 False False
1 True True
2 True True
3 True False
4 True False
5 False True
6 True True
7 False False
8 True True
9 True True
[10 rows x 2 columns]
In [31]: df.isin([1, 2]).any(1)
Out[31]:
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
dtype: bool
In [32]: df.loc[df.isin([1, 2]).any(1)]
Out[32]:
a b
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
8 1 1
9 2 2
[8 rows x 2 columns]
$list = array(
'Tunisia' => 'Tunis',
'Germany' => 'Berlin',
'Italy' => 'Rom',
'Egypt' => 'Cairo'
);
$afterIndex = 2;
$newVal= array('Palestine' => 'Jerusalem');
$newList = array_merge(array_slice($list,0,$afterIndex+1), $newVal,array_slice($list,$afterIndex+1));
Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
If you want to just compare dates,
yourdatetime.date() < datetime.today().date()
Or, obviously,
yourdatetime.date() == datetime.today().date()
If you want to check that they're the same date.
The documentation is usually helpful. It is also usually the first google result for python thing_i_have_a_question_about
. Unless your question is about a function/module named "snake".
Basically, the datetime
module has three types for storing a point in time:
date
for year, month, day of monthtime
for hours, minutes, seconds, microseconds, time zone infodatetime
combines date and time. It has the methods date()
and time()
to get the corresponding date
and time
objects, and there's a handy combine
function to combine date
and time
into a datetime
.For those who are working with aws I would highly recommend working with EC2 Instance Connect.
Amazon EC2 Instance Connect provides a simple and secure way to connect to your instances using Secure Shell (SSH).
With EC2 Instance Connect, you use AWS Identity and Access Management (IAM) policies and principles to control SSH access to your instances, removing the need to share and manage SSH keys.
After installing the relevant packages (pip install ec2instanceconnectcli
or cloning the repo directly) you can connect very easy to multiple EC2 instances by just changing the instance id:
What is happening behind the scenes?
When you connect to an instance using EC2 Instance Connect, the Instance Connect API pushes a one-time-use SSH public key to the instance metadata where it remains for 60 seconds. An IAM policy attached to your IAM user authorizes your IAM user to push the public key to the instance metadata.
The SSH daemon uses AuthorizedKeysCommand and AuthorizedKeysCommandUser, which are configured when Instance Connect is installed, to look up the public key from the instance metadata for authentication, and connects you to the instance.
(*) Amazon Linux 2 2.0.20190618 or later and Ubuntu 20.04 or later comes preconfigured with EC2 Instance Connect. For other supported Linux distributions, you must set up Instance Connect for every instance that will support using Instance Connect. This is a one-time requirement for each instance.
Links:
Set up EC2 Instance Connect
Connect using EC2 Instance Connect
Securing your bastion hosts with Amazon EC2 Instance Connect
Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.
But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.
So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.
using System.Text.RegularExpressions;
private void Form1_Shown(object sender, EventArgs e)
{
filterTextBoxContent(textBox1);
}
string pattern = @"[^0-9^+^\-^/^*^(^)]";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
filterTextBoxContent(textBox1);
}
private bool filterTextBoxContent(TextBox textBox)
{
string text = textBox.Text;
MatchCollection matches = Regex.Matches(text, pattern);
bool matched = false;
int selectionStart = textBox.SelectionStart;
int selectionLength = textBox.SelectionLength;
int leftShift = 0;
foreach (Match match in matches)
{
if (match.Success && match.Captures.Count > 0)
{
matched = true;
Capture capture = match.Captures[0];
int captureLength = capture.Length;
int captureStart = capture.Index - leftShift;
int captureEnd = captureStart + captureLength;
int selectionEnd = selectionStart + selectionLength;
text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);
textBox.Text = text;
int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);
if (boundSelectionStart == -1)
{
if (boundSelectionEnd == 0)
{
selectionLength -= selectionEnd - captureStart;
}
else if (boundSelectionEnd == 1)
{
selectionLength -= captureLength;
}
}
else if (boundSelectionStart == 0)
{
if (boundSelectionEnd == 0)
{
selectionStart = captureStart;
selectionLength = 0;
}
else if (boundSelectionEnd == 1)
{
selectionStart = captureStart;
selectionLength -= captureEnd - selectionStart;
}
}
else if (boundSelectionStart == 1)
{
selectionStart -= captureLength;
}
leftShift++;
}
}
textBox.SelectionStart = selectionStart;
textBox.SelectionLength = selectionLength;
return matched;
}
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
$limit=5; // for exemple
$query = $this->getDoctrine()->getEntityManager()->createQuery(
'// your request')
->setMaxResults($limit);
$results = $query->getResult();
// Done
//You may use this example. Might be help you...
$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
->join("items","items.user_id","=","users.id")
->join("jobs",function($join){
$join->on("jobs.user_id","=","users.id")
->on("jobs.item_id","=","items.id");
})
->get();
print_r($user);
Try adding $(document).ready(function(){
to the beginning of your script, and then });
. Also, does the div
have the id in it properly, i.e., as an id, not a class, etc.?
VS 17 Community Edition is free. You just need to sign-in with your Microsoft account and everything will be fine again.
You can use JavaScript Timing Events to call function after certain interval of time:
This shows the alert box after 3 seconds:
setInterval(function(){alert("Hello")},3000);
You can use two method of time event in javascript.i.e.
setInterval()
: executes a function, over and over again, at
specified time intervalssetTimeout()
: executes a function, once, after waiting a
specified number of millisecondsmap(lambda s: s.strip(), mylist)
would be a little better than explicitly looping. Or for the whole thing at once: map(lambda s:s.strip(), string.split(','))
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You can use something like code below, if you need to affect only specific value, and not touch others:
view.getLayoutParams().width = newWidth;
This is a stronger regex replace that won't replace %% that are already doubled in the input.
str = str.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%");
In C++ the C-style initializers were replaced by constructors which by compile time can ensure that only valid initializations are performed (i.e. after initialization the object members are consistent).
It is a good practice, but sometimes a pre-initialization is handy, like in your example. OOP solves this by abstract classes or creational design patterns.
In my opinion, using this secure way kills the simplicity and sometimes the security trade-off might be too expensive, since simple code does not need sophisticated design to stay maintainable.
As an alternative solution, I suggest to define macros using lambdas to simplify the initialization to look almost like C-style:
struct address {
int street_no;
const char *street_name;
const char *city;
const char *prov;
const char *postal_code;
};
#define ADDRESS_OPEN [] { address _={};
#define ADDRESS_CLOSE ; return _; }()
#define ADDRESS(x) ADDRESS_OPEN x ADDRESS_CLOSE
The ADDRESS macro expands to
[] { address _={}; /* definition... */ ; return _; }()
which creates and calls the lambda. Macro parameters are also comma separated, so you need to put the initializer into brackets and call like
address temp_address = ADDRESS(( _.city = "Hamilton", _.prov = "Ontario" ));
You could also write generalized macro initializer
#define INIT_OPEN(type) [] { type _={};
#define INIT_CLOSE ; return _; }()
#define INIT(type,x) INIT_OPEN(type) x INIT_CLOSE
but then the call is slightly less beautiful
address temp_address = INIT(address,( _.city = "Hamilton", _.prov = "Ontario" ));
however you can define the ADDRESS macro using general INIT macro easily
#define ADDRESS(x) INIT(address,x)
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 20px;
resize: both;
overflow: auto;
}
img{
height: 100%;
width: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<h1>The resize Property</h1>
<div>
<p>Let the user resize both the height and the width of this 1234567891011 div
element.
</p>
<p>To resize: Click and drag the bottom right corner of this div element.</p>
<img src="images/scenery.jpg" alt="Italian ">
</div>
<p><b>Note:</b> Internet Explorer does not support the resize property.</p>
</body>
</html>
I found a very nice thread on the net that explains the difference in a very straightforward way : http://www.thestudentroom.co.uk/showthread.php?t=232168.
Kruskal's algorithm will grow a solution from the cheapest edge by adding the next cheapest edge, provided that it doesn't create a cycle.
Prim's algorithm will grow a solution from a random vertex by adding the next cheapest vertex, the vertex that is not currently in the solution but connected to it by the cheapest edge.
Here attached is an interesting sheet on that topic.
If you implement both Kruskal and Prim, in their optimal form : with a union find and a finbonacci heap respectively, then you will note how Kruskal is easy to implement compared to Prim.
Prim is harder with a fibonacci heap mainly because you have to maintain a book-keeping table to record the bi-directional link between graph nodes and heap nodes. With a Union Find, it's the opposite, the structure is simple and can even produce directly the mst at almost no additional cost.
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Take a look at the Oracle Documentation.
Starting from JDK 1.4 an Application terminates if:
Cornercases:
The document states that some packages create displayable components without releasing them.A program which calls Toolkit.getDefaultToolkit() won't terminate. is among others given as an example.
Also other Processes can keep AWT alive when they, for what ever reason, are sending events into the native event queue.
Also I noticed that on some Systems it takes a coupple of seconds before the Application actually terminates.
Hope this tip will save someone else's life. In my case the problem was that I ran out of memory, but only slightly, was hard to think about it. Wasted 3hrs on that. I recommend running:
sudo htop
or
sudo free -m
...along with running problematic requests on the server to see if your memory doesn't run out. And if it does like in my case, you need to create a swap file (unless you already have one).
I have followed this tutorial to create swap file on Ubuntu Server 14.04 and it worked just fine: http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/
You have not mentioned how value is changed. I have used similar functionality when user is entering value. i.e. entering and leaving edit mode.
Using CellEndEdit event of datagridview.
private void dgMapTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
double newInteger;
if (double.TryParse(dgMapTable[e.ColumnIndex,e.RowIndex].Value.ToString(), out newInteger)
{
if (newInteger < 0 || newInteger > 50)
{
dgMapTable[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
dgMapTable[e.ColumnIndex, e.RowIndex].ErrorText
= "Keep value in Range:" + "0 to " + "50";
}
}
}
You may add logic for clearing error notification in a similar way.
if in your case, if data is loaded programmatically, then CellLeave event can be used with same code.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
break;
case DisplayMetrics.DENSITY_MEDIUM:
break;
case DisplayMetrics.DENSITY_HIGH:
break;
}
This will work on API level 4 and higher.
To extend vlad2135's answer (read his first); that is how you set up Python debugging in Visual Studio Code with Don Jayamanne's great Python extension (which is a pretty full featured IDE for Python these days, and arguably one of Visual Studio Code's best language extensions, IMO).
Basically, when you click the gear icon, it creates a launch.json file in your .vscode
directory in your workspace. You can also make this yourself, but it's probably just simpler to let Visual Studio Code do the heavy lifting. Here's an example file:
You'll notice something cool after you generate it. It automatically created a bunch of configurations (most of mine are cut off; just scroll to see them all) with different settings and extra features for different libraries or environments (like Django).
The one you'll probably end up using the most is Python; which is a plain (in my case C)Python debugger and is easiest to work with settings wise.
I'll make a short walkthrough of the JSON attributes for this one, since the others use the pretty much same configuration with only different interpreter paths and one or two different other features there.
"launch"
, but changing it to "attach"
allows the debugger to attach to an already running Python process. Instead of changing it, add a configuration of type attach and use that.false
if you don't want it, true
otherwise."${workspaceRoot}"
is the root folder you opened up as your workspace (When you go over to the file icon, the base open folder). Another neat trick if you want to get your program running quickly, or you have multiple entry points to your program is to set this to "${file}"
which will start debugging at the file you have open and in focus in the moment you hit debug."${workspaceRoot}"
.python file.py [args]
into your terminal; passing each JSON string in the list to the program in order.You can go here for more information on the Visual Studio Code file variables you can use to configure your debuggers and paths.
You can go here for the extension's own documentation on launch options, with both optional and required attributes.
You can click the Add Configuration button at the bottom right if you don't see the config template already in the file. It'll give you a list to auto generate a configuration for most of the common debug processes out there.
Now, as per vlad's answer, you may add any breakpoints you need as per normal visual debuggers, choose which run configuration you want in the top left dropdown menu and you can tap the green arrow to the left to the configuration name to start your program.
Pro tip: Different people on your team use different IDEs and they probably don't need your configuration files. Visual Studio Code nearly always puts it's IDE files in one place (by design for this purpose; I assume), launch or otherwise so make sure to add directory .vscode/
to your .gitignore if this is your first time generating a Visual Studio Code file (this process will create the folder in your workspace if you don't have it already)!
just put the autoplay="false" on source tag.. :)
In more modern browsers, querySelector
allows us to retrieve the selected option in one statement, using the :checked
pseudo-class. From the selected option, we can gather whatever information we need:
const opt = document.querySelector('#ddlViewBy option:checked');_x000D_
// opt is now the selected option, so_x000D_
console.log(opt.value, 'is the selected value');_x000D_
console.log(opt.text, "is the selected option's text");
_x000D_
<select id="ddlViewBy">_x000D_
<option value="1">test1</option>_x000D_
<option value="2" selected="selected">test2</option>_x000D_
<option value="3">test3</option>_x000D_
</select>
_x000D_
For modern browsers, use td:nth-child(2)
for the second td
, and td:nth-child(3)
for the third. Remember that these retrieve the second and third td
for every row.
If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.
It's just mv srcdir/* targetdir/
.
If there are too many files in srcdir
you might want to try something like the following approach:
cd srcdir
find -exec mv {} targetdir/ +
In contrast to \;
the final +
collects arguments in an xargs
like manner instead of executing mv
once for every file.
Although, I'm a big fan of Kanban Tool service (it has everything you need except free of charge) and therefore it's difficult for me to stay objective, I think that should go for Trello or Kanban Flow. Both are free and both provide basic features that are essential for agile process managers and their teams.
I tried @Aaron's solution and it didn't quite work for me, because it would re-add my keys every time I opened a new tab in my terminal. So I modified it a bit(note that most of my keys are also password-protected so I can't just send the output to /dev/null):
added_keys=`ssh-add -l`
if [ ! $(echo $added_keys | grep -o -e my_key) ]; then
ssh-add "$HOME/.ssh/my_key"
fi
What this does is that it checks the output of ssh-add -l
(which lists all keys that have been added) for a specific key and if it doesn't find it, then it adds it with ssh-add
.
Now the first time I open my terminal I'm asked for the passwords for my private keys and I'm not asked again until I reboot(or logout - I haven't checked) my computer.
Since I have a bunch of keys I store the output of ssh-add -l
in a variable to improve performance(at least I guess it improves performance :) )
PS: I'm on linux and this code went to my ~/.bashrc
file - if you are on Mac OS X, then I assume you should add it to .zshrc
or .profile
EDIT:
As pointed out by @Aaron in the comments, the .zshrc
file is used from the zsh
shell - so if you're not using that(if you're not sure, then most likely, you're using bash
instead), this code should go to your .bashrc
file.
I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.
Why don't you examine System.getProperty("os.arch")
value in your code?
Hashes can not be decrypted check this out.
If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).
But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php
For Blowfish by crypt()
function -
crypt('String', '$2a$07$twentytwocharactersalt$');
password_hash
will be introduced in PHP 5.5.
$options = [
'cost' => 7,
'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.
You use Array.GetLength with the index of the dimension you wish to retrieve.
When "waiting for lock on repository", delete the repository file: .hg/wlock
(or it may be in
).hg/store/lock
When deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true).
From the official docs:
interval The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle.
You can either pass this value with javascript or using a data-interval="false"
attribute.
%c
is designed for a single character a char, so it print only one element.Passing the char array as a pointer you are passing the address of the first element of the array(that is a single char) and then will be printed :
s
printf("%c\n",*name++);
will print
i
and so on ...
Pointer is not needed for the %s because it can work directly with String of characters.
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
You can use https://github.com/keighl/KTCenterFlowLayout like this:
KTCenterFlowLayout *layout = [[KTCenterFlowLayout alloc] init];
[self.collectionView setCollectionViewLayout:layout];
For completeness: If you are already using the Spring framework, the StringUtils provide the method
org.springframework.util.StringUtils.hasLength(String str)
Returns: true if the String is not null and has length
as well as the method
org.springframework.util.StringUtils.hasText(String str)
Returns: true if the String is not null, its length is greater than 0, and it does not contain whitespace only
If you are writing MarkDown for PanDoc, you can do this:
![drawing](drawing.jpg){ width=50% }
This adds style="width: 50%;"
to the HTML <img>
tag, or [width=0.5\textwidth]
to \includegraphics
in LaTeX.
Source: http://pandoc.org/MANUAL.html#extension-link_attributes
try
if ! grep -q sysa /etc/passwd ; then
grep
returns true
if it finds the search target, and false
if it doesn't.
So NOT false
== true
.
if
evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).
Also, looking at your code as is, your use of the $( ... )
form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa")
to see what I mean. You can take that further by using the -c
(count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then
which works but is rather old school.
BUT, you could use the newest shell features (arithmetic evaluation) like
if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`
which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,%
and maybe a few others.
In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like
if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....
OR
if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....
Finally, there is an award called the Useless Use of Cat (UUOC)
. :-) Some people will jump up and down and cry gothca! I'll just say that grep
can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)
I hope this helps.
Here is the code for compling and running java source code: - Open Notepadd++ - Hit F6 - Paste this code
npp_save <-- Saves the current document
CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
javac "$(FILE_NAME)" <-- compiles your file named *.java
java "$(NAME_PART)" <-- executes the program
The Java Classpath variable has to be set for this...
Another useful site: http://www.scribd.com/doc/52238931/Notepad-Tutorial-Compile-and-Run-Java-Program
You need to give relative
or absolute
or fixed
positioning to your container (#shop
) and set its zIndex
to say 100.
You also need to give say relative
positioning to your elements with the class content
and lower zIndex
say 97.
Do the above-mentioned with your images too and set their zIndex
to 91.
And then position your button higher by setting its position to absolute
and zIndex
to 95
See the DEMO
HTML
<div id="shop">
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
</div>
CSS
#shop{
background-image: url("images/shop_bg.png");
background-repeat: repeat-x;
height:121px;
width: 984px;
margin-left: 20px;
margin-top: 13px;
position:relative;
z-index:100
}
#shop .content{
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
z-index:97
}
img{
position:relative;
z-index:91
}
.span{
width:70px;
height:40px;
border:1px solid red;
position:absolute;
z-index:95;
right:60px;
bottom:-20px;
}
Just wanted to summarize everything:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<div class="unselectable" unselectable="yes" onselectstart="return false;"/>
Just use x["error_msg"]
. If the property doesn't exist, it returns null
.
Here's a real world example with the use of non-minified versus minified assets in your layout.
Web.Config
<appSettings>
<add key="Environment" value="Dev" />
</appSettings>
Razor Template - use that var above like this:
@if (System.Configuration.ConfigurationManager.AppSettings["Environment"] == "Dev")
{
<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/theme.css" )">
}else{
<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/blue_theme.min.css" )">
}
try this (if your server is Linux):
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command);
echo $localIP;
I was able to do this using a little LINQ,
public static List<string> GetErrorListFromModelState
(ModelStateDictionary modelState)
{
var query = from state in modelState.Values
from error in state.Errors
select error.ErrorMessage;
var errorList = query.ToList();
return errorList;
}
The above method returns a list of validation errors.
Further Reading :
After struggling with the same problem, I tried two different solutions that works:
""
) with your variables.Easiest way just double quotes your variables as pointed in previous answer:
cd "$yourPathWithBlankSpace"
eval
.According to this answer Unix command to escape spaces you can strip blank space then make use of eval
, like this:
yourPathEscaped=$(printf %q "$yourPathWithBlankSpace")
eval cd $yourPathEscaped
If you have a repository that was cloned with --depth 1
then many of the commands that were listed will not work. For example, see here
% git clone --depth 1 https://github.com/repo/code
Cloning into 'code'...
cd code
remote: Counting objects: 1778, done.
remote: Compressing objects: 100% (1105/1105), done.
remote: Total 1778 (delta 87), reused 1390 (delta 58), pack-reused 0
Receiving objects: 100% (1778/1778), 5.54 MiB | 4.33 MiB/s, done.
Resolving deltas: 100% (87/87), done.
Checking connectivity... done.
Checking out files: 100% (1215/1215), done.
% cd code
% git checkout other_branch
error: pathspec 'other_branch' did not match any file(s) known to git.
% git fetch origin other_branch
remote: Counting objects: 47289, done.
remote: Compressing objects: 100% (15906/15906), done.
remote: Total 47289 (delta 30151), reused 46699 (delta 29570), pack-reused 0
Receiving objects: 100% (47289/47289), 31.03 MiB | 5.70 MiB/s, done.
Resolving deltas: 100% (30151/30151), completed with 362 local objects.
From https://github.com/repo/code
* branch other_branch-> FETCH_HEAD
% git checkout other_branch
error: pathspec 'other_branch' did not match any file(s) known to git.
%
In this case I would reclone the repository, but perhaps there are other techniques e.g. git shallow clone (clone --depth) misses remote branches
Simply, App.config is an XML
based file format that holds the Application Level Configurations.
Example:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="key" value="test" />
</appSettings>
</configuration>
You can access the configurations by using ConfigurationManager
as shown in the piece of code snippet below:
var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"
Note: ConfigurationSettings
is obsolete method to retrieve configuration information.
var value = System.Configuration.ConfigurationSettings.AppSettings["key"];
It is similar to BVB Media's answer.
grep -rnw 'blablabla' `pwd`
It works fine on my ubuntu bash.
I think your problem is that you send the broadcast before the other activity start ! so the other activity will not receive anything .
You can do it with just a few lines of pure js codes.
var date = new Date(1324339200000);
var dateToStr = date.toUTCString().split(' ');
var cleanDate = dateToStr[2] + ' ' + dateToStr[1] ;
console.log(cleanDate);
returns Dec 20. Hope it helps.
Not very clean but it works :)
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr = arr.Concat({newItem}).ToArray
Use break?
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
Since I can only edit my own answer, I'm going to make a composite answer from the other answers to my question. Thanks to all of you who answered.
Using std::copy, this still iterates in the background, but you don't have to type out the code.
int foo(int* data, int size)
{
static std::vector<int> my_data; //normally a class variable
std::copy(data, data + size, std::back_inserter(my_data));
return 0;
}
Using regular memcpy. This is probably best used for basic data types (i.e. int) but not for more complex arrays of structs or classes.
vector<int> x(size);
memcpy(&x[0], source, size*sizeof(int));
The ListAvailable option doesn't work for me. Instead this does:
if (-not (Get-Module -Name "<moduleNameHere>")) {
# module is not loaded
}
Or, to be more succinct:
if (!(Get-Module "<moduleNameHere>")) {
# module is not loaded
}
I believe there is a simpler solution.
You must use Html.Hidden
instead of Html.HiddenFor
. Look:
@Html.Hidden("CRN", ViewData["crn"]);
This will create an INPUT
tag of type="hidden"
, with id="CRN"
and name="CRN"
, and the correct value inside the value
attribute.
Hope it helps!
From 5.2.2/2 (character display semantics) :
\b
(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.
\n
(new line) Moves the active position to the initial position of the next line.
\r
(carriage return) Moves the active position to the initial position of the current line.
Here, your code produces :
<new_line>ab
\b
: back one charactersi
: overrides the b
with s
(producing asi
on the second line)\r
: back at the beginning of the current lineha
: overrides the first two characters (producing hai
on the second line)In the end, the output is :
\nhai
You can use dateutil.parser.parse
(install with python -m pip install python-dateutil
) to parse strings into datetime objects.
dateutil.parser.parse
will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime
which you supply a format string to (see Brent Washburne's answer).
from dateutil.parser import parse
a = "2012-10-09T19:00:55Z"
b = parse(a)
print(b.weekday())
# 1 (equal to a Tuesday)
#include<stdio.h>
int main()
{
int a,b,i,c,j;
printf("\n Enter the two no. in between you want to check:");
scanf("%d%d",&a,&c);
printf("%d-%d\n",a,c);
for(j=a;j<=c;j++)
{
b=0;
for(i=1;i<=c;i++)
{
if(j%i==0)
{
b++;
}
}
if(b==2)
{
printf("\nPrime number:%d\n",j);
}
else
{
printf("\n\tNot prime:%d\n",j);
}
}
}
The best and easiest way to do this is to use:
SELECT DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)
Just replace GETDATE() with whatever date you need.
Late answer, but for python>=3.6
you can use:
import dload
j = dload.json(url)
Install dload
with:
pip3 install dload
I've been having the same problem (well I hope the same). Anyways it turned out to be my version of ntwdblib.dll, which was out of date in my PHP folder.
http://dba.fyicenter.com/faq/sql_server_2/Finding_ntwdblib_dll_Version_2000_80_194_0.html
Don't manually edit the .designer files in visual studio that usually leads to headaches. Instead either specify it in the properties section of your DataGridRow which should be contained within a DataGrid element. Or if you just want VS to do it for you find the double click event within the properties page->events (little lightning bolt icon) and double click the text area where you would enter a function name for that event.
This link should help
http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx
I tried the first answer in this discussion and it wasn't working for me no matter what I did so I came up with my own solution:
Wrap the iframe with a class (.maps in this example) and ideally embedresponsively code: http://embedresponsively.com/ — Change the CSS of the iframe to pointer-events: none
and then using jQuery's click function to the parent element you can change the iframes css to pointer-events:auto
HTML
<div class='embed-container maps'>
<iframe width='600' height='450' frameborder='0' src='http://foo.com'></iframe>
</div>
CSS
.maps iframe{
pointer-events: none;
}
jQuery
$('.maps').click(function () {
$('.maps iframe').css("pointer-events", "auto");
});
$( ".maps" ).mouseleave(function() {
$('.maps iframe').css("pointer-events", "none");
});
I'm sure there's a JavaScript only way of doing this, if someone wants to add to this feel free.
The JavaScript way to reactivate the pointer-events is pretty simple. Just give an Id to the iFrame (i.e. "iframe"), then apply an onclick event to the cointainer div:
onclick="document.getElementById('iframe').style.pointerEvents= 'auto'"
<div class="maps" onclick="document.getElementById('iframe').style.pointerEvents= 'auto'">
<iframe id="iframe" src="" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
I am wondering if you are after something like Squiggle. Also something very useful is jDBI. It won't help you with the queries though.
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.
Go to Xcode
-> Project Settings
You can find the way to go to derived Data
You can also simply convert a 2D array into hash using:
1.9.3p362 :005 > a= [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
1.9.3p362 :006 > h = Hash[a]
=> {1=>2, 3=>4}
An awk
code based on RS
.
awk '1' RS=',\n' file
or:
awk 'BEGIN{RS=",\n"}1' file
This last example will be valid for any char before newline:
awk '1' RS='.\n' file
Note: dot .
matches any character except line breaks.
Explanation
awk
allows us to use different record (line) regex
separators, we just need to include the comma before the line break (or dot
for any char) in the one used for the input
, the RS
.
Note: what that 1
means?
Short answer, It's just a shortcut to avoid using the print
statement.
In awk
when a condition gets matched the default action is to print the input line, example:
$ echo "test" |awk '1'
test
That's because 1
will be always true, so this expression is equivalent to:
$ echo "test"|awk '1==1'
test
$ echo "test"|awk '{if (1==1){print}}'
test
Documentation
Check Record Splitting with Standard awk and Output Separators.
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
That 'u' is part of the external representation of the string, meaning it's a Unicode string as opposed to a byte string. It's not in the string, it's part of the type.
As an example, you can create a new Unicode string literal by using the same synax. For instance:
>>> sandwich = u"smörgås"
>>> sandwich
u'sm\xf6rg\xe5s'
This creates a new Unicode string whose value is the Swedish word for sandwich. You can see that the non-English characters are represented by their Unicode code points, ö is \xf6
and å is \xe5
. The 'u' prefix appears just like in your example to signify that this string holds Unicode text.
To get rid of those, you need to encode the Unicode string into some byte-oriented representation, such as UTF-8. You can do that with e.g.:
>>> sandwich.encode("utf-8")
'sm\xc3\xb6rg\xc3\xa5s'
Here, we get a new string without the prefix 'u', since this is a byte string. It contains the bytes representing the characters of the Unicode string, with the Swedish characters resulting in multiple bytes due to the wonders of the UTF-8 encoding.
private string FormatMultipleEmailAddresses(string emailAddresses)
{
var delimiters = new[] { ',', ';' };
var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", addresses);
}
Now you can use it like
var mailMessage = new MailMessage();
mailMessage.To.Add(FormatMultipleEmailAddresses("[email protected];[email protected],[email protected]"));
Add the below dependency to your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
If you are getting that List
from a method call that you implement, then don't return null
, return an empty List
.
If you can't change the implementation then you are stuck with the null
check. If it should't be null
, then throw an exception.
I would not go for the helper method that returns an empty list because it may be useful some times but then you would get used to call it in every loop you make possibly hiding some bugs.
PEAR: Mail worked for me sending email messages from Gmail. Also, the instructions: How to Send Email from a PHP Script Using SMTP Authentication (Using PEAR::Mail) helped greatly. Thanks, CMS!
For Android Studio:
Click on Build.gradle (module: app).
And add for
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('libs/commons-io-2.4.jar')
}
and in your directory "app", create a directory, "libs". Add the file yourfile.jar:
Finally, compile the Gradle Files:
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
$i = 1;
do {
$newTime = strtotime('+'.$i++.' days',$startTime);
echo $newTime;
} while ($newTime < $endTime);
or
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
do {
$startTime = strtotime('+1 day',$startTime);
echo $startTime;
} while ($startTime < $endTime);
Simplest of All Solutions:
Use:
filtered_df = df[(df['col1'] >= 1) & (df['col1'] <= 5)]
Another Example, To filter the dataframe for values belonging to Feb-2018, use the below code
filtered_df = df[(df['year'] == 2018) & (df['month'] == 2)]
In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)
it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.
The modern standard syntax for the same query would be
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id
or with a shorthand for a.id=b.id
(not supported by all databases):
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)
Older syntax, in both Oracle and other databases:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id
More modern syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id
Or simply:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id
It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.
This is just the same as a LEFT JOIN, but switches which table is optional.
Old Oracle syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id
Modern standard syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id
https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187
You can use grep, as the other answers state. But you don't need grep, awk, sed, perl, cut, or any external tool. You can do it with pure bash.
Try this (semicolons are there to allow you to put it all on one line):
$ while read line;
do
if [[ "${line%%:\ *}" == "potato" ]];
then
echo ${line##*:\ };
fi;
done< file.txt
## tells bash to delete the longest match of ": " in $line from the front.
$ while read line; do echo ${line##*:\ }; done< file.txt
1234
5678
5432
4567
5432
56789
or if you wanted the key rather than the value, %% tells bash to delete the longest match of ": " in $line from the end.
$ while read line; do echo ${line%%:\ *}; done< file.txt
potato
apple
potato
grape
banana
sushi
The substring to split on is ":\ " because the space character must be escaped with the backslash.
You can find more like these at the linux documentation project.
I'm not sure how stuck you are:
You must have a web server (Windows comes with one called IIS, but it may not be installed)
http://localhost/
in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS Installing your application
Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\
. Read Installing ASP.NET Applications (IIS 6.0) for more information
Accessing the web site from another machine
In theory, once you have a web server running, and the application installed, you only need the IP address
of your web server to access the application.
To find your IP address try:
Start
-> Run
-> type cmd
(hit ENTER
) -> type ipconfig
(hit ENTER
)
Once
you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.
If you put your application in a directory called NewApp
, you will need to type something like http://your_ip_address/NewApp/default.aspx
Turn off your firewall
If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.
Try adding the -f
option to show the function names :
addr2line -f -e a.out 0x4005BDC
The purpose of data-toggle in bootstrap is so you can use jQuery to find all tags of a certain type. For example, you put data-toggle="popover" in all popover tags and then you can use a JQuery selector to find all those tags and run the popover() function to initialize them. You could just as well put class="myPopover" on the tag and use the .myPopover selector to do the same thing. The documentation is confusing, because it makes it appear that something special is going on with that attribute.
This
<div class="container">
<h3>Popover Example</h3>
<a href="#" class="myPop" title="Popover1 Header" data-content="Some content inside the popover1">Toggle popover1</a>
<a href="#" class="myPop" title="Popover2 Header" data-content="Some content inside the popover2">Toggle popover2</a>
</div>
<script>
$(document).ready(function(){
$('.myPop').popover();
});
</script>
works just fine.
In Addition you also need to be sure that you have
<context:annotation-config/>
in your SPring configuration xml.
I also would recommend you to read this blog post. It helped me alot. Spring blog - Ajax Simplifications in Spring 3.0
Update:
just checked my working code where I have @RequestBody
working correctly.
I also have this bean in my config:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
May be it would be nice to see what Log4j
is saying. it usually gives more information and from my experience the @RequestBody
will fail if your request's content type is not Application/JSON
. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.
I had a situation where I needed a separate but persistent name space. I used classes. I don't otherwise. Segregated but persistent names are closures.
>>> class f2:
... def __init__(self):
... self.a = 0
... def __call__(self, arg):
... self.a += arg
... return(self.a)
...
>>> f=f2()
>>> f(2)
2
>>> f(2)
4
>>> f(4)
8
>>> f(8)
16
# **OR**
>>> f=f2() # **re-initialize**
>>> f(f(f(f(2)))) # **nested**
16
# handy in list comprehensions to accumulate values
>>> [f(i) for f in [f2()] for i in [2,2,4,8]][-1]
16
**page 1**
<form action="exapmple.php?variable_name=$value" method="POST">
<button>
<input type="hidden" name="x">
</button>
</form>`
page 2
if(isset($_POST['x'])) {
$new_value=$_GET['variable_name'];
}
You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:
vi test_script.sh
Add the following to your file:
#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>
cd <base directory for your put file>
lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT
And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq
.Then make your script executable chmod +x test_script.sh
and execute it ./test_script.sh
.
Pipes are a way of streaming data between applications. Under Linux I use this all the time to stream the output of one process into another. This is anonymous because the destination app has no idea where that input-stream comes from. It doesn't need to.
A named pipe is just a way of actively hooking onto an existing pipe and hoovering-up its data. It's for situations where the provider doesn't know what clients will be eating the data.
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
Instead of adding "ws." before every Range, as suggested above, you can add "ws.activate" before Call instead.
This will get you into the worksheet you want to work on.
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
bFound sets to true if searched string is matched with any element of array 'lines'.
I get a better tips to get non-duplicate entries in a file
awk '$0 != x ":FOO" && NR>1 {print x} {x=$0} END {print}' file_name | uniq -f1 -u
we can follow below procedure to avoid display of key-values in alphabetical order.
Javascript
$scope.data = {
"id": 2,
"project": "wewe2012",
"date": "2013-02-26",
"description": "ewew",
"eet_no": "ewew",
};
var array = [];
for(var key in $scope.data){
var test = {};
test[key]=$scope.data[key];
array.push(test);
}
$scope.data = array;
HTML
<p ng-repeat="obj in data">
<font ng-repeat="(key, value) in obj">
{{key}} : {{value}}
</font>
</p>
Try executing vmware as administrator
I was impatient and chose not to wait for answers... for reference it doesn't look that hard to do something like this (which works for my application, I don't need to worry about escaped quotes, as the stuff in quotes is limited to a few constrained forms):
final static private Pattern splitSearchPattern = Pattern.compile("[\",]");
private List<String> splitByCommasNotInQuotes(String s) {
if (s == null)
return Collections.emptyList();
List<String> list = new ArrayList<String>();
Matcher m = splitSearchPattern.matcher(s);
int pos = 0;
boolean quoteMode = false;
while (m.find())
{
String sep = m.group();
if ("\"".equals(sep))
{
quoteMode = !quoteMode;
}
else if (!quoteMode && ",".equals(sep))
{
int toPos = m.start();
list.add(s.substring(pos, toPos));
pos = m.end();
}
}
if (pos < s.length())
list.add(s.substring(pos));
return list;
}
(exercise for the reader: extend to handling escaped quotes by looking for backslashes also.)
try this function
public static Date StringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
dtReturn = simpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dtReturn;
}
"FirstLine" + "<br/>" "SecondLine"
I've seen a few answers that utilized decorators, though I felt a few were a bit verbose. Here's something I use for logging function names as well as their respective input and output values. I've adapted it here to just print the info rather than creating a log file and adapted it to apply to the OP specific example.
def debug(func=None):
def wrapper(*args, **kwargs):
try:
function_name = func.__func__.__qualname__
except:
function_name = func.__qualname__
return func(*args, **kwargs, function_name=function_name)
return wrapper
@debug
def my_function(**kwargs):
print(kwargs)
my_function()
Output:
{'function_name': 'my_function'}
Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.
View.VISIBLE The view is visible.
View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"
View.GONE The view is gone, you can't see it and it doesn't take up the "spot".
So to answer your question, you're looking for:
if (myImageView.getVisibility() == View.VISIBLE) {
// Its visible
} else {
// Either gone or invisible
}
These need to go as different commands e.g.:
NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"
The expansion $NAME
to empty string is done by the shell earlier, before running echo
, so at the time the NAME
variable is passed to the echo
command's environment, the expansion is already done (to null string).
To get the same result in one command:
NAME=sam printenv NAME
My usecase was replacing None
with some default value.
I've timed approaches to this problem that were presented here, including the one by @kxr - using str.count
.
Test code in ipython with Python 3.8.1:
def rep1(lst, replacer = 0):
''' List comprehension, new list '''
return [item if item is not None else replacer for item in lst]
def rep2(lst, replacer = 0):
''' List comprehension, in-place '''
lst[:] = [item if item is not None else replacer for item in lst]
return lst
def rep3(lst, replacer = 0):
''' enumerate() with comparison - in-place '''
for idx, item in enumerate(lst):
if item is None:
lst[idx] = replacer
return lst
def rep4(lst, replacer = 0):
''' Using str.index + Exception, in-place '''
idx = -1
# none_amount = lst.count(None)
while True:
try:
idx = lst.index(None, idx+1)
except ValueError:
break
else:
lst[idx] = replacer
return lst
def rep5(lst, replacer = 0):
''' Using str.index + str.count, in-place '''
idx = -1
for _ in range(lst.count(None)):
idx = lst.index(None, idx+1)
lst[idx] = replacer
return lst
def rep6(lst, replacer = 0):
''' Using map, return map iterator '''
return map(lambda item: item if item is not None else replacer, lst)
def rep7(lst, replacer = 0):
''' Using map, return new list '''
return list(map(lambda item: item if item is not None else replacer, lst))
lst = [5]*10**6
# lst = [None]*10**6
%timeit rep1(lst)
%timeit rep2(lst)
%timeit rep3(lst)
%timeit rep4(lst)
%timeit rep5(lst)
%timeit rep6(lst)
%timeit rep7(lst)
I get:
26.3 ms ± 163 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
29.3 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
33.8 ms ± 191 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
11.9 ms ± 37.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
11.9 ms ± 60.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
260 ns ± 1.84 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
56.5 ms ± 204 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Using the internal str.index
is in fact faster than any manual comparison.
I didn't know if the exception in test 4 would be more laborious than using str.count
, the difference seems negligible.
Note that map()
(test 6) returns an iterator and not an actual list, thus test 7.
SELECT aa.*,
bb.meal
FROM table1 aa
INNER JOIN table2 bb
ON aa.tableseat = bb.tableseat AND
aa.weddingtable = bb.weddingtable
INNER JOIN
(
SELECT a.tableSeat
FROM table1 a
INNER JOIN table2 b
ON a.tableseat = b.tableseat AND
a.weddingtable = b.weddingtable
WHERE b.meal IN ('chicken', 'steak')
GROUP by a.tableSeat
HAVING COUNT(DISTINCT b.Meal) = 2
) c ON aa.tableseat = c.tableSeat
You can get it by XMLHttpRequest.responseText
in XMLHttpRequest.onreadystatechange
when XMLHttpRequest.readyState
equals to XMLHttpRequest.DONE
.
Here's an example (not compatible with IE6/7).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
You can also use PHP's error_reporting();
// Disable it all for current call
error_reporting(0);
If you want to ignore errors from one function only, you can prepend a @
symbol.
@any_function(); // Errors are ignored
Close PHP Storm in terminal go to the project folder type
git rm -rf .idea; git commit -m "delete .idea"; git push;
Then go to project folder and delete the folder .idea
sudo rm -r .idea/
Start PhpStorm and you are done
I've added the <%%
literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <%
part of the tag which is necessary for js apps like displaying chart.js tooltips etc.
Update (Fixed broken link)
Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags
in laravel 5.4 this code Model::whereNotNull('column')
was not working you need to add get()
like this one Model::whereNotNull('column')->get();
this one works fine for me.
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
You can use a .Net environment Visual studio, Take a look at the differences with the PC version.
A lighter editor would be Visual Code
Alternatives :
Installing the Mono Project runtime . It allows you to re-compile the code and run it on a Mac, but this requires various alterations to the codebase, as the fuller .Net Framework is not available. (Also, WPF applications aren't supported here either.)
Virtual machine (VMWare Fusion perhaps)
Update your codebase to .Net Core, (before choosing this option take a look at this migration process)
.Net Core 3.1 is an open-source, free and available on Window, MacOs and Linux
As of September 14, a release candidate 1 of .Net Core 5.0 has been deployed on Window, MacOs and Linux.
[1] : Release candidate (RC) : releases providing early access to complete features. These releases are supported for production use when they have a go-live license
thisReader.GetString(int columnIndex)
If you are wanting to configure this locally on OS X 10.8 serving Angular with Apache then you might find the following in your .htaccess file helps:
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteBase /~yourusername/appname/public/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png|jpg|jpeg|gif|txt)
RewriteRule (.*) index.html [L]
</IfModule>
Options +FollowSymlinks if not set may give you a forbidden error in the logs like so:
Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden
Rewrite base is required otherwise requests will be resolved to your server root which locally by default is not your project directory unless you have specifically configured your vhosts, so you need to set the path so that the request finds your project root directory. For example on my machine I have a /Users/me/Sites directory where I keep all my projects. Like the old OS X set up.
The next two lines effectively say if the path is not a directory or a file, so you need to make sure you have no files or directories the same as your app route paths.
The next condition says if request not ending with file extensions specified so add what you need there
And the [L] last one is saying to serve the index.html file - your app for all other requests.
If you still have problems then check the apache log, it will probably give you useful hints:
/private/var/log/apache2/error_log
Try this
public static void main(String[] args)
{
String original = "ABCDEFGHIJKLMNOPQ";
String tobeChecked = "GHi";
System.out.println(containsString(original, tobeChecked, true));
System.out.println(containsString(original, tobeChecked, false));
}
public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
if (caseSensitive)
{
return original.contains(tobeChecked);
}
else
{
return original.toLowerCase().contains(tobeChecked.toLowerCase());
}
}
Non-blocking: This function won't wait while on the stack.
Asynchronous: Work may continue on behalf of the function call after that call has left the stack
I wasn't aware of a problem with setAttribute
in IE ? However you could directly set the expando property on the node itself:
hiddenInput.id = "uniqueIdentifier";
Here is an approach using str.slice(0, -n)
.
Where n is the number of characters you want to truncate.
var str = 1437203995000;_x000D_
str = str.toString();_x000D_
console.log("Original data: ",str);_x000D_
str = str.slice(0, -3);_x000D_
str = parseInt(str);_x000D_
console.log("After truncate: ",str);
_x000D_
Why not use the extension methods?
Consider the following code:
var intArray = new int[] { 0, 1, 1, 2, 3, 4 };
// Replaces the first occurance and returns the index
var index = intArray.Replace(1, 0);
// {0, 0, 1, 2, 3, 4}; index=1
var stringList = new List<string> { "a", "a", "c", "d"};
stringList.ReplaceAll("a", "b");
// {"b", "b", "c", "d"};
var intEnum = intArray.Select(x => x);
intEnum = intEnum.Replace(0, 1);
// {0, 0, 1, 2, 3, 4} => {1, 1, 1, 2, 3, 4}
The source code:
namespace System.Collections.Generic
{
public static class Extensions
{
public static int Replace<T>(this IList<T> source, T oldValue, T newValue)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var index = source.IndexOf(oldValue);
if (index != -1)
source[index] = newValue;
return index;
}
public static void ReplaceAll<T>(this IList<T> source, T oldValue, T newValue)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
int index = -1;
do
{
index = source.IndexOf(oldValue);
if (index != -1)
source[index] = newValue;
} while (index != -1);
}
public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return source.Select(x => EqualityComparer<T>.Default.Equals(x, oldValue) ? newValue : x);
}
}
}
The first two methods have been added to change the objects of reference types in place. Of course, you can use just the third method for all types.
P.S. Thanks to mike's observation, I've added the ReplaceAll method.
Update: As a commenter pointed out, any version of JavaScript that supports arrow functions will also support ({[myKey]:myValue})
, so this answer has no actual use-case (and, in fact, it might break in some bizarre corner-cases).
Don't use the below-listed method.
I can't believe this hasn't been posted yet: just use arrow functions with anonymous evaluation!
Completely non-invasive, doesn't mess with the namespace, and it takes just one line:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
demo:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
_x000D_
useful in environments that don't support the new I stand corrected; just wrap the thing in parenthesis and it works.{[myKey]: myValue}
syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08.
(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce
, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)
not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactly the answer to the question as stated, I'll show this in the original context:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
<?php
// do something here
header("Location: http://example.com/thankyou.php");
?>
This adds nothing to the above, but is written in the simple and heavily commented style that I like. It yields a table with the objects ordered in size , but without some of the detail given in the examples above:
#Find the objects
MemoryObjects = ls()
#Create an array
MemoryAssessmentTable=array(NA,dim=c(length(MemoryObjects),2))
#Name the columns
colnames(MemoryAssessmentTable)=c("object","bytes")
#Define the first column as the objects
MemoryAssessmentTable[,1]=MemoryObjects
#Define a function to determine size
MemoryAssessmentFunction=function(x){object.size(get(x))}
#Apply the function to the objects
MemoryAssessmentTable[,2]=t(t(sapply(MemoryAssessmentTable[,1],MemoryAssessmentFunction)))
#Produce a table with the largest objects first
noquote(MemoryAssessmentTable[rev(order(as.numeric(MemoryAssessmentTable[,2]))),])
Just a supplement to the first post: use a user defined union type to store the pthread_t:
union tid {
pthread_t pthread_id;
unsigned long converted_id;
};
Whenever you want to print pthread_t
, create a tid
and assign tid.pthread_id = ...
, then print tid.converted_id
.
If you've deleted your root
user by mistake you can do one thing:
mysqld_safe --skip-grant-tables &
mysql -u root -p
and press enter.use mysql;
Then execute this query:
insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
then restart the mysqld
EDIT: October 6, 2018
In case anyone else needs this answer, I tried it today using innodb_version 5.6.36-82.0 and 10.1.24-MariaDB and it works if you REMOVE THE BACKTICKS (no single quotes either, just remove them):
insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, ssl_type, ssl_cipher, x509_issuer, x509_subject, max_questions, max_updates, max_connections, max_user_connections)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
HashSet hs = new HashSet();
hs.addAll(arrayList);
arrayList.clear();
arrayList.addAll(hs);
I think your question boils down to "the difference between (Is
and =
) and also (IsNot
and <>)".
The answer in both cases is the same :
=
and <>
are implicitly defined for value types and you can explicitly define them for your types.
Is
and IsNot
are designed for comparisons between reference types to check if the two references refer to the same object.
In your example, you are comparing a string object to Nothing (Null) and since the =
/<>
operators are defined for strings, the first example works. However, it does not work when a Null is encountered because Strings are reference types and can be Null. The better way (as you guessed) is the latter version using Is
/IsNot
.
In addition to the above, you can do this (where "YourListObjectName" is the name of your table):
Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")
But I think that only works if you want to reference a list object that's on the active sheet.
I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.
Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.
Dim WB As Workbook
Set WB = ActiveWorkbook
' Create a PivotTable object and set it to be
' the pivot table in the active cell:
Dim PT As PivotTable
Set PT = ActiveCell.PivotTable
Dim LO As ListObject
Dim LOWS As Worksheet
' Loop through the worksheets and each worksheet's list objects
' to find the name of the worksheet that contains the list object
' that the pivot table uses as its source data:
Dim WS As Worksheet
For Each WS In WB.Worksheets
' Loop through the ListObjects in each workshet:
For Each LO In WS.ListObjects
' If the ListObject's name is the name of the pivot table's soure data,
' set the LOWS to be the worksheet that contains the list object:
If LO.Name = PT.SourceData Then
Set LOWS = WB.Worksheets(LO.Parent.Name)
End If
Next LO
Next WS
Debug.Print LOWS.Name
End Sub
Maybe someone knows a more direct way.
Use :after
pseudo selector. Look http://jsfiddle.net/A52T8/1/
<ul>
<li>Dogs</li>
<li>Cats</li>
<li>Lions</li>
<li>Tigers</li>
<li>Zebras</li>
<li>Giraffes</li>
<li>Bears</li>
<li>Hippopotamuses</li>
<li>Antelopes</li>
<li>Unicorns</li>
<li>Seagulls</li>
</ul>
ul li { float: left; }
ul li:after { content: "|"; padding: 0 .5em; }
EDIT:
jQuery solution:
html:
<div>
<ul id="animals">
<li>Dogs</li>
<li>Cats</li>
<li>Lions</li>
<li>Tigers</li>
<li>Zebras</li>
<li>Giraffes</li>
<li>Bears</li>
<li>Hippopotamuses</li>
<li>Antelopes</li>
<li>Unicorns</li>
<li>Seagulls</li>
<li>Monkey</li>
<li>Hedgehog</li>
<li>Chicken</li>
<li>Rabbit</li>
<li>Gorilla</li>
</ul>
</div>
css:
div { width: 300px; }
ul li { float: left; border-right: 1px solid black; padding: 0 .5em; }
ul li:last-child { border: 0; }
jQuery
var maxWidth = 300, // Your div max-width
totalWidth = 0;
$('#animals li').each(function(){
var currentWidth = $(this).outerWidth(),
nextWidth = $(this).next().outerWidth();
totalWidth += currentWidth;
if ( (totalWidth + nextWidth) > maxWidth ) {
$(this).css('border', 'none');
totalWidth = 0;
}
});
Take a look here. I also added a few more animals. http://jsfiddle.net/A52T8/10/
Here is Java 8 code. I think this code will solve your problem.Happy Coding
LocalDate start = LocalDate.now();
LocalDate end = LocalDate.of(2016, 9, 1);//JAVA 9 release date
Long duration = start.until(end, ChronoUnit.DAYS);
System.out.println(duration);
// Do Any stuff Here there after
IntStream.iterate(0, i -> i + 1)
.limit(duration)
.forEach((i) -> {});
//old way of iteration
for (int i = 0; i < duration; i++)
System.out.print("" + i);// Do Any stuff Here
You need to use quote marks.
font-family: "Comic Sans MS", cursive, sans-serif;
Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.
Please note that; the below code will create new application context instead of using the already loaded one.
private static final ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Also note that beans.xml
should be part of src/main/resources
means in war it is part of WEB_INF/classes
, where as the real application will be loaded through applicationContext.xml
mentioned at Web.xml
.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>META-INF/spring/applicationContext.xml</param-value>
</context-param>
It is difficult to mention applicationContext.xml
path in ClassPathXmlApplicationContext
constructor. ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml")
wont be able to locate the file.
So it is better to use existing applicationContext by using annotations.
@Component
public class OperatorRequestHandlerFactory {
public static ApplicationContext context;
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
context = applicationContext;
}
}
Update April 10, 2016
Flexboxes should now be used to vertically (or even horizontally) align items.
body {
height: 150px;
border: 5px solid cyan;
font-size: 50px;
display: flex;
align-items: center; /* Vertical center alignment */
justify-content: center; /* Horizontal center alignment */
}
_x000D_
Middle
_x000D_
A good guide to flexbox can be read on CSS Tricks. Thanks Ben (from comments) for pointing it out. I didn't have time to update.
A good guy named Mahendra posted a very working solution here.
The following class should make the element horizontally and vertically centered to its parent.
.absolute-center {
/* Internet Explorer 10 */
display: -ms-flexbox;
-ms-flex-pack: center;
-ms-flex-align: center;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari, Opera, and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
No you can't; datetime will be stored in default format only while creating table and then you can change the display format in you select
query the way you want using the Mysql Date Time Functions
Well this type of error comes when u are taking input a particular file or data in pandas such as :-
data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv)
Then the error is displaying like this :- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf4 in position 1: invalid continuation byte
So to avoid this type of error can be removed by adding an argument
data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv', encoding='ISO-8859-1')
You can check undefined object using below code.
ReactObject === 'undefined'
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
how do you get
"\u6f22\u5b57"
from??
in JavaScript?
These are JavaScript Unicode escape sequences e.g. \u12AB
. To convert them, you could iterate over every code unit in the string, call .toString(16)
on it, and go from there.
However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA
in the output wherever possible.
Also note that ASCII symbols such as A
, b
, and -
probably don’t need to be escaped.
I’ve written a small JavaScript library that does all this for you, called jsesc
. It has lots of options to control the output.
Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97
Your question was tagged as utf-8
. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js
(online demo).
If you really want to use String:
NSString *number = [[NSString alloc] initWithFormat:@"%d", 123];
But I would recommend using NSNumber:
NSNumber *number = [[NSNumber alloc] initWithInt:123];
Then just add it to the array.
[array addObject:number];
Don't forget to release it after that, since you created it above.
[number release];
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
I'm doing it like this at the moment:
// Requires NuGet package Microsoft.Extensions.Configuration.Json
using Microsoft.Extensions.Configuration;
using System.IO;
namespace ImagesToMssql.AppsettingsJson
{
public static class AppSettingsJson
{
public static IConfigurationRoot GetAppSettings()
{
string applicationExeDirectory = ApplicationExeDirectory();
var builder = new ConfigurationBuilder()
.SetBasePath(applicationExeDirectory)
.AddJsonFile("appsettings.json");
return builder.Build();
}
private static string ApplicationExeDirectory()
{
var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
var appRoot = Path.GetDirectoryName(location);
return appRoot;
}
}
}
And then I use this where I need to get the data from the appsettings.json file:
var appSettingsJson = AppSettingsJson.GetAppSettings();
// appSettingsJson["keyName"]
Using coalesce() converts null to 0:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;
With Python 3, the following code will format an Exception
object exactly as would be obtained using traceback.format_exc()
:
import traceback
try:
method_that_can_raise_an_exception(params)
except Exception as ex:
print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))
The advantage being that only the Exception
object is needed (thanks to the recorded __traceback__
attribute), and can therefore be more easily passed as an argument to another function for further processing.
As others have said both are valid and will do the trick. I'm not 100% convinced that they are identical though. If you have some style cascading going on then they could in theory produce different results since they are effectively overriding different values.
For example. If you set "border: none;" and then later on have two different styles that override the border width and style then one will do something and the other will not.
In the following example on both IE and firefox the first two test divs come out with no border. The second two however are different with the first div in the second block being plain and the second div in the second block having a medium width dashed border.
So though they are both valid you may need to keep an eye on your styles if they do much cascading and such like I think.
<html>
<head>
<style>
div {border: 1px solid black; margin: 1em;}
.zerotest div {border: 0;}
.nonetest div {border: none;}
div.setwidth {border-width: 3px;}
div.setstyle {border-style: dashed;}
</style>
</head>
<body>
<div class="zerotest">
<div class="setwidth">
"Border: 0" and "border-width: 3px"
</div>
<div class="setstyle">
"Border: 0" and "border-style: dashed"
</div>
</div>
<div class="nonetest">
<div class="setwidth">
"Border: none" and "border-width: 3px"
</div>
<div class="setstyle">
"Border: none" and "border-style: dashed"
</div>
</div>
</body>
</html>
To me this was permission error and this resolved it:
chown -R nginx:nginx /var/opt/remi/php73/lib/php/session
I have tested a few hours on PHP and the last test I did was that I created two files session1.php and session2.php.
session1.php:
session_start();
$_SESSION["user"] = 123;
header("Location: session2.php");
session2.php:
session_start();
print_r($_SESSION);
and it was printing an empty array.
At this point, I thought it could be a server issue and in fact, it was.
Hope this helps someone.
To get the value of cell, use the following syntax,
datagridviewName(columnFirst, rowSecond).value
But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond
approach...
This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint
function to generate the correct number of values within the range of each bin for the hist function to graph, for example:
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])
as for labels you can align x ticks with bins to get something like this:
#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])
Try this:
UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:
mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
See? No syntax error. I tested against MySQL 5.5.8.
var keys = new Array();
for(var key in obj)
{
keys[keys.length] = key;
}
var keyLength = keys.length;
to access any value from the object, you can use obj[key];
One other thing to look at that solved it for me :
In an Eclipse / Maven project, I had Java classes in src/test/java
in which I was using the this.getClass().getResource("someFile.ext");
pattern to look for resources in src/test/resources
where the resource file was in the same package location in the resources source folder as the test class was in the the test source folder. It still failed to locate them.
Right click on the src/test/resources
source folder, Build Path, then "configure inclusion / exclusion filters"; I added a new inclusion filter of **/*.ext
to make sure my files weren't getting scrubbed; my tests now can find their resource files.
You'll need different sized icons for iOS and Android, like Rockvic said. In addition, I recommend this site for generating different sized icons if anybody is interested. You don't need to download anything and it works perfectly.
Hope it helps.
There is a new feature called Interpreter in status bar (scroll down a little bit). This makes switching between python interpreters and seeing which version you’re using easier.
In case you cannot see the status bar, you can easily activate it by running the Find Action command (Ctrl+Shift+A or ?+ ?+A on mac). Then type status bar and choose View: Status Bar to see it.
If you call your created method in the lifecycle methods like componentDidMount... then you can only use the this.onToggleLoop = this.onToogleLoop.bind(this)
and the fat arrow function onToggleLoop = (event) => {...}
.
The normal approach of the declaration of a function in the constructor wont work because the lifecycle methods are called earlier.
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
def search(myDict, lookup):
a=[]
for key, value in myDict.items():
for v in value:
if lookup in v:
a.append(key)
a=list(set(a))
return a
if the research involves more keys maybe you should create a list with all the keys
Another option is to transfer stored procedures using SQL Server Integration Services (SSIS). There is a task called Transfer SQL Server Objects Task. You can use the task to transfer the following items:
It's a graphical tutorial for Transfer SQL Server Objects Task.
As .Net progresses, so does their ability to add new 32-bit configurations that trips everyone up it seems.
If you are on .Net Framework 4.7.2 do the following:
Go to Project Properties
Build
Uncheck 'prefer 32-bit'
Cheers!
To ignore a field, annotate it with @Transient
so it will not be mapped by hibernate.
but then jackson will not serialize the field when converting to JSON.
If you need mix JPA with JSON(omit by JPA but still include in Jackson) use @JsonInclude
:
@JsonInclude()
@Transient
private String token;
TIP:
You can also use JsonInclude.Include.NON_NULL and hide fields in JSON during deserialization when token == null
:
@JsonInclude(JsonInclude.Include.NON_NULL)
@Transient
private String token;
Your best bet to start is to use ?str()
. To explore some examples, let's make some data:
set.seed(3221) # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])
@Wilmer E Henao H's solution is very streamlined:
sapply(my.data, class)
y x1 x2 X3
"numeric" "integer" "logical" "factor"
Using str()
gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable):
str(my.data)
'data.frame': 5 obs. of 4 variables:
$ y : num 1.03 1.599 -0.818 0.872 -2.682
$ x1: int 1 2 3 4 5
$ x2: logi TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
@Gavin Simpson's approach is also streamlined, but provides slightly different information than class()
:
sapply(my.data, typeof)
y x1 x2 X3
"double" "integer" "logical" "integer"
For more information about class
, typeof
, and the middle child, mode
, see this excellent SO thread: A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient.
If you didn't commit it to the master branch yet, its easy:
git checkout -b oops/fluke/dang
)git add -u; git commit;
)git checkout master
)Your changes will be saved in branch oops/fluke/dang; master will be as it was.
I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.
The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.
The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.
You can have two possible scenarios:
The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self]
used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.
The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate]
you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.
So, which will/should you actually use most of the times?
Quoting Joe Groff from twitter:
Unowned is faster and allows for immutability and nonoptionality.
If you don't need weak, don't use it.
You'll find more about unowned*
inner workings here.
*
Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.
On my windows 8.1, and mysql 5.7.9 MySQL Community Server (GPL),
I had to remove the ;
after the file path.
This failed: source E:/jokoni/db/Banking/createTables.sql;
This Worked: source E:/jokoni/db/Banking/createTables.sql
(without termination, and forward slashes instead of windows' backslashes in path)
To replace with dashes, do the following:
text.replace(/[\W_-]/g,' ');
You want \s
Matches a single white space character, including space, tab, form feed, line feed.
Equivalent to
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
in Firefox and [ \f\n\r\t\v]
in IE.
str = str.replace(/\s/g, "X");
Joe Kington's excellent answer is already 4 years old,
Matplotlib has incrementally changed (in particular, the introduction
of the cycler
module) and the new major release, Matplotlib 2.0.x,
has introduced stylistic differences that are important from the point
of view of the colors used by default.
The color of individual lines (as well as the color of different plot
elements, e.g., markers in scatter plots) is controlled by the color
keyword argument,
plt.plot(x, y, color=my_color)
my_color
is either
(0.,0.5,0.5)
),"#008080"
(RGB) or "#008080A0"
),"k"
for black, possible values in "bgrcmykw"
),"teal"
) --- aka HTML color name (in the docs also X11/CSS4 color name),'xkcd:'
(e.g., 'xkcd:barbie pink'
),'T10'
categorical palette, (e.g., 'tab:blue'
, 'tab:olive'
),"C3"
, i.e., the letter "C"
followed by a single digit in "0-9"
).By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).
The color cycle is a property of the axes
object, and in older
releases was simply a sequence of valid color names (by default a
string of one character color names, "bgrcmyk"
) and you could set it
as in
my_ax.set_color_cycle(['kbkykrkg'])
(as noted in a comment this API has been deprecated, more on this later).
In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
, the Vega category10 palette.
(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)
The following code shows that the color cycle notion has been deprecated
In [1]: from matplotlib import rc_params
In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))
Out[2]:
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
Now the relevant property is the 'axes.prop_cycle'
In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Previously, the color_cycle
was a generic sequence of valid color
denominations, now by default it is a cycler
object containing a
label ('color'
) and a sequence of valid color denominations. The
step forward with respect to the previous interface is that it is
possible to cycle not only on the color of lines but also on other
line attributes, e.g.,
In [5]: from cycler import cycler
In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}
As you have seen, the cycler
objects are composable and when you iterate on a composed cycler
what you get, at each iteration, is a dictionary of keyword arguments for plt.plot
.
You can use the new defaults on a per axes
object ratio,
my_ax.set_prop_cycle(new_prop_cycle)
or you can install temporarily the new default
plt.rc('axes', prop_cycle=new_prop_cycle)
or change altogether the default editing your .matplotlibrc
file.
Last possibility, use a context manager
with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
...
to have the new cycler
used in a group of different plots, reverting to defaults at the end of the context.
The doc string of the cycler()
function is useful, but the (not so much) gory details about the cycler
module and the cycler()
function, as well as examples, can be found in the fine docs.