<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>
To get or set the Password in a PasswordBox, use the Password property. Such as
string password = PasswordBox.Password;
This doesn't support Databinding as far as I know, so you'd have to set the value in the codebehind, and update it accordingly.
The easiest way to achieve this is to create only 1 table with both Table A and B fields NOT NULL. This way it is impossible to have one without the other.
If anyone can't seem to get there .bash_profile
file to take any new Paths AND you have other commands in that file (like alias commands) then try moving the PATH statements to the top of the file.
That is the only thing that worked for me. The reason it worked was because I had some typos in my alias commands and apparently this file throws an error and exits if it runs into a problem. So that is why my PATH statements weren't being run. Moving it to the top just let it run first.
x # initial numpy array
I = np.argsort(x) or I = x.argsort()
y = np.sort(x) or y = x.sort()
z # reverse sorted array
z = x[I[::-1]]
z = -np.sort(-x)
z = np.flip(y)
z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)
z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)
Testing on a 100×10×10 array 1000 times.
Method | Time (ms)
-------------+----------
y[::-1] | 0.126659 # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y) | 0.121711
x[I[::-1]] | 4.611778
x.sort() | 0.024961
x.argsort() | 0.041830
np.flip(x) | 0.002026
This is mainly due to reindexing rather than argsort
.
# Timing code
import time
import numpy as np
def timeit(fun, xs):
t = time.time()
for i in range(len(xs)): # inline and map gave much worse results for x[-I], 5*t
fun(xs[i])
t = time.time() - t
print(np.round(t,6))
I, N = 1000, (100, 10, 10)
xs = np.random.rand(I,*N)
timeit(lambda x: np.sort(x)[::-1], xs)
timeit(lambda x: -np.sort(-x), xs)
timeit(lambda x: np.flip(x.sort()), xs)
timeit(lambda x: x[x.argsort()[::-1]], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)
For me this problem was entirely related to a broken install of Oracle ODP tools for VS. I uninstalled and reinstalled and everything was working again.
I needed to print ALL lines after the pattern ( ok Ed, REGEX ), so I settled on this one:
sed -n '/pattern/,$p' # prints all lines after ( and including ) the pattern
But since I wanted to print all the lines AFTER ( and exclude the pattern )
sed -n '/pattern/,$p' | tail -n+2 # all lines after first occurrence of pattern
I suppose in your case you can add a head -1
at the end
sed -n '/pattern/,$p' | tail -n+2 | head -1 # prints line after pattern
Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.
I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.
This from the accepted answer helped me solve this problem:
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern
The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema
I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.
import nltk
nltk.download('punkt')
Open the Python prompt and run the above statements.
The sent_tokenize function uses an instance of PunktSentenceTokenizer from the nltk.tokenize.punkt module. This instance has already been trained and works well for many European languages. So it knows what punctuation and characters mark the end of a sentence and the beginning of a new sentence.
You have the right general strategy for doing this using base graphics, but as was pointed out you're essentially telling R to pick a random color from a set of 10 for each line. Given that, it's not surprising that you will occasionally get two lines with the same color. Here's an example using base graphics:
plot(0,0,xlim = c(-10,10),ylim = c(-10,10),type = "n")
cl <- rainbow(5)
for (i in 1:5){
lines(-10:10,runif(21,-10,10),col = cl[i],type = 'b')
}
Note the use of type = "n"
to suppress all plotting in the original call to set up the window, and the indexing of cl
inside the for loop.
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use document.referrer
.
To access the user-agent, use navigator.userAgent
.
As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.
You must change the cmake C/CXX default FLAGS .
According to CMAKE_BUILD_TYPE={DEBUG/MINSIZEREL/RELWITHDEBINFO/RELEASE}
put in the main CMakeLists.txt
one of :
For C
set(CMAKE_C_FLAGS_DEBUG "put your flags")
set(CMAKE_C_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_C_FLAGS_RELEASE "put your flags")
For C++
set(CMAKE_CXX_FLAGS_DEBUG "put your flags")
set(CMAKE_CXX_FLAGS_MINSIZEREL "put your flags")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "put your flags")
set(CMAKE_CXX_FLAGS_RELEASE "put your flags")
This will override the values defined in CMakeCache.txt
void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
{
TextBox txt = (TextBox)sender;
var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
string str = txt.Text + e.Text.ToString();
int cntPrc = 0;
if (str.Contains('.'))
{
string[] tokens = str.Split('.');
if (tokens.Count() > 0)
{
string result = tokens[1];
char[] prc = result.ToCharArray();
cntPrc = prc.Count();
}
}
if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
The sane way to do this is to use zip()
and a List Comprehension / Generator Expression:
filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == '[email protected]')
new_emails, new_other_list = zip(*filtered)
Also, if your'e not using array.array()
or numpy.array()
, then most likely you are using []
or list()
, which give you Lists, not Arrays. Not the same thing.
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
In the first case you are just invoking the run()
method of the r1
and r2
objects.
In the second case you're actually creating 2 new Threads!
start()
will call run()
at some point!
Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99
.
Powershell + Curl + Zimbra SOAP API
${my_xml} = @"
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soapenv:Body>
<GetFolderRequest xmlns=\"urn:zimbraMail\">
<folder>
<path>Folder Name</path>
</folder>
</GetFolderRequest>
</soapenv:Body>
</soapenv:Envelope>
"@
${my_curl} = "c:\curl.exe"
${cookie} = "c:\cookie.txt"
${zimbra_soap_url} = "https://zimbra:7071/service/admin/soap"
${curl_getfolder_args} = "-b", "${cookie}",
"--header", "Content-Type: text/xml;charset=UTF-8",
"--silent",
"--data-raw", "${my_xml}",
"--url", "${zimbra_soap_url}"
[xml]${my_response} = & ${my_curl} ${curl_getfolder_args}
${my_response}.Envelope.Body.GetFolderResponse.folder.id
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
Or use Series.tolist
or Series.any
:
>>> s = pd.Series(list('abc'))
>>> s
0 a
1 b
2 c
dtype: object
>>> 'a' in s.tolist()
True
>>> (s=='a').any()
True
Series.tolist
makes a list about of a Series
, and the other one i am just getting a boolean Series
from a regular Series
, then checking if there are any True
s in the boolean Series
.
Set the min SDK version in your project's AndroidManifest.xml file and in the toolbar search for "Sync Projects with Gradle Files" icon. It works for me.
Also look for your project's build.gradle file and update the min sdk version.
You will need to repeat your call to strtol
inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...);
instead of while, you don't get a the same sort of repeat things twice behaviour.
You should also format your code so that it's possible to see where the code is inside a loop and not.
Personally, I would go with one of the JavaScript / jQuery solutions. Not only does this keep your HTML semantic (i.e., an image is shown as an img element with it's usual src image defined in the markup), but if you use a JS / jQuery solution then you will also be able to use the JS / jQuery to preload your hover image.
Preloading the hover image will mean there is likely to be no download delay when the user hovers over the original image, resulting in your site behaving much more professionally.
It does mean you have a dependency on JS, but the tiny minority that don't have JS enabled are probably not going to be too fussed - and everyone else will get a better experience... and your code will be good, too!
AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post
out into the longer $.ajax
call and adds the async
option).
var it_works = false;
$.ajax({
type: 'POST',
async: false,
url: "some_file.php",
data: "",
success: function() {it_works = true;}
});
alert(it_works);
Hope this helps!
Can't be iterating directly in dictionary. So you can through converting into tuple.
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first_names': first_names,
'last_name': last_names,
}
tup_field=tuple(fields.items())
for names in fields.items():
field,possible_values = names
tup_possible_values=tuple(possible_values)
for pvalue in tup_possible_values:
print (field + "is" + pvalue)
grep -A20 -B20 pattern file.txt
Search pattern and show 20 lines after and before pattern
You should be able to set the className property of the element. You could do a += to append it.
As stated in the solution, if the List
is empty then an IndexOutOfBoundsException
is thrown. A better solution is to use the Optional
type:
public class ListUtils {
public static <T> Optional<T> last(List<T> list) {
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
}
}
As you'd expect, the last element of the list is returned as an Optional
:
var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;
It also deals gracefully with empty lists as well:
var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;
I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
I was a great fan of submit()
but not anymore.
In the web page that I test, I enter username and password and click Login. When I invoked usernametextbox.submit()
, password textbox is cleared (becomes empty) and login keeps failing.
After breaking my head for sometime, when I replaced usernametextbox.submit()
with loginbutton.click()
, it worked like a magic.
If you want to by pass the time and resources it takes to count(*) your 3million row tables. Try this per SQL SERVER Central by Kendal Van Dyke.
Row Counts Using sysindexes If you're using SQL 2000 you'll need to use sysindexes like so:
-- Shows all user tables and row counts for the current database
-- Remove OBJECTPROPERTY function call to include system objects
SELECT o.NAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME
If you're using SQL 2005 or 2008 querying sysindexes will still work but Microsoft advises that sysindexes may be removed in a future version of SQL Server so as a good practice you should use the DMVs instead, like so:
-- Shows all user tables and row counts for the current database
-- Remove is_ms_shipped = 0 check to include system objects
-- i.index_id < 2 indicates clustered index (1) or hash table (0)
SELECT o.name,
ddps.row_count
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID
INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID
AND i.index_id = ddps.index_id
WHERE i.index_id < 2 AND o.is_ms_shipped = 0 ORDER BY o.NAME
I was stumped by this too because I was including the .Java extension ... then I noticed the capital J.
This will also cause the "annotation processing" error:
javac myclass.Java
Instead, it should be:
javac myclass.java
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:justifyContent="space_around"> <!-- or "space_between", "space_evenly" -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp" />
</com.google.android.flexbox.FlexboxLayout>
Make sure to import implementation 'com.google.android:flexbox:2.0.0'
Flexbox
is far more powerful; it is a good complement to ConstraintLayout
. This is a great resource to learn more.
position: relative;
z-index: 2;
cursor: pointer
worked for me.
As this isn't mentioned in the accepted answer.
You can make use of Simple Requests.
In order to perform a 'Simple Requests' the request needs to meet several conditions. E.g. only allowing POST
, GET
and HEAD
method, as well as only allowing some given Headers (you can find all conditions here).
If your client code does not explicit set affected Headers (e.g. "Accept") with a fix value in the request it might occur that some clients do set these Headers automatically with some "non-standard" values causing the server to not accept it as Simple Request - which will give you a CORS error.
This worked for me: conda install --force-reinstall pyqt qt
Based on this
The easiest option to do that is running a VM with a OSX copy.
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Adding @WebAppConfiguration
(org.springframework.test.context.web.WebAppConfiguration
) annotation to your DemoApplicationTests class will work.
You can just use the equality operator: ==
. Objects are checked by reference by default, so you don't even need to use the ===
operator.
try this, just make sure you're using the correct variable reference in the place of car1
:
var i, car, l = cars.length;
for (i = 0; i < l; i++)
{
if ((car = cars[i]) == car1)
{
break;
}
else car = null;
}
Edit to add:
An array extension was mentioned, so here's the code for it:
Array.prototype.contains = Array.prototype.contains || function(obj)
{
var i, l = this.length;
for (i = 0; i < l; i++)
{
if (this[i] == obj) return true;
}
return false;
};
Note that I'm caching the length value, as the Array's length
property is actually an accessor, which is marginally slower than an internal variable.
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:
alias df-gb='df -BG'
So if you type:
df-gb
into a terminal, you'll get your intended output of the disk usage in GB.
EDIT: or even use just df -h
to get it in a standard, human readable format.
Old question, but this works for my need (Swift 5.x):
print(type(of: myObjectName))
It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex
, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.
From this link
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;
namespace ClientUtil
{
public class DataTableUtil
{
public static string DataTableToXmlString(DataTable dtData)
{
if (dtData == null || dtData.Columns.Count == 0)
return (string) null;
DataColumn[] primaryKey = dtData.PrimaryKey;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(“<TABLE>”);
stringBuilder.Append(“<TR>”);
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
if (DataTableUtil.IsPrimaryKey(dataColumn.ColumnName, primaryKey))
stringBuilder.Append(“<TH IsPK=’true’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
else
stringBuilder.Append(“<TH IsPK=’false’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
}
stringBuilder.Append(“</TR>”);
int num1 = 0;
foreach (DataRow dataRow in (InternalDataCollectionBase) dtData.Rows)
{
stringBuilder.Append(“<TR>”);
int num2 = 0;
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
string str = Convert.IsDBNull(dataRow[dataColumn.ColumnName]) ? (string) null : Convert.ToString(dataRow[dataColumn.ColumnName]).Replace(“<“, “<”).Replace(“>”, “>”).Replace(“\””, “"”).Replace(“‘”, “'”).Replace(“&”, “&”);
if (!string.IsNullOrEmpty(str))
stringBuilder.Append(“<TD>”).Append(str).Append(“</TD>”);
else
stringBuilder.Append(“<TD>”).Append(“</TD>”);
++num2;
}
stringBuilder.Append(“</TR>”);
++num1;
}
stringBuilder.Append(“</TABLE>”);
return ((object) stringBuilder).ToString();
}
protected static bool IsPrimaryKey(string ColumnName, DataColumn[] PKs)
{
if (PKs == null || string.IsNullOrEmpty(ColumnName))
return false;
foreach (DataColumn dataColumn in PKs)
{
if (dataColumn.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
return true;
}
return false;
}
public static DataTable XmlStringToDataTable(string XmlData)
{
DataTable dataTable = (DataTable) null;
IList<DataColumn> list = (IList<DataColumn>) new List<DataColumn>();
if (string.IsNullOrEmpty(XmlData))
return (DataTable) null;
XmlDocument xmlDocument1 = new XmlDocument();
xmlDocument1.PreserveWhitespace = true;
XmlDocument xmlDocument2 = xmlDocument1;
xmlDocument2.LoadXml(XmlData);
XmlNode xmlNode1 = xmlDocument2.SelectSingleNode(“/TABLE”);
if (xmlNode1 != null)
{
dataTable = new DataTable();
int num = 0;
foreach (XmlNode xmlNode2 in xmlNode1.SelectNodes(“TR”))
{
if (num == 0)
{
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TH”))
{
bool result = false;
string str = xmlNode3.Attributes[“IsPK”].Value;
if (!string.IsNullOrEmpty(str))
{
if (!bool.TryParse(str, out result))
result = false;
}
else
result = false;
Type type = Type.GetType(xmlNode3.Attributes[“ColType”].Value);
DataColumn column = new DataColumn(xmlNode3.InnerText, type);
if (result)
list.Add(column);
if (!dataTable.Columns.Contains(column.ColumnName))
dataTable.Columns.Add(column);
}
if (list.Count > 0)
{
DataColumn[] dataColumnArray = new DataColumn[list.Count];
for (int index = 0; index < list.Count; ++index)
dataColumnArray[index] = list[index];
dataTable.PrimaryKey = dataColumnArray;
}
}
else
{
DataRow row = dataTable.NewRow();
int index = 0;
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TD”))
{
Type dataType = dataTable.Columns[index].DataType;
string s = xmlNode3.InnerText;
if (!string.IsNullOrEmpty(s))
{
try
{
s = s.Replace(“<”, “<“);
s = s.Replace(“>”, “>”);
s = s.Replace(“"”, “\””);
s = s.Replace(“'”, “‘”);
s = s.Replace(“&”, “&”);
row[index] = Convert.ChangeType((object) s, dataType);
}
catch
{
if (dataType == typeof (DateTime))
row[index] = (object) DateTime.ParseExact(s, “yyyyMMdd”, (IFormatProvider) CultureInfo.InvariantCulture);
}
}
else
row[index] = Convert.DBNull;
++index;
}
dataTable.Rows.Add(row);
}
++num;
}
}
return dataTable;
}
}
}
To complement the rest of the answers, the MIME type for JSON linked data (JSON-LD) according to W3C is:
application/ld+json
Type name: application
Subtype name: ld+json
Additionally, from the same source:
File extension(s):
.jsonld
Each of the three conditions is evaluated independently[1]:
id != 1 // false
id != 2 // true
id != 3 // true
Then it evaluates false || true || true
, which is true (a || b
is true if either a
or b
is true). I think you want
id != 1 && id != 2 && id != 3
which is only true if the ID is not 1 AND it's not 2 AND it's not 3.
[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
I was fed up with the slow build of android on my local machine. The way I solved this was spinning up a high-end machine on AWS and rsyncing the code from my local to the machine and compiling it over there.
I saw an immediate increase in the performance and my local system was saved from CPU hog. Check out this tool I created to help the developers speed up their terminal https://stormyapp.com
Add the below code in app.gradle this will solve all the library dependency errors
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
exclude("META-INF/*.kotlin_module")
exclude 'META-INF/library_release.kotlin_module'
pickFirst 'lib/armeabi-v7a/libavdevice.so'
pickFirst 'lib/armeabi/libavdevice.so'
pickFirst 'lib/armeabi/libswresample.so'
pickFirst 'lib/armeabi-v7a/libswresample.so'
pickFirst 'lib/armeabi/libswscale.so'
pickFirst 'lib/armeabi/libavcodec.so'
pickFirst 'lib/armeabi-v7a/libavutil.so'
pickFirst 'lib/armeabi/libavutil.so'
pickFirst 'lib/armeabi-v7a/libavformat.so'
pickFirst 'lib/armeabi/libavfilter.so'
pickFirst 'lib/armeabi/libavformat.so'
pickFirst 'lib/armeabi-v7a/libavcodec.so'
pickFirst 'lib/armeabi-v7a/libswscale.so'
pickFirst 'lib/armeabi/libpostproc.so'
pickFirst 'lib/armeabi-v7a/libpostproc.so'
pickFirst 'lib/armeabi-v7a/libavfilter.so'
}
You said that budgetpost is alphanumeric. That means it is looking for comparisons against strings. You should try enclosing your parameters in single quotes (and you are missing the final THEN in the Case expression).
UPDATE tab1
SET budgpost_gr1= CASE
WHEN (budgpost in ('1001','1012','50055')) THEN 'BP_GR_A'
WHEN (budgpost in ('5','10','98','0')) THEN 'BP_GR_B'
WHEN (budgpost in ('11','876','7976','67465')) THEN 'What?'
ELSE 'Missing'
END
file = open('Failed.py', 'w')
file.write('whatever')
file.close()
Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:
with open('Failed.py', 'w') as file:
file.write('whatever')
You can use Django's to-python queryset serializer.
Just put the following code in your view:
from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )
And then in the template:
{% for instance in data %}
{% for field, value in instance.fields.items %}
{{ field }}: {{ value }}
{% endfor %}
{% endfor %}
Its great advantage is the fact that it handles relation fields.
For the subset of fields try:
data = serializers.serialize('python', SomeModel.objects.all(), fields=('name','size'))
* "For example, say you'd declared a List at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway)." *
This is correct, but this solution may not be generalizable. While setting a List object reference to null -will- make memory available for garbage collection, this is only true for a List object of primitive types. If the List object instead contains reference types, setting the List object = null will not dereference -any- of the reference types contained -in- the list. In this case, setting the List object = null will orphan the contained reference types whose objects will not be available for garbage collection unless the garbage collection algorithm is smart enough to determine that the objects have been orphaned.
For PDO You may do this
$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')";
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";
$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);
BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;
Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:
:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
The second command adds a belongs_to :user
relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id
column and it will use a model named User
to instantiate the specific user.
The second command also adds an index on the new user_id
column.
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
For those who are still frustrated, if you are using the experimental ART runtime, try switching back to dalvik (in developer options on device)
If the strings are the same length, then I would go for '%x' % ()
of the built-in xor (^
).
Examples -
>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'
If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]
The control searches for a view in the following order:
As you do not have xxx.cshtml
in those locations, it returns a "view not found" error.
Solution: You can use the complete path of your view:
Like
PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
First be sure that your working copy is not modified. Then:
git diff --binary HEAD commit_sha_you_want_to_revert_to | git apply
and then just commit. Don't forget to document what's the reason for revert.
It turns out that lstlisting
is able to format code nicely, but requires a lot of tweaking.
Wikibooks has a good example for the parameters you can tweak.
The easiest way to stream video via IP Camera !
I just edit your example. You must replace your IP and add /video
on your link. And go ahead with your project
import cv2
cap = cv2.VideoCapture('http://192.168.18.37:8090/video')
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
In my case I refactored code and put the creation of the Dialog in a separate class. I only handed over the clicked View because a View contains a context object already. This led to the same error message although all ran on the MainThread.
I then switched to handing over the Activity as well and used its context in the dialog creation -> Everything works now.
fun showDialogToDeletePhoto(baseActivity: BaseActivity, clickedParent: View, deletePhotoClickedListener: DeletePhotoClickedListener) {
val dialog = AlertDialog.Builder(baseActivity) // <-- here
.setTitle(baseActivity.getString(R.string.alert_delete_picture_dialog_title))
...
}
I , can't format the code snippet properly, sorry :(
I could do it using
from subprocess import Popen
process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))
it killed the cmd.exe
and the program that i gave the command for.
(On Windows)
In my case it was pretty simple because my database tables are InnoDB with foreign keys with Cascade on Delete.
So in this case if your photos table contains a foreign key reference for the user than all you have to do is to delete the hotel and the cleanup will be done by the Data Base, the data base will delete all the photos records from the data base.
From SQLServer 2012 more elegant alter role:
use mydb
go
ALTER ROLE db_datareader
ADD MEMBER MYUSER
go
ALTER ROLE db_datawriter
ADD MEMBER MYUSER
go
Yes, quite straight forward:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
If you want to change whether it highlights the best fitting possibility, use:
Ctrl + Alt + Space
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.
I think ADTC's solution is better, but mine's also works.
Here is the other solution I found
select p.name
from person p
where instr(p.name,chr(8211)) > 0; --contains the character chr(8211)
--at least 1 time
Thank you.
Another way this could be accomplished is by using the Start-Transcript
and Stop-Transcript
commands, respectively before and after command execution. This would capture the entire session including commands.
For this particular case Out-File
is probably your best bet though.
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
I encountered this problem when loading CSS for a React layout module that I installed with npm. You have to import two .css files to get this module running, so I initially imported them like this:
@import "../../../../node_modules/react-grid-layout/css/styles.css";
but found out that the file extension has to be dropped, so this worked:
@import "../../../../node_modules/react-grid-layout/css/styles";
These two commands do basically the thing asked for:
diff --brief --recursive --no-dereference --new-file --no-ignore-file-name-case /dir1 /dir2 > dirdiff_1.txt
rsync --recursive --delete --links --checksum --verbose --dry-run /dir1/ /dir2/ > dirdiff_2.txt
The choice between them depends on the location of dir1 and dir2:
When the directories reside on two seperate drives, diff outperforms rsync. But when the two directories compared are on the same drive, rsync is faster. It's because diff puts an almost equal load on both directories in parallel, maximizing load on the two drives.
rsync calculates checksums in large chunks before actually comparing them. That groups the i/o operations in large chunks and leads to a more efficient processing when things take place on a single drive.
For me the problem come from the name of my branch : "#name-of-my-branch", without "#" it's work fine!
Have you tried before and after rather than >= and <=? Also, is this a date or a timestamp?
var filteredFiles = Directory
.GetFiles(path, "*.*")
.Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
.ToList();
Edit 2014-07-23
You can do this in .NET 4.5 for a faster enumeration:
var filteredFiles = Directory
.EnumerateFiles(path) //<--- .NET 4.5
.Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
.ToList();
Random number generators are not actually random, they like most software is completely predictable. What rand does is create a different pseudo-random number each time it is called One which appears to be random. In order to use it properly you need to give it a different starting point.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
/* initialize random seed: */
srand ( time(NULL) );
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
return 0;
}
Assuming you want to float the elements, you would also have to float the label
elements too.
Something like this would work:
label {
/* Other styling... */
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
clear: both;_x000D_
float:left;_x000D_
margin-right:15px;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
float: left;_x000D_
}_x000D_
input[type=button] {_x000D_
float:none;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" id="Student" />_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" id="Matric_no" />_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" id="Email" />_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" id="Username" />_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" id="Password" type="password" />_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Alternatively, a more common approach would be to wrap the input
/label
elements in groups:
<div class="form-group">
<label for="Student">Name:</label>
<input name="Student" id="Student" />
</div>
#form {_x000D_
background-color: #FFF;_x000D_
height: 600px;_x000D_
width: 600px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
margin-top: 0px;_x000D_
border-top-left-radius: 10px;_x000D_
border-top-right-radius: 10px;_x000D_
padding: 0px;_x000D_
text-align:center;_x000D_
}_x000D_
label {_x000D_
font-family: Georgia, "Times New Roman", Times, serif;_x000D_
font-size: 18px;_x000D_
color: #333;_x000D_
height: 20px;_x000D_
width: 200px;_x000D_
margin-top: 10px;_x000D_
margin-left: 10px;_x000D_
text-align: right;_x000D_
margin-right:15px;_x000D_
float:left;_x000D_
}_x000D_
input {_x000D_
height: 20px;_x000D_
width: 300px;_x000D_
border: 1px solid #000;_x000D_
margin-top: 10px;_x000D_
}
_x000D_
<div id="form">_x000D_
<form action="" method="post" name="registration" class="register">_x000D_
<fieldset>_x000D_
<div class="form-group">_x000D_
<label for="Student">Name:</label>_x000D_
<input name="Student" id="Student" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Matric_no">Matric number:</label>_x000D_
<input name="Matric_no" id="Matric_no" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Email">Email:</label>_x000D_
<input name="Email" id="Email" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Username">Username:</label>_x000D_
<input name="Username" id="Username" />_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label for="Password">Password:</label>_x000D_
<input name="Password" id="Password" type="password" />_x000D_
</div>_x000D_
<input name="regbutton" type="button" class="button" value="Register" />_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>
_x000D_
Note that the for
attribute should correspond to the id
of a labelable element, not its name
. This will allow users to click the label
to give focus to the corresponding form element.
There is also possibility to use WebDriverWait with ExpectedConditions (to make sure that Frame will be available).
With string as parameter
(new WebDriverWait(driver, 5)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frame-name"));
With locator as a parameter
(new WebDriverWait(driver, 5)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frame-id")));
More info can be found here
If someone still needs it (like I do).
The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html
We need to make the current session user a member of the role:
create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;
produces:
Role ROLE created.
Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"
Grant succeeded.
Role SET succeeded.
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
If you do have a Main method but still get this error, make sure that the file containing the Main method has "Build action" set to "Compile" and "Copy to ouput directory" set to "Do not copy".
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class GetJsonFromUrl {
String url = null;
public GetJsonFromUrl(String url) {
this.url = url;
}
public String GetJsonData() {
try {
URL Url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
line = sb.toString();
connection.disconnect();
is.close();
sb.delete(0, sb.length());
return line;
} catch (Exception e) {
return null;
}
}
}
and this class use for post data
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by user on 11/2/16.
*/
public class sendDataToServer {
public String postdata(String requestURL,HashMap<String,String> postDataParams){
try {
String response = "";
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
Log.d("test", response);
return response;
}catch (Exception e){
return e.toString();
}
}
public String postjson(String url,String json){
try {
URL obj = new URL(url);
HttpURLConnection con= (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = ""+json;
// Send post request
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}catch(Exception e){
return e.toString();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
/* public String postdata(String url) {
}*/
}
Can be used as a shorthand in equality check.
So this code
if(ob != null && this.getClass() == ob.getClass) {
}
can be written as
if(ob instanceOf ClassA) {
}
(fiddle: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Html:
<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>
Js:
document.getElementById('btnOpen').onclick = function(){
openFile(function(txt){
document.getElementById('tbMain').value = txt;
});
}
function openFile(callBack){
var element = document.createElement('input');
element.setAttribute('type', "file");
element.setAttribute('id', "btnOpenFile");
element.onchange = function(){
readText(this,callBack);
document.body.removeChild(this);
}
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
function readText(filePath,callBack) {
var reader;
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
callBack(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
but it's not working in IE. recommend using :nth-child(2n+1) :nth-child(2n+2)
li {_x000D_
color: black;_x000D_
}_x000D_
li:nth-child(odd) {_x000D_
color: #777;_x000D_
}_x000D_
li:nth-child(even) {_x000D_
color: blue;_x000D_
}
_x000D_
<ul>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
</ul>
_x000D_
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
@wdavo is correct. The same is also true for functions.
If you override a base function, like Update, then in your subclass you need:
new void Update()
{
//do stufff
}
Without the new at the start of the function decleration you will get the warning flag.
OS X tends to prefix the system account names with "_"; you don't say what version of OS X you're using, but at least in 10.8 and 10.9 the _postgres user exists in a default install. Note that you won't be able to su
to this account (except as root), since it doesn't have a password. sudo -u _postgres
, on the other hand, should work fine.
Not beautiful, but a solution nonetheless:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
If Existing Project Solution is planned to move on TSF in VS Code:
open Terminal and run following commands:
Initialize git in that folder (root Directory)
git init
Add Git
git add .
Link your TSf/Git to that Project - {url} replace with your git address
git remote add origin {url}
Commit those Changes:
git commit -m "initial commit"
Push - I pushed code as version1 you can use any name for your branch
git push origin HEAD:Version1
If you're open to using jQuery, it has some nice facilities for creating detached DOM elements from strings of HTML. These can then be queried through the usual means, E.g.:
var html = "<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>";
var anchors = $('<div/>').append(html).find('a').get();
Edit - just saw @Florian's answer which is correct. This is basically exactly what he said, but with jQuery.
Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :
var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...
...
d3.select("#the_SVG_ID").remove();
You do not have to use final
, but the final
is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final
needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public
).
Here's why:
final
, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.public
, the compiler will also inline this value into any other compile unit. That means other classes using this field.What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar
, you'll get:
I am using version 1.0
Now, you improve Foo
and change the version to "1.1".
After recompiling Foo
, you run Bar
and get this wrong output:
I am using version 1.0
This happens, because VERSION
is declared final
, so the actual value of it was already in-lined in Bar
during the first compile run. As a consequence, to let the example of a public static final ...
field propagate properly after actually changing what was declared final
(you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final
you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
I prefer to use <limits>
to check for an int
until it is passed.
#include <iostream> #include <limits> //std::numeric_limits using std::cout, std::endl, std::cin; int main() { int num; while(!(cin >> num)){ //check the Input format for integer the right way cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cout << "Invalid input. Reenter the number: "; }; cout << "output= " << num << endl; return 0; }
You can use app.run(debug=True)
for the Werkzeug Debugger edit as mentioned below, and I should have known.
Be wary of "slurping" files. That's when you read the entire file into memory at once.
The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.
Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.
I like to use:
IO.foreach("testfile") {|x| print "GOT ", x }
or
File.foreach('testfile') {|x| print "GOT", x }
File inherits from IO, and foreach
is in IO, so you can use either.
I have some benchmarks showing the impact of trying to read big files via read
vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".
Simple and 100% working trick
(Make sure you install cmake)
My Anaconda python ver : 3.6.8 (64 bit) | OS :Windows 10
python -m pip install https://files.pythonhosted.org/packages/0e/ce/f8a3cff33ac03a8219768f0694c5d703c8e037e6aba2e865f9bae22ed63c/dlib-19.8.1-cp36-cp36m-win_amd64.whl#sha256=794994fa2c54e7776659fddb148363a5556468a6d5d46be8dad311722d54bfcf
Yes, you can do this. You can also even process the state and return the object.
function mapStateToProps(state){
let completed = someFunction (state);
return {
completed : completed,
}
}
This would be useful if you want to shift the logic related to state from render function to outside of it.
You can check if the Connected property is set to $true and display a friendly message:
$t = New-Object Net.Sockets.TcpClient "10.45.23.109", 443
if($t.Connected)
{
"Port 443 is operational"
}
else
{
"..."
}
On Mac the default key combination for showing the quick documentation is: CTRL + F1
The cursor has to be on the method when using this.
In your strings.xml file you can use any Unicode sign you want.
For example, the Unicode number for percent sign is 0025:
<string name="percent_sign">%</string>
You can see a comprehensive list of Unicode signs here
In case anyone else comes across this problem, this was giving me issues due to the AJAX request and a normal form request being sent. I solved it with the following line:
<form onsubmit="submitfunc(); return false;">
The key there is the return false, which causes the form not to send. You could also just return false from inside of submitfunc(), but I find explicitly writing it to be clearer.
Another table that is useful is:
SELECT * FROM user_objects WHERE object_type='TRIGGER';
You can also use this to query views, indexes etc etc
I have been in the same situation, my complete solution has been posted here
Basically I load a template in the directive in this way
var tpl = '' +
<div ng-if="maxLength"
ng-include="\'length.tpl.html\'">
</div>' +
'<div ng-if="required"
ng-include="\'required.tpl.html\'">
</div>';
then according to the value of maxLength
and required
I can dynamically load one of the 2 templates, only one of them at a time is shown if necessary.
I heope it helps.
The characters will get send just like that to the underlying output device (in your case probably a terminal emulator).
It is up to the terminal's implementation then how those characters get actually displayed. For example, a bell (\a
) could trigger a beep sound on some terminals, a flash of the screen on others, or it will be completely ignored. It all depends on how the terminal is configured.
What I would do is do this:
<button type="submit" style="background-color:rgba(255,255,255,0.0); border:none;" id="resultButton" onclick="showResults();"><img src="images/search.png" /></button>
I used background-color:rgba(255,255,255,0.0); So that the original background color of a button goes away. The same with the border:none; it will take the original border away.
Below mentioned code works perfectly fine for taking length of any characters entered in textbox.
$("#Texboxid").val().length;
To make a commit that looks like it was done in the past you have to set both GIT_AUTHOR_DATE
and GIT_COMMITTER_DATE
:
GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git commit -m '...'
where date -d'...'
can be exact date like 2019-01-01 12:00:00
or relative like 5 months ago 24 days ago
.
To see both dates in git log use:
git log --pretty=fuller
This also works for merge commits:
GIT_AUTHOR_DATE=$(date -d'...') GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" git merge <branchname> --no-ff
This error usually happens when your database is accessed by one application already, and you're trying to access it with another application.
->where($qb->expr()->in('foo.bar', ':data'))
->setParameter('participants', $data);
Also works with:
->andWhere($qb->expr()->in('foo.bar', ':users'))
->setParameter('data', $data);
The answer
git clean -d -f
was underrated (-d to remove directories). Thanks!
Use this -
create table dummy_table_name as select * from source_table_name;
This will create the new table with existing data available on source_table_name
.
Are you going to want to do a setInterval()
?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success()
callback:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Or use .ajax().complete()
if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
Have you tried:
ifconfig 10:35978f0 down
As the physical interface is 10
and the virtual aspect is after the colon :
.
See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/
On Fedora:
Some composer bins are not in the .composer directory So you need to locate them using:
locate composer | grep vendor/bin
Then echo the the part into the .bashrc
echo 'export PATH="$PATH:$HOME/{you_composer_vendor_path}"' >> ~/.bashrc
Mine was "/.config/composer/vendor/bin"
Cheers!
PHP by itself has no SMS module or functions and doesn't allow you to send SMS.
SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.
Usually people in telecom business use Asterisk to handle calls and sms programming.
In my case it also turned into a multi-hour debugging session. Trying to set up a more verbose logging turned out to be completely futile because the problem was that my application did not even start. Here's my context.xml
:
<?xml version='1.0' encoding='utf-8'?>
<Context path="/rc2" docBase="rc2" antiResourceLocking="false" >
<JarScanner>
<JarScanFilter
tldScan="spring-webmvc*.jar, spring-security-taglibs*.jar, jakarta.servlet.jsp.jstl*.jar"
tldSkip="*.jar"
<!-- my-own-app*.jar on the following line was missing! -->
pluggabilityScan="${tomcat.util.scan.StandardJarScanFilter.jarsToScan}, my-own-app*.jar"
pluggabilitySkip="*.jar"/>
</JarScanner>
</Context>
The problem was that to speed up the application startup, I started skipping scanning of many JARs, unfortunately including my own application.
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.This is the most restrictive and safest way I've found, as explained here for hypothetical ~/my/web/root/
directory for your web content:
~/my
, ~/my/web
, ~/my/web/root
):
chmod go-rwx DIR
(nobody other than owner can access content)chmod go+x DIR
(to allow "users" including _www to "enter" the dir)sudo chgrp -R _www ~/my/web/root
(all web content is now group _www)chmod -R go-rwx ~/my/web/root
(nobody other than owner can access web content)chmod -R g+rx ~/my/web/root
(all web content is now readable/executable/enterable by _www)All other solutions leave files open to other local users (who are part of the "staff" group as well as obviously being in the "o"/others group). These users may then freely browse and access DB configurations, source code, or other sensitive details in your web config files and scripts if such are part of your content. If this is not an issue for you, then by all means go with one of the simpler solutions.
I use the following template in my projects:
angular.module("AppName.moduleName", [])
/**
* @ngdoc controller
* @name AppName.moduleName:ControllerNameController
* @description Describe what the controller is responsible for.
**/
.controller("ControllerNameController", function (dependencies) {
/* type */ $scope.modelName = null;
/* type */ $scope.modelName.modelProperty1 = null;
/* type */ $scope.modelName.modelPropertyX = null;
/* type */ var privateVariable1 = null;
/* type */ var privateVariableX = null;
(function init() {
// load data, init scope, etc.
})();
$scope.modelName.publicFunction1 = function () /* -> type */ {
// ...
};
$scope.modelName.publicFunctionX = function () /* -> type */ {
// ...
};
function privateFunction1() /* -> type */ {
// ...
}
function privateFunctionX() /* -> type */ {
// ...
}
});
The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.
Example:
java.sql.Connection conn = <connect procedure>;
conn.close();
try {
conn.getMetaData();
} catch (Exception e) {
System.out.println("Connection is closed");
}
In Eclipse using Subversive:
Right click your project > Team > Merge
In the merge window, select the revisions you want to revert as normally but also enable checkbox "Reversed merge".
Merge as normally.
The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.
You don't want to include cpp
files. You want to include header files.
The header file should just have the class definition. The corresponding cpp
file, which you will compile separately, will have the function definition.
fun.hpp:
#include <iostream>
class classA {
friend void funct();
public:
classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
int propa;
int propb;
void outfun(){
std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
}
};
fun.cpp:
#include "fun.hpp"
using namespace std;
void funct(){
cout<<"enter funct"<<endl;
classA tmp(1,2);
tmp.outfun();
cout<<"exit funct"<<endl;
}
mainfile.cpp:
#include <iostream>
#include "fun.hpp"
using namespace std;
int main(int nargin,char* varargin[]) {
cout<<"call funct"<<endl;
funct();
cout<<"exit main"<<endl;
return 0;
}
Note that it is generally recommended to avoid using namespace std
in header files.
I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.
GET /items
200: ["a", "b", null]
GET /items/0
200: "a"
GET /items/1
200: "b"
GET /items/2
204:
GET /items/3
404: Not Found
A new fork of the sexy-combo project is now out which looks promising: http://code.google.com/p/ufd/
If you wish the delete to be automatic, you need to change your schema so that the foreign key constraint is ON DELETE CASCADE
.
For more information, see the MSDN page on Cascading Referential Integrity Constraints.
ETA (after clarification from the poster): If you can't update the schema, you have to manually DELETE the affected child records first.
Even though this one does not address the specific problem of the OP, it might be a solution for other people finding this question.
In some circumstances, Xcode will not recognise (won't even see) a connected device that was previously recognised, even though there were no changes in Mac OS/iOS/Xcode versions. This seems to happen if you connect the device while the Mac and/or the device are locked when you connect them. The device will ask if you want to trust the computer even though you already did so, but the device will still not be visible in Xcode.
Restarting Xcode or the device do not seem to have any effect. One solution is to reboot the Mac. Another much quicker solution is to restart usbmuxd
:
sudo pkill usbmuxd
(it will be restarted again automatically)Your device should now be visible again in Xcode!
Hope that helps a few people. Apparently it does!
A new list is created but the items in it are references to the orginal items (just like in the original list). Changes to the list itself are independent, but to the items will find the change in both lists.
If you have a fixed width element and know the width of your background image, you can simply set the background-position to : the element's width - the image's width - the gap you want on the right.
For example : with a 100px-wide element and a 300px-wide image, to get a gap of 10px on the right, you set it to 100-300-10=-210px :
#myElement {
background:url(my_image.jpg) no-repeat -210px top;
width:100px;
}
And you get the rightmost 80 pixels of your image on the left of your element, and a gap of 20px on the right.
I know it can sound stupid but sometimes it saves the time... I use that much in a vertical manner (gap at bottom) for navigation links with text below image.
Not sure it applies to your case though.
get_or_create()
returns a tuple:
customer.source, created = Source.objects.get_or_create(name="Website")
created
? has a boolean value, is created or not.
customer.source
? has an object of get_or_create()
method.
You can also send characters that you want to be trimed
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func trim(characterSet:CharacterSet) -> String {
return self.trimmingCharacters(in: characterSet)
}
}
validationMessage = validationMessage.trim(characterSet: CharacterSet(charactersIn: ","))
Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.
<textarea name="post" id="post" onclick="if(this.value == 'Write Something here..............') this.value='';" onblur="if(this.value == '') this.value='Write Something here..............';" >Write Something here..............</textarea>
Two easy ways:
Using hive conf
hive> set USER_NAME='FOO';
hive> select * from foobar where NAME = '${hiveconf:USER_NAME}';
Using hive vars
On your CLI set vars and then use them in hive
set hivevar:USER_NAME='FOO';
hive> select * from foobar where NAME = '${USER_NAME}';
hive> select * from foobar where NAME = '${hivevar:USER_NAME}';
Documentation: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+VariableSubstitution
Your configure file contains CRLF line endings (windows style) instead of simple LF line endings (unix style). Did you transfer it using FTP mode ASCII from Windows?
You can use
dos2unix configure
to fix this, or open it in vi and use :%s/^M//g;
to substitute them all (use CTRL+V, CTRL+M to get the ^M)
Personally I'd go with AJAX.
If you cannot switch to @Ajax...
helpers, I suggest you to add a couple of properties in your model
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
Change your view to a strongly typed Model via
@using MyModel
Before returning the View, in case of successfull creation do something like
MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);
then in your view, add this
@{
if (model.TriggerOnLoad) {
<text>
<script type="text/javascript">
alert('@Model.TriggerOnLoadMessage');
</script>
</text>
}
}
Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:
$(document).ready(function () {
alert('@Model.TriggerOnLoadMessage');
});
Please remember to reset the Model properties upon successfully alert emission.
Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:
@Html.EditorFor (m => m.TriggerOnLoadMessage)
But in case you want to build up such a thing, maybe it's better to define your own C# class:
class ClientMessageNotification {
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
}
and add a ClientMessageNotification
property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification
class and you're done. Nice, clean, and reusable.
This is use mostly for assigning variable, and it uses binomial conditioning eg.
var time = Date().getHours(); // or something
var clockTime = time > 12 ? 'PM' : 'AM' ;
There is no ElseIf, for the sake of development don't use chaining, you can use switch
which is much faster if you have multiple conditioning in .js
The first answer will not pass through all the points. This graph will exactly pass through all the points and will be a perfect curve with the points as [{x:,y:}] n such points.
var points = [{x:1,y:1},{x:2,y:3},{x:3,y:4},{x:4,y:2},{x:5,y:6}] //took 5 example points
ctx.moveTo((points[0].x), points[0].y);
for(var i = 0; i < points.length-1; i ++)
{
var x_mid = (points[i].x + points[i+1].x) / 2;
var y_mid = (points[i].y + points[i+1].y) / 2;
var cp_x1 = (x_mid + points[i].x) / 2;
var cp_x2 = (x_mid + points[i+1].x) / 2;
ctx.quadraticCurveTo(cp_x1,points[i].y ,x_mid, y_mid);
ctx.quadraticCurveTo(cp_x2,points[i+1].y ,points[i+1].x,points[i+1].y);
}
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
def normalize(x):
try:
x = x/np.linalg.norm(x,ord=1)
return x
except :
raise
data = pd.DataFrame.apply(data,normalize)
From the document of pandas,DataFrame structure can apply an operation (function) to itself .
DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)
Applies function along input axis of DataFrame. Objects passed to functions are Series objects having index either the DataFrame’s index (axis=0) or the columns (axis=1). Return type depends on whether passed function aggregates, or the reduce argument if the DataFrame is empty.
You can apply a custom function to operate the DataFrame .
If under Windows and user Git for Windows and the manager
for managing the credentials (aka Git-Credential-Manager-for-Windows
Link) the problem is that there is no easy way to switch amongst users when pushing to GitHub over https
using OAuth
tokens.
The reason is that the token is stored as:
git:https://github.com
Personal Access Token
OAuth_Token
Variations of the URL in Internet Address
don't work, for example:
git:https://[email protected]
git:https://github.com/username
The solution: namespaces. This is found in the details for the configuration of the Git-Credential-Manager-for-Windows
:
Quoting from it:
namespace
Sets the namespace for stored credentials.
By default the GCM uses the 'git' namespace for all stored credentials, setting this configuration value allows for control of the namespace used globally, or per host.
git config --global credential.namespace name
Now, store your credential in the Windows Credential Manager as:
git.username:https://github.com
Personal Access Token
OAuth_Token
Notice that we have changed: git
-> git.username
(where you change username
to your actual username or for the sake of it, to whatever you may want as unique identifier)
Now, inside the repository where you want to use the specific entry, execute:
git config credential.namespace git.username
(Again ... replace username
with your desired value)
Your .git/config
will now contain:
[credential]
namespace = git.username
Et voilá! The right credential will be pulled from the Windows Credential Store.
This, of course, doesn't change which user/e-mail is pushing. For that you have to configure the usual user.name
and user.email
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
You're also not going to get the output you're hoping for as long as you append to listoflists only inside the if-clause.
Try something like this instead:
import copy
listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((copy.copy(list), copy.copy(list[0])))
print(listoflists)
Dependency Injection in an ASP.NET project can be accomplished with a few lines of code. I suppose there is some advantage to using a container when you have an app that uses multiple front ends and needs unit tests.
I also faced a similar issue. Resolved the problem by going through the step step tutorial from the below link.
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/jersey-hello-world-example/
apache-tomcat-7.0.56-windows-x64\apache -tomcat-7.0.56\webapps\JerseyJSONExample\WEB-INF\lib
"11/23/2014 12:06 AM 130,458 jersey-client-1.9.jar
11/23/2014 12:06 AM 458,739 jersey-core-1.9.jar
11/23/2014 12:06 AM 147,952 jersey-json-1.9.jar
11/23/2014 12:06 AM 713,089 jersey-server-1.9.jar" 4 File(s) 1,450,238 bytes
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/
Both the links gave a good picture on how things work and save a lot of time.
Also be sure to check whether you have desktop client installed. I double checked everything, my permission, SSH, but turns out my repo listed in the client was overriding the one I was inputting via terminal.
Nothing above worked for me. I had to edit the file ".npmrc" which will be under user home directory (ex: c:\users\abcuser) :
http_proxy=null
registry=https://registry.npmjs.org/
strict-ssl=true
proxy=null
The pyplot functions you are calling, axhline()
and axvline()
draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin
or ymin
use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.
Instead, use plt.plot((x1, x2), (y1, y2), 'k-')
to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot
.
In HTML:
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />
In PHP:
if (isset($_POST["btnSubmit"])){
// "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
// "Delete" clicked
}
I recommend you use:
var returnedData = JSON.parse(data);
to convert the JSON string (if it is just text) to a JavaScript object.
if (function_exists('header_remove')) {
header_remove('X-Powered-By'); // PHP 5.3+
} else {
@ini_set('expose_php', 'off');
}
Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):
When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.
Note: the answer was edited on Jan 2016 to reflect most recent changes
I think refilling the same adapter with different data would be more or most better technique. Put this method in your Adapter class with right argument (the data list you want to display as names in my case) Call this where u update the data of list with updated list (names in my case)
public void refill(ArrayList<BeanDatabase> names) {
list.clear();
list.addAll(names);
list.notifyDataSetChanged();
}
If you change the adapter or set the adapter again and again on when the list updates, then force close error would surely cause problems at some point. (Error:List data been updated but adapter doesn't notify the List View)
You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.
perhaps I am late
you can use git remote remove origin
it will do the job.
/**
* Assigns the specified char value to each element of the specified array
* of chars.
*
* @param a the array to be filled
* @param val the value to be stored in all elements of the array
*/
public static void fill(char[] a, char val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}
That's the way Arrays.fill does it.
(I suppose you could drop into JNI and use memset
.)
Give a Format String value of C2 for the value's properties as shown in figure below.
Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.
http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx
But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").
The solution suggested
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.
A more sensible solution is to include this in your web.config:
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
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
}
}
This is a variance of need to reset body to original content. It doesn't deal with a form but I feel it might be of some use. If the original content was a ton of html, it is very difficult to string out the html and store it to a variable. Javascript does not take kindly to the line breaks that VS 2015/whatever allows. So I store original ton of html in default modal like this on page load:
var stylesString = $('#DefaultModal .modal-body').html();
Which allows me to to reuse this content when original default button for modal is pressed (there are other buttons that show other content in same modal).
$("#btnStyles").click(function () {
//pass the data in the modal body adding html elements
$('#DefaultModal .modal-body').html(stylesString);
$('#DefaultModal').modal('show');
})
If I put an alert for the styleString variable it would have an endless string of all the html with no breaks but does it for me and keeps it out of VS editor.
Here is how it looks in Visual Studio inside default modal. Saved in the string variable whether automatic (.html) or by hand in VS, it would be one big line:
<div class="modal-body" id="modalbody">
<div class="whatdays"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">All Styles</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/ballroom.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Ballroom</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/blues.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Blues</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/contra.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Contra</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/countrywestern.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Country</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/english-country.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">English Country</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/israeli.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Israeli</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/lindyhop.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Lindy Hop/Swing</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/miscvariety.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Misch/Variety</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/neo-square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Neo-Square</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/polka.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Polka</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/salsa.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Salsa</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/scottish.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Scottish</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/square.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Square</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/tango.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Tango</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/waltz.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Waltz</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/wcswing.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">WCS</span></div>
<div class="whatdays" style="background-image: url('../../Responsive/zyedeco-gator.jpg');background-size: 100% 100%;"><span style="background-color:black;color:white;padding:4px 4px 4px 4px;border:2px solid yellow;">Zydeco/Cajun</span></div>
RewriteCond %{HTTP:X-Forwarded-Proto} =https
String.prototype.replaceAll = function(character,replaceChar){
var word = this.valueOf();
while(word.indexOf(character) != -1)
word = word.replace(character,replaceChar);
return word;
}
Maybe these two examples illustrate you the difference between a deadlock and a livelock:
Java-Example for a deadlock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DeadlockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
}
public static void doB() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
}
}
Sample output:
Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2
Java-Example for a livelock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LivelockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(LivelockSample::doA, "Thread A");
Thread threadB = new Thread(LivelockSample::doB, "Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
public static void doB() {
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
}
Sample output:
Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...
Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.
A look at the API and it says you have to sort the array first
So:
Arrays.sort(array);
Arrays.binarySearch(array, value);
If you don't want to sort the array:
public int find(double[] array, double value) {
for(int i=0; i<array.length; i++)
if(array[i] == value)
return i;
}
I found another way to implement this (this is a functional component):
const Image = ({icon}) => {
const Img = require(`./path_to_your_file/${icon}.svg`).ReactComponent;
return <Img />
}
Hope it helps!
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
I've experienced the same problem and now I just found my solution to this issue.
#!/usr/bin/python
import sys
import os
os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))
This is the code[1] for my case. When I tried this script I received error message like :
import: command not found
I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.
I finally tried to type the shebang my self.
#!/usr/bin/python
and removed the copied one.
And my problem solved!!!
I copied the code from the internet[1].
And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.
I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)
Journeyer
PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.
[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy
Declare where display: flex;
was given Element.
align-items: center;
If you want to see python version then you should use py -V
instead of python -V
C:\Users\ghasan>py -V
Python 3.7.1
If you want to go to python's running environment then you should use py
instead of python
C:\Users\ghasan>py
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Here you can run the python program as:
print('Hello Python')
Hello Python
You can use LinkedHashMap to main insertion order in Map
The important points about Java LinkedHashMap class are:
A LinkedHashMap contains values based on the key 3.It may have one null key and multiple null values. 4.It is same as HashMap instead maintains insertion order
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link
Combining Günter Zöchbauer's answer with good-old vanilla-JS, here is a directive with two lines of logic that supports (123) 456-7890 format.
Reactive Forms: Plunk
import { Directive, Output, EventEmitter } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: '[formControlName][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class PhoneMaskDirective {
@Output() rawChange:EventEmitter<string> = new EventEmitter<string>();
constructor(public model: NgControl) {}
onInputChange(value) {
var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
var y = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
this.model.valueAccessor.writeValue(y);
this.rawChange.emit(rawValue);
}
}
Template-driven Forms: Plunk
import { Directive } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: '[ngModel][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class PhoneMaskDirective {
constructor(public model: NgControl) {}
onInputChange(value) {
var x = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
this.model.valueAccessor.writeValue(value);
}
}
Here is the JSONP I wrote to share with everyone:
the page to send req
http://c64.tw/r20/eqDiv/fr64.html
please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt
or embedded the code in your page:
function callbackForJsonp(resp) {
var elemDivResp = $("#idForDivResp");
elemDivResp.empty();
try {
elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
elemDivResp.append(" = " + resp.ans + "<br/>");
elemDivResp.append(" = " + resp.ans2 + "<br/>");
} catch (e) {
alert("callbackForJsonp=" + e);
}
}
$(document).ready(function() {
var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";
$(document.body).prepend("post to " + testUrl + "<br/><br/>");
$("#idForBtnToGo").click(function() {
$.ajax({
url : testUrl,
type : "POST",
data : {
f1 : $("#idForF1").val(),
f2 : $("#idForF2").val(),
op : "add"
},
dataType : "jsonp",
crossDomain : true,
//jsonpCallback : "callbackForJsonp",
success : callbackForJsonp,
//success : function(resp) {
//console.log("Yes, you success");
//callbackForJsonp(resp);
//},
error : function(XMLHttpRequest, status, err) {
console.log(XMLHttpRequest.status + "\n" + err);
//alert(XMLHttpRequest.status + "\n" + err);
}
});
});
});
You should use the EndXXX of your async method to return the value. EndXXX should wait until there is a result using the IAsyncResult's WaitHandle and than return with the value.
The second argument of date
is a UNIX timestamp, not a database timestamp string.
You need to convert your database timestamp with strtotime.
<?= date("c", strtotime($post[3])) ?>
Call c_str()
to get a const char *
(LPCSTR
) from a std::string
.
It's all in the name:
LPSTR
- (long) pointer to string - char *
LPCSTR
- (long) pointer to constant string - const char *
LPWSTR
- (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR
- (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR
- (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR
- (long) pointer to constant TCHAR string - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
It's empty by default. You'll find a bunch of settings in /etc/apache2/apache2.conf
.
In there it does this:
# Include all the user configurations:
Include httpd.conf
After keep on running into this issue and keep on coming back to this question I thought I'd share what my problem was.
Everything that @Xeberdee is correct so follow that and see if that solves the issue, if not this was my issue:
In my apps.py this is what I had:
class AlgoExplainedConfig(AppConfig):
name = 'algo_explained'
verbose_name = "Explain_Algo"
....
And all I did was I added the project name in front of my app name like this:
class AlgoExplainedConfig(AppConfig):
name = '**algorithms_explained**.algo_explained'
verbose_name = "Explain_Algo"
and that solved my problem and I was able to run the makemigrations and migrate command after that! good luck
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
You might want to check out this old thread.
If you can omit AM/PM portion and using SQL Server 2008, you should go with the approach suggested here
To get the rid from nenoseconds in time(SQL Server 2008), do as below :
SELECT CONVERT(TIME(0),GETDATE()) AS HourMinuteSecond
I hope it helps!!
I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing
import org.springframework.transaction.annotation.Transactional;
unknowingly i have imported
import javax.transaction.Transactional;
Afer changing it everything worked fine.
So thought of sharing,If somebody does same mistake .
This happens because you use the savedValue
in the onCreate()
method. The savedValue
is updated in onRestoreInstanceState()
method, but onRestoreInstanceState()
is called after the onCreate()
method. You can either:
savedValue
in onCreate()
method, orsavedValue
in onRestoreInstanceState()
method.But I suggest you to use the first approach, making the code like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int display_mode = getResources().getConfiguration().orientation;
if (display_mode == 1) {
setContentView(R.layout.main_grid);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
mGrid.setVisibility(0x00000000);
// mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
} else {
setContentView(R.layout.main_grid_land);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
Log.d("Mode", "land");
// mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
if (savedInstanceState != null) {
savedUser = savedInstanceState.getString("TEXT");
} else {
savedUser = ""
}
Log.d("savedUser", savedUser);
if (savedUser.equals("admin")) { //value 0
adapter.setApps(appManager.getApplications());
} else if (savedUser.equals("prof")) { //value 1
adapter.setApps(appManager.getTeacherApplications());
} else {// default value
appManager = new ApplicationManager(this, getPackageManager());
appManager.loadApplications(true);
bindApplications();
}
}
It was suggested to use numpy's bincount, however it works only for 1d arrays with non-negative integers. Also, the resulting array might be confusing (it contains the occurrences of the integers from min to max of the original list, and sets to 0 the missing integers).
A better way to do it with numpy is to use the unique function with the attribute return_counts
set to True. It returns a tuple with an array of the unique values and an array of the occurrences of each unique value.
# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True) # array([0, 1, 2, 3]), array([2, 3, 1, 2]
and then we can pair them as
dict(zip(a_uniq, counts)) # {0: 2, 1: 3, 2: 1, 3: 2}
It also works with other data types and "2d lists", e.g.
>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}
merge
is used to bring two (or more) branches together.
a little example:
# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"
# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"
# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"
so now there are three separate branches (namely A B and C) with different heads
to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:
# create an octopus merge
$ git merge B C
your history will then look something like this:
…-o-o-x-------A
|\ /|
| B---/ |
\ /
C---/
if you want to merge across repository/computer borders, have a look at git pull
command, e.g. from the pc with branch A (this example will create two new commits):
# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C
The classes LocalDate
and LocalDateTime
do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId
instance.
LocalDate
LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();
LocalDateTime
LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();
Privileges assigned through GRANT option do not need FLUSH PRIVILEGES to take effect - MySQL server will notice these changes and reload the grant tables immediately.
If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE, your changes have no effect on privilege checking until you either restart the server or tell it to reload the tables. If you change the grant tables directly but forget to reload them, your changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!
To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.
If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.
I have used flavorDimensions for my application in build.gradle (Module: app)
flavorDimensions "tier"
productFlavors {
production {
flavorDimensions "tier"
//manifestPlaceholders = [appName: APP_NAME]
//signingConfig signingConfigs.config
}
staging {
flavorDimensions "tier"
//manifestPlaceholders = [appName: APP_NAME_STAGING]
//applicationIdSuffix ".staging"
//versionNameSuffix "-staging"
//signingConfig signingConfigs.config
}
}
// Specifies two flavor dimensions.
flavorDimensions "tier", "minApi"
productFlavors {
free {
// Assigns this product flavor to the "tier" flavor dimension. Specifying
// this property is optional if you are using only one dimension.
dimension "tier"
...
}
paid {
dimension "tier"
...
}
minApi23 {
dimension "minApi"
...
}
minApi18 {
dimension "minApi"
...
}
}
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Using array .map function that executes a function for every value in an array seems cleanest to me.
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.
try:
#do something
except
print 'error/exception'
def printError(e):
print e
If you change "except" above to "except:", the error will go away.
Good luck.