NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
The name will be something like "Australia/Sydney", or "Europe/Lisbon".
Since it sounds like you might only care about the continent, that might be all you need.
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
You put it as =(B0+4)/($A$0)
You can also go across WorkSheets with Sheet1!$a$0
If your .htaccess file is ok and the problem persist try to make the AllowOverride directive enabled in your httpd.conf. If the AllowOverride directive is set to None in your Apache httpd.config file, then .htaccess files are completely ignored. Example of enabled AllowOverride directive in httpd.config:
<Directory />
Options FollowSymLinks
**AllowOverride All**
</Directory>
Therefor restart your server.
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
A block like this could be useful to you.
DECLARE
table_exist INT;
BEGIN
SELECT Count(*)
INTO table_exist
FROM dba_tables
WHERE owner = 'SCHEMA_NAME'
AND table_name = 'EMPLOYEE_TABLE';
IF table_exist = 1 THEN
EXECUTE IMMEDIATE 'drop table EMPLOYEE_TABLE';
END IF;
END;
package com.test;
import java.util.Arrays;
public class Person implements Comparable {
private int age;
private Person(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Object o) {
Person other = (Person)o;
if (this == other)
return 0;
if (this.age < other.age) return 1;
else if (this.age == other.age) return 0;
else return -1;
}
public static void main(String[] args) {
Person[] arr = new Person[4];
arr[0] = new Person(50);
arr[1] = new Person(20);
arr[2] = new Person(10);
arr[3] = new Person(90);
Arrays.sort(arr);
for (int i=0; i < arr.length; i++ ) {
System.out.println(arr[i].age);
}
}
}
Here is one way of doing it.
function tar.create() {
local folder="${1}"
local tar="$(basename "${folder}")".tar.gz
cd "${folder}" && tar -zcvf "../${tar}" .; cd - &> /dev/null
}
Example:
tar.create /path/to/folder
You are welcome.
git rm --cached remove_file
git add .gitignore
git commit -m "Excluding"
how i solve it in Eclipse
.
character as a wildcard to match any single character.Example regex: a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
[]
to match any characters in a set.\w
to match any single alphanumeric character: 0-9
, a-z
, A-Z
, and _
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
Example regex: a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
Example regex: a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.
Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).
How about:
echo "hello" >> <filename>
Using the >>
operator will append data at the end of the file, while using the >
will overwrite the contents of the file if already existing.
You could also use printf
in the same way:
printf "hello" >> <filename>
Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last >
all data in the file will be destroyed. You can change this behavior by setting the noclobber
variable in your .bashrc
:
set -o noclobber
Now when you try to do echo "hello" > file.txt
you will get a warning saying cannot overwrite existing file
.
To force writing to the file you must now use the special syntax:
echo "hello" >| <filename>
You should also know that by default echo
adds a trailing new-line character which can be suppressed by using the -n
flag:
echo -n "hello" >> <filename>
References
All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover()
is the better choice:
$(window).hover(function(event) {
if (event.fromElement) {
console.log("inactive");
} else {
console.log("active");
}
});
This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.
ItemDecoration
Static headers can easily be added with an ItemDecoration
and without any further changes.
// add the decoration. done.
HeaderDecoration headerDecoration = new HeaderDecoration(/* init */);
recyclerView.addItemDecoration(headerDecoration);
The decoration is also reusable since there is no need to modify the adapter or the RecyclerView
at all.
The sample code provided below will require a view to add to the top which can just be inflated like everything else. It can look like this:
If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.
If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)
You can find the full source code here on GitHub including a Builder
to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.
Please be sure to set a correct layout_height
for your view. e.g. match_parent
might not work properly.
public class HeaderDecoration extends RecyclerView.ItemDecoration {
private final View mView;
private final boolean mHorizontal;
private final float mParallax;
private final float mShadowSize;
private final int mColumns;
private final Paint mShadowPaint;
public HeaderDecoration(View view, boolean scrollsHorizontally, float parallax, float shadowSize, int columns) {
mView = view;
mHorizontal = scrollsHorizontally;
mParallax = parallax;
mShadowSize = shadowSize;
mColumns = columns;
if (mShadowSize > 0) {
mShadowPaint = new Paint();
mShadowPaint.setShader(mHorizontal ?
new LinearGradient(mShadowSize, 0, 0, 0,
new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
new float[]{0f, .5f, 1f},
Shader.TileMode.CLAMP) :
new LinearGradient(0, mShadowSize, 0, 0,
new int[]{Color.argb(55, 0, 0, 0), Color.argb(55, 0, 0, 0), Color.argb(3, 0, 0, 0)},
new float[]{0f, .5f, 1f},
Shader.TileMode.CLAMP));
} else {
mShadowPaint = null;
}
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
// layout basically just gets drawn on the reserved space on top of the first view
mView.layout(parent.getLeft(), 0, parent.getRight(), mView.getMeasuredHeight());
for (int i = 0; i < parent.getChildCount(); i++) {
View view = parent.getChildAt(i);
if (parent.getChildAdapterPosition(view) == 0) {
c.save();
if (mHorizontal) {
c.clipRect(parent.getLeft(), parent.getTop(), view.getLeft(), parent.getBottom());
final int width = mView.getMeasuredWidth();
final float left = (view.getLeft() - width) * mParallax;
c.translate(left, 0);
mView.draw(c);
if (mShadowSize > 0) {
c.translate(view.getLeft() - left - mShadowSize, 0);
c.drawRect(parent.getLeft(), parent.getTop(), mShadowSize, parent.getBottom(), mShadowPaint);
}
} else {
c.clipRect(parent.getLeft(), parent.getTop(), parent.getRight(), view.getTop());
final int height = mView.getMeasuredHeight();
final float top = (view.getTop() - height) * mParallax;
c.translate(0, top);
mView.draw(c);
if (mShadowSize > 0) {
c.translate(0, view.getTop() - top - mShadowSize);
c.drawRect(parent.getLeft(), parent.getTop(), parent.getRight(), mShadowSize, mShadowPaint);
}
}
c.restore();
break;
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) < mColumns) {
if (mHorizontal) {
if (mView.getMeasuredWidth() <= 0) {
mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
}
outRect.set(mView.getMeasuredWidth(), 0, 0, 0);
} else {
if (mView.getMeasuredHeight() <= 0) {
mView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
}
outRect.set(0, mView.getMeasuredHeight(), 0, 0);
}
} else {
outRect.setEmpty();
}
}
}
Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.
An ItemDecoration
is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.
The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
The below code useful to display in the map insertion order.
<ul>
<li *ngFor="let recipient of map | keyvalue: asIsOrder">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
.ts file add the below code.
asIsOrder(a, b) {
return 1;
}
Does it differ between different SQL implementations?
Yes, Microsoft Access doesn't allow just join
. It requires inner join
.
Download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer and add it to Keychain access > certificates (which expires on 2023)
(Jun-Nov 2016) The question and its answers are now out-of-date as: 1) GData APIs are the previous generation of Google APIs. While not all GData APIs have been deprecated, all the latest Google APIs do not use the Google Data Protocol; and 2) there is a new Google Sheets API v4 (also not GData).
Moving forward from here, you need to get the Google APIs Client Library for .NET and use the latest Sheets API, which is much more powerful and flexible than any previous API. Here's a C# code sample to help get you started. Also check the .NET reference docs for the Sheets API and the .NET Google APIs Client Library developers guide.
If you're not allergic to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with slightly longer, more "real-world" examples of using the API you can learn from and migrate to C# if desired:
Try this ...
import sys
buffer = []
while True:
userinput = sys.stdin.readline().rstrip('\n')
if userinput == 'quit':
break
else:
buffer.append(userinput)
This is here:
<button onClick="window.location='page_name.php';" value="click here" />
Here is a minor improvement for Denis Tulskiy answer. It cuts the time by half
public static long[] generateSeed(String goal, long start, long finish) {
char[] input = goal.toCharArray();
int[] dif = new int[input.length - 1];
for (int i = 1; i < input.length; i++) {
dif[i - 1] = input[i] - input[i - 1];
}
mainLoop:
for (long seed = start; seed < finish; seed++) {
Random random = new Random(seed);
int lastChar = random.nextInt(27);
int base = input[0] - lastChar;
for (int d : dif) {
int nextChar = random.nextInt(27);
if (nextChar - lastChar != d) {
continue mainLoop;
}
lastChar = nextChar;
}
if(random.nextInt(27) == 0){
return new long[]{seed, base};
}
}
throw new NoSuchElementException("Sorry :/");
}
Check out heredoc. Example:
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<"FOOBAR"
Hello World!
FOOBAR;
The is also nowdoc but no parsing is done inside the block.
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
You can solve the issue by clearing value of address in endpoint tag in web.config:
<endpoint address="" name="wsHttpEndpoint" ....... />
In IDEA 13 this seems to no longer be an issue, you just have to have the Lombok plugin installed.
I suggest you do it through the GET request: for example, index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="result.php" method="post">
Answer 1 <input type="radio" name="ans" value="ans1" /><br />
Answer 2 <input type="radio" name="ans" value="ans2" /><br />
Answer 3 <input type="radio" name="ans" value="ans3" /><br />
Answer 4 <input type="radio" name="ans" value="ans4" /><br />
<input type="button" value="submit" onclick="sendPost()" />
</form>
<script type="text/javascript">
function sendPost(){
var value = $('input[name="ans"]:checked').val();
window.location.href = "sendpost.php?ans="+value;
};
</script>
this is sendpost.php:
<?php
if(isset($_GET["ans"]) AND !empty($_GET["ans"])){
echo $_GET["ans"];
}
?>
I got it via the Prism.WPF NuGet-Package. (it includes Windows.System.Interactivity)
Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that's 8 concurrent requests.
Flask doesn't spawn or manage threads or processes. That's the responsability of the WSGI gateway (eg. gunicorn).
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
This post pertains to R proxy issues on *nix. You should know that R has many libraries/methods to fetch data over internet.
For 'curl', 'libcurl', 'wget' etc, just do the following:
Open a terminal. Type the following command:
sudo gedit /etc/R/Renviron.site
Enter the following lines:
http_proxy='http://username:[email protected]:port/'
https_proxy='https://username:[email protected]:port/'
Replace username
, password
, abc.com
, xyz.com
and port
with these settings specific to your network.
Quit R and launch again.
This should solve your problem with 'libcurl' and 'curl' method. However, I have not tried it with 'httr'. One way to do that with 'httr' only for that session is as follows:
library(httr)
set_config(use_proxy(url="abc.com",port=8080, username="username", password="password"))
You need to substitute settings specific to your n/w in relevant fields.
I think you are after this:
CONVERT(datetime, date_as_string, 103)
Notice, that datetime
hasn't any format. You think about its presentation. To get the data of datetime
in an appropriate format you can use
CONVERT(varchar, date_as_datetime, 103)
If you use Tomcat, you can map resources to the default servlet:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
and access your resources with url http://{context path}/static/res/...
Also works with Jetty, not sure about other servlet containers.
This is my code I'm using in my projects:
function isMobile() {
try {
if(/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)) {
return true;
};
return false;
} catch(e){ console.log("Error in isMobile"); return false; }
}
Expanding on @Robert Brisita has just expand , also if you don't want to set up all the variables of the profile in the script, you can select the variables to export on the top of the script
In crontab -e file:
SHELL=/bin/bash
*/1 * * * * /Path/to/script/script.sh
In script.sh
#!/bin/bash
export JAVA_HOME=/path/to/jdk
some-other-command
Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it
CASE
WHEN [condition.1] THEN [expression.1]
WHEN [condition.2] THEN [expression.2]
...
WHEN [condition.n] THEN [expression.n]
ELSE [expression]
END
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
This could also be the result of not updating your support packages when targeting Android 7.1, 8.0+. Update them to v25.4.0.2+ and this particular error might go away(giving you´ve configured your file_path file correctly as others stated).
Giving context: I switched to targeting Oreo from Nougat in a Xamarin.Forms app and taking a picture with the Xam.Plugin.Media started failing with the above error message, so updating the packages did the trick for me ok.
How about without using predefined function like min
or max
?
$arr = [4,5,6,7,8,2,9,1];
$val = $arr[0];
$n = count($arr);
for($i=1;$i<$n;$i++) {
if($val<$arr[$i]) {
$val = $val;
} else {
$val = $arr[$i];
}
}
print($val);
?>
Create a .htaccess file in the images folder and add this
<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>
you can put this Options All -Indexes
in the project file .htaccess
,file to deny direct access to other folders.
This does what you want
Simple and precise-
First of all, get a latest stable commit in which you have that file by -
git log
Say you find $commitid 1234567..., then
git checkout <$commitid> $fileName
This will restore the file version which was in that commit.
I have another solution that makes this possible. It requires the client be running Javascript (which I think is a fair requirement these days).
Simply use an AJAX request on Page A to go and generate your invoice number and customer details in the background (your previous Page B), then once the request gets returned successfully with the correct information - simply complete the form submission over to your payment gateway (Page C).
This will achieve your result of the user only clicking one button and proceeding to the payment gateway. Below is some pseudocode
HTML:
<form id="paymentForm" method="post" action="https://example.com">
<input type="hidden" id="customInvoiceId" .... />
<input type="hidden" .... />
<input type="submit" id="submitButton" />
</form>
JS (using jQuery for convenience but trivial to make pure Javascript):
$('#submitButton').click(function(e) {
e.preventDefault(); //This will prevent form from submitting
//Do some stuff like build a list of things being purchased and customer details
$.getJSON('setupOrder.php', {listOfProducts: products, customerDetails: details }, function(data) {
if (!data.error) {
$('#paymentForm #customInvoiceID').val(data.id);
$('#paymentForm').submit(); //Send client to the payment processor
}
});
You have a line break <br>
in-between the second and third images in your markup. Get rid of that, and it'll show inline.
Here is one more example. (check the reference)
const myObject = {_x000D_
"employeeid": "160915848",_x000D_
"firstName": "tet",_x000D_
"lastName": "test",_x000D_
"email": "[email protected]",_x000D_
"country": "Brasil",_x000D_
"currentIndustry": "aaaaaaaaaaaaa",_x000D_
"otherIndustry": "aaaaaaaaaaaaa",_x000D_
"currentOrganization": "test",_x000D_
"salary": "1234567"_x000D_
};_x000D_
const {otherIndustry, ...otherIndustry2} = myObject;_x000D_
console.log(otherIndustry2);
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
top: 0;_x000D_
}
_x000D_
I stumbled upon this post, looking to use CSS transform in jQuery for an infinite loop animation. This one worked fine for me. I don't know how professional it is though.
function progressAnim(e) {
var ang = 0;
setInterval(function () {
ang += 3;
e.css({'transition': 'all 0.01s linear',
'transform': 'rotate(' + ang + 'deg)'});
}, 10);
}
Example of using:
var animated = $('#elem');
progressAnim(animated)
I know this question is old, and already answered, but...
Since SqlDataReader already implements IEnumerable, why is there a need to create a loop over the records?
I've been using the method below without any issues, nor without any performance issues: So far I have tested with IList, List(Of T), IEnumerable, IEnumerable(Of T), IQueryable, and IQueryable(Of T)
Imports System.Data.SqlClient
Imports System.Data
Imports System.Threading.Tasks
Public Class DataAccess
Implements IDisposable
#Region " Properties "
''' <summary>
''' Set the Query Type
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property QueryType() As CmdType
Set(ByVal value As CmdType)
_QT = value
End Set
End Property
Private _QT As CmdType
''' <summary>
''' Set the query to run
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property Query() As String
Set(ByVal value As String)
_Qry = value
End Set
End Property
Private _Qry As String
''' <summary>
''' Set the parameter names
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ParameterNames() As Object
Set(ByVal value As Object)
_PNs = value
End Set
End Property
Private _PNs As Object
''' <summary>
''' Set the parameter values
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ParameterValues() As Object
Set(ByVal value As Object)
_PVs = value
End Set
End Property
Private _PVs As Object
''' <summary>
''' Set the parameter data type
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public WriteOnly Property ParameterDataTypes() As DataType()
Set(ByVal value As DataType())
_DTs = value
End Set
End Property
Private _DTs As DataType()
''' <summary>
''' Check if there are parameters, before setting them
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private ReadOnly Property AreParams() As Boolean
Get
If (IsArray(_PVs) And IsArray(_PNs)) Then
If (_PVs.GetUpperBound(0) = _PNs.GetUpperBound(0)) Then
Return True
Else
Return False
End If
Else
Return False
End If
End Get
End Property
''' <summary>
''' Set our dynamic connection string
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private ReadOnly Property _ConnString() As String
Get
If System.Diagnostics.Debugger.IsAttached OrElse My.Settings.AttachToBeta OrElse Not (Common.CheckPaid) Then
Return My.Settings.DevConnString
Else
Return My.Settings.TurboKitsv2ConnectionString
End If
End Get
End Property
Private _Rdr As SqlDataReader
Private _Conn As SqlConnection
Private _Cmd As SqlCommand
#End Region
#Region " Methods "
''' <summary>
''' Fire us up!
''' </summary>
''' <remarks></remarks>
Public Sub New()
Parallel.Invoke(Sub()
_Conn = New SqlConnection(_ConnString)
End Sub,
Sub()
_Cmd = New SqlCommand
End Sub)
End Sub
''' <summary>
''' Get our results
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetResults() As SqlDataReader
Try
Parallel.Invoke(Sub()
If AreParams Then
PrepareParams(_Cmd)
End If
_Cmd.Connection = _Conn
_Cmd.CommandType = _QT
_Cmd.CommandText = _Qry
_Cmd.Connection.Open()
_Rdr = _Cmd.ExecuteReader(CommandBehavior.CloseConnection)
End Sub)
If _Rdr.HasRows Then
Return _Rdr
Else
Return Nothing
End If
Catch sEx As SqlException
Return Nothing
Catch ex As Exception
Return Nothing
End Try
End Function
''' <summary>
''' Prepare our parameters
''' </summary>
''' <param name="objCmd"></param>
''' <remarks></remarks>
Private Sub PrepareParams(ByVal objCmd As Object)
Try
Dim _DataSize As Long
Dim _PCt As Integer = _PVs.GetUpperBound(0)
For i As Long = 0 To _PCt
If IsArray(_DTs) Then
Select Case _DTs(i)
Case 0, 33, 6, 9, 13, 19
_DataSize = 8
Case 1, 3, 7, 10, 12, 21, 22, 23, 25
_DataSize = Len(_PVs(i))
Case 2, 20
_DataSize = 1
Case 5
_DataSize = 17
Case 8, 17, 15
_DataSize = 4
Case 14
_DataSize = 16
Case 31
_DataSize = 3
Case 32
_DataSize = 5
Case 16
_DataSize = 2
Case 15
End Select
objCmd.Parameters.Add(_PNs(i), _DTs(i), _DataSize).Value = _PVs(i)
Else
objCmd.Parameters.AddWithValue(_PNs(i), _PVs(i))
End If
Next
Catch ex As Exception
End Try
End Sub
#End Region
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
End If
Try
Erase _PNs : Erase _PVs : Erase _DTs
_Qry = String.Empty
_Rdr.Close()
_Rdr.Dispose()
_Cmd.Parameters.Clear()
_Cmd.Connection.Close()
_Conn.Close()
_Cmd.Dispose()
_Conn.Dispose()
Catch ex As Exception
End Try
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
Protected Overrides Sub Finalize()
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(False)
MyBase.Finalize()
End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Strong Typing Class
Public Class OrderDCTyping
Public Property OrderID As Long = 0
Public Property OrderTrackingNumber As String = String.Empty
Public Property OrderShipped As Boolean = False
Public Property OrderShippedOn As Date = Nothing
Public Property OrderPaid As Boolean = False
Public Property OrderPaidOn As Date = Nothing
Public Property TransactionID As String
End Class
Usage
Public Function GetCurrentOrders() As IEnumerable(Of OrderDCTyping)
Try
Using db As New DataAccess
With db
.QueryType = CmdType.StoredProcedure
.Query = "[Desktop].[CurrentOrders]"
Using _Results = .GetResults()
If _Results IsNot Nothing Then
_Qry = (From row In _Results.Cast(Of DbDataRecord)()
Select New OrderDCTyping() With {
.OrderID = Common.IsNull(Of Long)(row, 0, 0),
.OrderTrackingNumber = Common.IsNull(Of String)(row, 1, String.Empty),
.OrderShipped = Common.IsNull(Of Boolean)(row, 2, False),
.OrderShippedOn = Common.IsNull(Of Date)(row, 3, Nothing),
.OrderPaid = Common.IsNull(Of Boolean)(row, 4, False),
.OrderPaidOn = Common.IsNull(Of Date)(row, 5, Nothing),
.TransactionID = Common.IsNull(Of String)(row, 6, String.Empty)
}).ToList()
Else
_Qry = Nothing
End If
End Using
Return _Qry
End With
End Using
Catch ex As Exception
Return Nothing
End Try
End Function
I would add another column on the data sheet with equation =month(A2), then run the countif on that column... If you still wanted to use text month('APRIL'), you would need a lookup table to reference the name to the month number. Otherwise, just use 4 instead of April on your metric sheet.
bs := string(body)
should be enough to give you a string.
From there, you can use it as a regular string.
A bit as in this thread:
var client http.Client
resp, err := client.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
bodyString := string(bodyBytes)
log.Info(bodyString)
}
See also GoByExample.
As commented below (and in zzn's answer), this is a conversion (see spec).
See "How expensive is []byte(string)
?" (reverse problem, but the same conclusion apply) where zzzz mentioned:
Some conversions are the same as a cast, like
uint(myIntvar)
, which just reinterprets the bits in place.
Sonia adds:
Making a string out of a byte slice, definitely involves allocating the string on the heap. The immutability property forces this.
Sometimes you can optimize by doing as much work as possible with []byte and then creating a string at the end. Thebytes.Buffer
type is often useful.
The accepted answer does not correctly dispose the WebResponse
or decode the text. Also, there's a new way to do this in .NET 4.5.
To perform an HTTP GET and read the response text, do the following.
public static string GetResponseText(string address)
{
var request = (HttpWebRequest)WebRequest.Create(address);
using (var response = (HttpWebResponse)request.GetResponse())
{
var encoding = Encoding.GetEncoding(response.CharacterSet);
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream, encoding))
return reader.ReadToEnd();
}
}
private static readonly HttpClient httpClient = new HttpClient();
public static async Task<string> GetResponseText(string address)
{
return await httpClient.GetStringAsync(address);
}
It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:
ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************ TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif
One more time, building off of @RalphyZ
This one doesn't break the exposed API.
from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# Add back help
optional.add_argument(
'-h',
'--help',
action='help',
default=SUPPRESS,
help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
Which will show the same as above and should survive future versions:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
Eclipse itself will add the @Override
annotation when you tell it to "generate unimplemented methods" during creation of a class that implements an interface.
You want:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
You may not place the deprecated non-block-scoped stage
(as in the original question) inside parallel
.
As of JENKINS-26107, stage
takes a block argument. You may put parallel
inside stage
or stage
inside parallel
or stage
inside stage
etc. However visualizations of the build are not guaranteed to support all nestings; in particular
stage
nesting.parallel
branches inside a top-level stage, but currently no more.JENKINS-27394, if implemented, would display arbitrarily nested stage
s.
The accepted answer is correct. I would like to provide an example to elaborate it a bit to those who aren't familiar with promise
.
Example:
In my example, I need to replace the src
attributes of img
tags with different mirror urls if available before rendering the content.
var img_tags = content.querySelectorAll('img');
function checkMirrorAvailability(url) {
// blah blah
return promise;
}
function changeSrc(success, y, response) {
if (success === true) {
img_tags[y].setAttribute('src', response.mirror_url);
}
else {
console.log('No mirrors for: ' + img_tags[y].getAttribute('src'));
}
}
var promise_array = [];
for (var y = 0; y < img_tags.length; y++) {
var img_src = img_tags[y].getAttribute('src');
promise_array.push(
checkMirrorAvailability(img_src)
.then(
// a callback function only accept ONE argument.
// Here, we use `.bind` to pass additional arguments to the
// callback function (changeSrc).
// successCallback
changeSrc.bind(null, true, y),
// errorCallback
changeSrc.bind(null, false, y)
)
);
}
$q.all(promise_array)
.then(
function() {
console.log('all promises have returned with either success or failure!');
render(content);
}
// We don't need an errorCallback function here, because above we handled
// all errors.
);
Explanation:
From AngularJS docs:
The then
method:
then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason.
$q.all(promises)
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
The promises
param can be an array of promises.
About bind()
, More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
This is my solution. From my point of view, you can not bypass the <a>
.
function export2json() {_x000D_
const data = {_x000D_
a: '111',_x000D_
b: '222',_x000D_
c: '333'_x000D_
};_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(_x000D_
new Blob([JSON.stringify(data, null, 2)], {_x000D_
type: "application/json"_x000D_
})_x000D_
);_x000D_
a.setAttribute("download", "data.json");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2json()">Export data to json file</button>
_x000D_
If you have anything in particular you want to hide (like a proprietary algorithm), put that on the server, or put it in a Flash movie and call it with JavaScript. Writing ActionScript is very similar to writing JavaScript, and you can communicate between JavaScript and ActionScript. You can do the same with Silverlight, but Silverlight doesn't have the penetration Flash does.
However, remember that any mobile phones can run your JavaScript, but not Silverlight or Flash, so you're crippling your mobile users if you go with Flash or Silverlight.
-- Update --
As of January 9th, 2015. the solution is now implemented in Rails 5 ActiveRecord's secure token implementation.
-- Rails 4 & 3 --
Just for future reference, creating safe random token and ensuring it's uniqueness for the model (when using Ruby 1.9 and ActiveRecord):
class ModelName < ActiveRecord::Base
before_create :generate_token
protected
def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless ModelName.exists?(token: random_token)
end
end
end
Edit:
@kain suggested, and I agreed, to replace begin...end..while
with loop do...break unless...end
in this answer because previous implementation might get removed in the future.
Edit 2:
With Rails 4 and concerns, I would recommend moving this to concern.
# app/models/model_name.rb
class ModelName < ActiveRecord::Base
include Tokenable
end
# app/models/concerns/tokenable.rb
module Tokenable
extend ActiveSupport::Concern
included do
before_create :generate_token
end
protected
def generate_token
self.token = loop do
random_token = SecureRandom.urlsafe_base64(nil, false)
break random_token unless self.class.exists?(token: random_token)
end
end
end
It was not clear to me in the question if ts.tax_status_code is a primary or alternate key or not. Same thing with recipient_code. This would be useful to know.
You can deal with the possibility of your bind variable being null using an OR as follows. You would bind the same thing to the first two bind variables.
If you are concerned about performance, you would be better to check if the values you intend to bind are null or not and then issue different SQL statement to avoid the OR.
insert into account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
(
select
account_type_standard_seq.nextval,
ts.tax_status_id,
r.recipient_id
from tax_status ts, recipient r
where (ts.tax_status_code = ? OR (ts.tax_status_code IS NULL and ? IS NULL))
and (r.recipient_code = ? OR (r.recipient_code IS NULL and ? IS NULL))
Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:
df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})
a b c
0 1 1 x
1 2 1 x
2 3 0 y
3 4 1 y
4 5 1 z
5 6 0 z
df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())
c
x 2.0
y 4.0
z 5.0
I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.
It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.
df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())
df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']
df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())
I hope this helps.
Enter services.msc and shutdown anything SQL you have running. The SQL server might be taking over the port.
I would just mention that you can use the cat
command to concatenate the input files prior to piping them to markdown_py
which has the same effect as what pandoc
does with multiple input files coming in.
cat *.md | markdown_py > youroutputname.html
works pretty much the same as the pandoc example above for the Python version of Markdown on my Mac.
I have encoding problems with XMLFilter solution, so I made XMLStreamReader to ignore namespaces:
class XMLReaderWithoutNamespace extends StreamReaderDelegate {
public XMLReaderWithoutNamespace(XMLStreamReader reader) {
super(reader);
}
@Override
public String getAttributeNamespace(int arg0) {
return "";
}
@Override
public String getNamespaceURI() {
return "";
}
}
InputStream is = new FileInputStream(name);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
Unmarshaller um = jc.createUnmarshaller();
Object res = um.unmarshal(xr);
SELECT * INTO newtable FROM oldtable where 1=2
Where 1=2
is used when you need to copy the complete structure of a
table without copying the data.
SELECT * INTO newtable FROM oldtable
To create a table with data you can use this statement.
ipconfig /renew
- solved this issue for me.
Yes, this will actually work just fine. Grep
and most Unix commands operate on streams one line at a time. Each line that comes out of tail will be analyzed and passed on if it matches.
Usually the /proc
directory contains such information in Linux, it is a virtual filesystem. For example, /proc/mounts
gives information about current mounted disks; and you can parse it directly. Utilities like top
, df
all make use of /proc
.
I haven't used it, but this might help too, if you want a wrapper: http://bitbucket.org/chrismiles/psi/wiki/Home
If you have a jenkinsfile for your pipeline, check if you see at execution time your branch name in your environment variables.
You can print them with:
pipeline {
agent any
environment {
DISABLE_AUTH = 'true'
DB_ENGINE = 'sqlite'
}
stages {
stage('Build') {
steps {
sh 'printenv'
}
}
}
}
However, PR 91 shows that the branch name is only set in certain pipeline configurations:
iOS Status bar has only 2 options (black and white). You can try this in AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
}
Depending on what kind of image you have, it might be better to rework the design so that the main image fades to a set solid color or repeatable pattern. If you center the image in the page and have the solid color as the backgroud.
See http://www.webdesignerwall.com/trends/80-large-background-websites/ for examples of sites using large or scalable backgrounds.
Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.
library(tidyverse)
MyDate %>%
filter(!is.na(the_variable)) %>%
ggplot(aes(x= the_variable, fill=the_variable)) +
geom_bar(stat="bin")
You should be able to remove the annoying NAs on your plot. Hope this works :)
GoogleSamples has verbose example using latest FusedLocationProviderApi. Unfortunately the most upvoted answers are out of date.
Follow the below examples to implement Location Services using FusedLocationProviderApi
https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates
In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.
You can read more with examples here.
When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.
For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.
Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.
So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.
You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.
If you are looking for an easy example please use the following link with example
You can use an index in a range and then access the array via its index:
<ul>
<li v-for="index in 10" :key="index">
{{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
</li>
</ul>
You can also check the Official Documentation for more information.
The way that I usually go about it is using a temporary table. It's probably not computationally efficient but it seems to work ok! Here i am duplicating record 99 in its entirety, creating record 100.
CREATE TEMPORARY TABLE tmp SELECT * FROM invoices WHERE id = 99;
UPDATE tmp SET id=100 WHERE id = 99;
INSERT INTO invoices SELECT * FROM tmp WHERE id = 100;
Hope that works ok for you!
This is a quick and simple add of a named tab to the current worksheet:
Sheets.Add.Name = "Tempo"
The crc code in zlib (http://zlib.net/) is among the fastest there is, and has a very liberal open source license.
And you should not use adler-32 except for special applications where speed is more important than error detection performance.
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
If you only want to know if any item of d
is contained in paid[j]
, as you literally say:
if any(x in paid[j] for x in d): ...
If you also want to know which items of d
are contained in paid[j]
:
contained = [x for x in d if x in paid[j]]
contained
will be an empty list if no items of d
are contained in paid[j]
.
There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d
contained in paid[j]
(and None
if no item is so contained):
firstone = next((x for x in d if x in paid[j]), None)
BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in
'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j]
into some more sophisticated predicate such as somere.search(paid[j])
for an appropriate RE object somere
.
(Python 2.6 or better -- slight differences in 2.5 and earlier).
If your intention is something else again, such as getting one or all of the indices in d
of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).
Use this code
Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
(int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.your_notification_icon)
.setContentTitle("Notification title")
.setContentText("Notification message!")
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());
This solution worked perfectly for me
var table = document.getElementById("myTable").rows;
var y;
for(i = 0; i < # of rows; i++)
{ for(j = 0; j < # of columns; j++)
{
y = table[i].cells;
//do something with cells in a row
y[j].innerHTML = "";
}
}
Target parameters:
float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);
Your original file:
var image = new Bitmap(file);
Target sizing (scale factor):
float scale = Math.Min(width / image.Width, height / image.Height);
The resize including brushing canvas first:
var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);
// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;
var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);
graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);
And don't forget to do a bmp.Save(filename)
to save the resulting file.
In fact, you can't change the time once it's created. But you can create it easily with many constructors: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2
For example, if you want to create a DateTime changing Seconds, you can just do this:
DateTime now = DateTime.Now;
DateTime secondschanged = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, yourseconds);
You can also use map:
a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))
It gives:
[2, 2, 2, 2, 2]
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
Servlets :
The Java Servlet API enables Java developers to write server-side code for delivering dynamic Web content. Like other proprietary Web server APIs, the Java Servlet API offered improved performance over CGI; however, it has some key additional advantages. Because servlets were coded in Java, they provides an object-oriented (OO) design approach and, more important, are able to run on any platform. Thus, the same code was portable to any host that supported Java. Servlets greatly contributed to the popularity of Java, as it became a widely used technology for server-side Web application development.
JSP :
JSP is built on top of servlets and provides a simpler, page-based solution to generating large amounts of dynamic HTML content for Web user interfaces. JavaServer Pages enables Web developers and designers to simply edit HTML pages with special tags for the dynamic, Java portions. JavaServer Pages works by having a special servlet known as a JSP container, which is installed on a Web server and handles all JSP page view requests. The JSP container translates a requested JSP into servlet code that is then compiled and immediately executed. Subsequent requests to the same page simply invoke the runtime servlet for the page. If a change is made to the JSP on the server, a request to view it triggers another translation, compilation, and restart of the runtime servlet.
JSF :
JavaServer Faces is a standard Java framework for building user interfaces for Web applications. Most important, it simplifies the development of the user interface, which is often one of the more difficult and tedious parts of Web application development.
Although it is possible to build user interfaces by using foundational Java Web technologies(such as Java servlets and JavaServer Pages) without a comprehensive framework designedfor enterprise Web application development, these core technologies can often lead to avariety of development and maintenance problems. More important, by the time the developers achieve a production-quality solution, the same set of problems solved by JSF will have been solved in a nonstandard manner. JavaServer Faces is designed to simplify the development of user interfaces for Java Web applications in the following ways:
• It provides a component-centric, client-independent development approach to building Web user interfaces, thus improving developer productivity and ease of use.
• It simplifies the access and management of application data from the Web user interface.
• It automatically manages the user interface state between multiple requests and multiple clients in a simple and unobtrusive manner.
• It supplies a development framework that is friendly to a diverse developer audience with different skill sets.
• It describes a standard set of architectural patterns for a web application.
[ Source : Complete reference:JSF ]
Just try this one it works fine for me.
let grouped = _.groupBy(cars, 'make');
Note: Using lodash lib, so include it.
In a general sense, SQL Server does not support regular expressions and you cannot use them in the native T-SQL code.
You could write a CLR function to do that. See here, for example.
Another approach in 3.4 (don't know if this is proper Ext): You can have a delete handler like this, assuming every row has a 'delete' button.
handler: function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
var id = rec.get('id');
// some DELETE/GET ajax callback here...
// pass in 'id' var or some key
// inside success
grid.getStore().removeAt(rowIndex);
}
Why not just use that:
manage.py inspectdb
Example output:
class GuardianUserobjectpermission(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
object_pk = models.CharField(max_length=255)
content_type = models.ForeignKey(DjangoContentType, models.DO_NOTHING)
permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
user = models.ForeignKey(CustomUsers, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'guardian_userobjectpermission'
unique_together = (('user', 'permission', 'object_pk'),)
I would use ternary operators to categorize your switch conditions.
So...
switch( number > 9 ? "High" :
number > 5 ? "Mid" :
number > 1 ? "Low" : "Floor")
{
case "High":
do the thing;
break;
case "Mid":
do the other thing;
break;
case "Low":
do something else;
break;
case "Floor":
do whatever;
break;
}
Scanner sc = new Scanner(System.in);
System.out.println("\n number of input sets::");
int value=sc.nextInt();
System.out.println("\n input sets::");
int[] inputset;
inputset = new int[value];
for(int i=0;i<value;i++)
{
inputset[i]=sc.nextInt();
}
int maxvalue=inputset[0];
int secondval=inputset[0];
for(int i=1;i<value;i++)
{
if(inputset[i]>maxvalue)
{
maxvalue=inputset[i];
}
}
for(int i=1;i<value;i++)
{
if(inputset[i]>secondval && inputset[i]<maxvalue)
{
secondval=inputset[i];
}
}
System.out.println("\n maxvalue"+ maxvalue);
System.out.println("\n secondmaxvalue"+ secondval);
You need to add style="overflow-y:scroll;"
to the div tag. (This will force a scrollbar on the vertical).
If you only want a scrollbar when needed, just do overflow-y:auto;
These are all great suggestions, but if you know location of text in another file use sed with ease. :r! sed -n '1,10 p' < input_file.txt
This will insert 10 lines in an already open file at the current position of the cursor.
Since Entity Framework 5.0 you can use following code in order to solve your issue:
public abstract class YourContext : DbContext
{
public YourContext()
{
(this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
}
}
This should solve your problems as Entity Framerwork will use 'C# like' null comparison.
This statement works for me
ALTER TABLE table_name DROP UNIQUE (column_name);
Use Invoke-RestMethod
to consume REST-APIs. Save the JSON to a string and use that as the body, ex:
$JSON = @'
{"@type":"login",
"username":"[email protected]",
"password":"yyy"
}
'@
$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
If you use Powershell 3, I know there have been some issues with Invoke-RestMethod
, but you should be able to use Invoke-WebRequest
as a replacement:
$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"
If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.
$JSON = @{
"@type" = "login"
"username" = "[email protected]"
"password" = "yyy"
} | ConvertTo-Json
Python 3.5 adds the math.isclose
and cmath.isclose
functions as described in PEP 485.
If you're using an earlier version of Python, the equivalent function is given in the documentation.
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
rel_tol
is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.
abs_tol
is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.
Its actually formulated more like:
https://<bucket-name>.s3.amazonaws.com/<key>
See here
Make Directory savehere to be virtual directory and give read/write permission from control panel
You Can Used This :
function ViewImage(){
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('input[type="file"]').files[0];
getBase64(file).then(data =>$("#ImageBase46").val(data));
}
Add To Your Input onchange=ViewImage();
It's easier than it is thought:
my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation
As already said, the easiest way is to use querystring.
But if you cannot, because of security reason, you should consider using cookies.
dic0.update(dic1)
Note this doesn't actually return the combined dictionary, it just mutates dic0
.
IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat
If you want to impute missing values with mean and you want to go column by column, then this will only impute with the mean of that column. This might be a little more readable.
sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))
As of Python 3.4 one can use the pathlib module to solve this.
If you happen to be on an older version, you can use the backported version found here
Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this:
some_path = 'a/b/c/the_file.extension'
So, you can take your path and create a Path
object out of it:
from pathlib import Path
p = Path(some_path)
Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file
to the_file_1
, then we can get the filename part:
name_without_extension = p.stem
And still hold the extension in hand as well:
ext = p.suffix
We can perform our modification with a simple string manipulation:
Python 3.6 and greater make use of f-strings!
new_file_name = f"{name_without_extension}_1"
Otherwise:
new_file_name = "{}_{}".format(name_without_extension, 1)
And now we can perform our rename by calling the rename
method on the path object we created and appending the ext
to complete the proper rename structure we want:
p.rename(Path(p.parent, new_file_name + ext))
More shortly to showcase its simplicity:
Python 3.6+:
from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))
Versions less than Python 3.6 use the string format method instead:
from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))
Go to File>Project Structure>JDK location:
Here, you have to set the directory path exactly same, in which you have installed the java version.
Also, you have to mention the paths of SDK for project run on emulator successfully.
Why This Problem Occurs: It is due to the unsynchronized java version directory that should be available to Android Studio for java code compilance.
In my case the problem was cause by a disabled PK.
In order to enable it:
I look for the Constraint name with:
SELECT * FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'referenced_table_name';
Then I took the Constraint name in order to enable it with the following command:
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name;
Further to @montrealmike 's answer, can I just add my adaptation?
I did this:
.container {
overflow: hidden;
....
}
#sidebar {
margin-bottom: -101%;
padding-bottom: 101%;
....
}
I did the "101%" thing to cater for the (ultra rare) possibility that somebody may be viewing the site on a huge screen with a height more than 5000px!
Great answer though, montrealmike. It worked perfectly for me.
function parameter string value image dynamically from JSON. Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter.
My Function Onclick
items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+" onclick='changeImage(\""+item.product_image2+"\");'>";
My Function
<script type="text/javascript">
function changeImage(img)
{
document.getElementById("saleDetailDivGetImg").src=img;
alert(img);
}
</script>
Just a NOTE, something that I wasted hours tracking down tonight...
If you decide to hold onto a marker for some reason, after you have REMOVED it from a map... getTag will return NULL, even though the remaining get values will return with the values you set them to when the marker was created...
TAG value is set to NULL if you ever remove a marker, and then attempt to reference it.
Seems like a bug to me...
Finally I could successfully compile a program with C++ connector in Ubuntu 12.04 I have installed the connector using this command
'apt-get install libmysqlcppconn-dev'
Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.
sql::mysql::MySQL_Driver *driver;
try {
driver = sql::mysql::get_driver_instance();
}
and I compiled the program with -l mysqlcppconn linker option
and don't forget to include this header
#include "mysql_driver.h"
In my case it works like this:
...
<properties>
<main_dir>${project.parent.relativePath}/..</main_dir>
</properties>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-1</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${main_dir}/maven_custom.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
For set tint for an image view programmatically in android
I have two methods for android :
1)
imgView.setColorFilter(context.getResources().getColor(R.color.blue));
2)
DrawableCompat.setTint(imgView.getDrawable(),
ContextCompat.getColor(context, R.color.blue));
I hope I helped anyone out :-)
Yes.
Set a reference to MS Scripting runtime ('Microsoft Scripting Runtime'). As per @regjo's comment, go to Tools->References and tick the box for 'Microsoft Scripting Runtime'.
Create a dictionary instance using the code below:
Set dict = CreateObject("Scripting.Dictionary")
or
Dim dict As New Scripting.Dictionary
Example of use:
If Not dict.Exists(key) Then
dict.Add key, value
End If
Don't forget to set the dictionary to Nothing
when you have finished using it.
Set dict = Nothing
REQUIREMENTS files.
Seriously, I use this in conjunction with virtualenv every day.
QUICK DEPENDENCY MANAGEMENT TUTORIAL, FOLKS
Requirements files allow you to create a snapshot of all packages that have been installed through pip. By encapsulating those packages in a virtualenvironment, you can have your codebase work off a very specific set of packages and share that codebase with others.
From Heroku's documentation https://devcenter.heroku.com/articles/python
You create a virtual environment, and set your shell to use it. (bash/*nix instructions)
virtualenv env
source env/bin/activate
Now all python scripts run with this shell will use this environment's packages and configuration. Now you can install a package locally to this environment without needing to install it globally on your machine.
pip install flask
Now you can dump the info about which packages are installed with
pip freeze > requirements.txt
If you checked that file into version control, when someone else gets your code, they can setup their own virtual environment and install all the dependencies with:
pip install -r requirements.txt
Any time you can automate tedium like this is awesome.
Power is **
and e^
is math.exp
:
x.append(1 - math.exp(-0.5 * (value1*value2)**2))
In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.
In case of entity framework FK in dependent must also be its PK so in your case you should use:
public class Boo
{
[Key, ForeignKey("Foo")]
public string BooId{get;set;}
public Foo Foo{get;set;}
}
Or fluent mapping
modelBuilder.Entity<Foo>()
.HasOptional(f => f.Boo)
.WithRequired(s => s.Foo);
There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/
This allows you to write very clean code like this:
string value = null;
int? x = value.ConvertOrDefault<int?>();
and also:
object obj = 1;
string value = null;
int x = 5;
if (value.TryConvert(out x))
Console.WriteLine("TryConvert example: " + x);
bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();
MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();
Just for reference, if you are using:
$(el).offset().top
To get the position, it can be affected by the position of the parent element. Thus you may want to be consistent and use the following to set it:
$(el).offset({top: pos});
As opposed to the CSS methods above.
Try this code
$serverName = "serverName\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
Using jQuery you can use contents()
. For example:
var inside = $('#one').contents();
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
Object doesn't support this property or method.
Think of it like if anything after the dot is called on an object. It's like a chain.
An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot .
you get intelli-sense (that white dropdown) trying to help you pick the correct action.
(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)
Type this much anywhere in your code area
Dim a As Worksheets
a.
you get help from VBE, it's a little dropdown called Intelli-sense
It lists all available actions that particular object exposes to any user. You can't see the .Selection
member of the Worksheets()
class. That's what the error tells you exactly.
Object doesn't support this property or method.
If you look at the example on MSDN
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
It activates
the sheet first then calls the Selection...
it's not connected together because Selection
is not a member of Worksheets()
class. Simply, you can't prefix the Selection
What about
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
MsgBox "The selection contains " & Selection.Columns.Count & " columns."
Else
For i = 1 To iAreaCount
MsgBox "Area " & i & " of the selection contains " & _
Selection.Areas(i).Columns.Count & " columns."
Next i
End If
End Sub
from HERE
For i As Integer = 0 To 100
bool = False
For j As Integer = 0 To 100
If check condition Then
'if condition match
bool = True
Exit For 'Continue For
End If
Next
If bool = True Then Continue For
Next
verify
itself returns an error if expired. Safer as @Gabriel said.
const jwt = require('jsonwebtoken')
router.use((req, res, next) => {
const token = yourJwtService.getToken(req) // Get your token from the request
jwt.verify(token, req.app.get('your-secret'), function(err, decoded) {
if (err) throw new Error(err) // Manage different errors here (Expired, untrusted...)
req.auth = decoded // If no error, token info is returned in 'decoded'
next()
});
})
And same written in async/await
syntax:
const jwt = require('jsonwebtoken')
const jwtVerifyAsync = util.promisify(jwt.verify);
router.use(async (req, res, next) => {
const token = yourJwtService.getToken(req) // Get your token from the request
try {
req.auth = await jwtVerifyAsync(token, req.app.get('your-secret')) // If no error, token info is returned
} catch (err) {
throw new Error(err) // Manage different errors here (Expired, untrusted...)
}
next()
});
Your current directory does not has the write/create permission to create kivy
directory, thats why occuring this problem.
Your current directory give 777 rights and try it.
sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git
This is possible if you have an existing Newline character in the row or another row.
Select the square-box that represents the existing Newline character, copy it (control-C), and then paste it (control-V) where you want it to be.
This is slightly cheesy, but I actually did get it to work in SSMS 2008 and I was not able to get any of the other suggestions (control-enter, alt-13, or any alt-##) to work.
You can add a div
to the td
, then style that. It should work as you expected.
<td><div>AAAAAAAAAAAAAAAAAAA</div></td>
Then the css.
td div { width: 50px; overflow: hidden; }
I had some trouble similar to this,
<repository>
<id>java.net</id>
<url>https://maven-repository.dev.java.net/nonav/repository</url>
<layout>legacy</layout>
</repository>
<repository>
<id>java.net2</id>
<url>https://maven2-repository.dev.java.net/nonav/repository</url>
</repository>
Setting the updatePolicy to "never" did not work. Removing these repo was the way I solved it. ps: I was following this tutorial about web services (btw, probably the best tutorial for ws for java)
Rclone is what you are looking for. Rclone ("rsync for cloud storage") is a command line program to sync files and directories to and from different cloud storage providers including local filesystems. Rclone was previously known as Swiftsync and has been available since 2013.
regarding jQuery:
the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.
Reference: http://api.jquery.com/remove/
jQuery v1.8.2 .remove()
source code:
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
}
apparently jQuery uses node.removeChild()
According to this : https://developer.mozilla.org/en-US/docs/DOM/Node.removeChild ,
The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.
ie event listeners might get removed, but node
still exists in memory.
A more distilled quick answer:
git add -A
git add .
git add -u
DML have to be committed or rollbacked. DDL cannot.
http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands
You can switch auto-commit on and that's again only for DML. DDL are never part of transactions and therefore there is nothing like an explicit commit/rollback.
truncate
is DDL and therefore commited implicitly.
Edit
I've to say sorry. Like @DCookie and @APC stated in the comments there exist sth like implicit commits for DDL. See here for a question about that on Ask Tom.
This is in contrast to what I've learned and I am still a bit curious about.
If you are debugging or similar - In chrome developer tools, you can simply use
$x('/html/.//div[@id="text"]')
Why not try adding Scope? Scope is a very good feature of Eloquent.
class User extends Eloquent {
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
public function scopeWomen($query)
{
return $query->whereGender('W');
}
}
$users = User::popular()->women()->orderBy('created_at')->get();
Something like this will work
arr = ["A", "B", "C", "B", "A"]
arr.inject(Hash.new(0)) { |h,e| h[e] += 1; h }.
select { |k,v| v > 1 }.
collect { |x| x.first }
That is, put all values to a hash where key is the element of array and value is number of occurences. Then select all elements which occur more than once. Easy.
There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.
class JSonModel {
...
[JsonIgnore]
public DateTime MyDate { get; set; }
[JsonProperty("date")]
public string CustomDate {
get { return MyDate.ToString("ddMMyyyy"); }
// set { MyDate = DateTime.Parse(value); }
set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
}
...
}
This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.
You can group those first according to some criteria. In this post I will just explain the underscore character and the right-arrow.
_._
contains a period. A period in Scala always indicates a method call. So left of the period you have the receiver, and right of it the message (method name). Now _
is a special symbol in Scala. There are several posts about it, for example this blog entry all use cases. Here it is an anonymous function short cut, that is it a shortcut for a function that takes one argument and invokes the method _
on it. Now _
is not a valid method, so most certainly you were seeing _._1
or something similar, that is, invoking method _._1
on the function argument. _1
to _22
are the methods of tuples which extract a particular element of a tuple. Example:
val tup = ("Hallo", 33)
tup._1 // extracts "Hallo"
tup._2 // extracts 33
Now lets assume a use case for the function application shortcut. Given a map which maps integers to strings:
val coll = Map(1 -> "Eins", 2 -> "Zwei", 3 -> "Drei")
Wooop, there is already another occurrence of a strange punctuation. The hyphen and greater-than characters, which resemble a right-hand arrow, is an operator which produces a Tuple2
. So there is no difference in the outcome of writing either (1, "Eins")
or 1 -> "Eins"
, only that the latter is easier to read, especially in a list of tuples like the map example. The ->
is no magic, it is, like a few other operators, available because you have all implicit conversions in object scala.Predef
in scope. The conversion which takes place here is
implicit def any2ArrowAssoc [A] (x: A): ArrowAssoc[A]
Where ArrowAssoc
has the ->
method which creates the Tuple2
. Thus 1 -> "Eins"
is actual the call Predef.any2ArrowAssoc(1).->("Eins")
. Ok. Now back to the original question with the underscore character:
// lets create a sequence from the map by returning the
// values in reverse.
coll.map(_._2.reverse) // yields List(sniE, iewZ, ierD)
The underscore here shortens the following equivalent code:
coll.map(tup => tup._2.reverse)
Note that the map
method of a Map passes in the tuple of key and value to the function argument. Since we are only interested in the values (the strings), we extract them with the _2
method on the tuple.
jj is super-fast, can handle ginormous JSON documents economically, does not mess with valid JSON numbers, and is easy to use, e.g.
jj -p # for reading from STDIN
or
jj -p -i input.json
It is (2018) still quite new so maybe it won’t handle invalid JSON the way you expect, but it is easy to install on major platforms.
I think it may vary from system to system but one way of checking would be to just use printf
#include <stdio.h>
int main(void)
{
printf("%d", EOF);
return 0;
}
I did this on Windows and -1
was printed to the console. Hope this helps.
I think you may also use the command line :
git add -p
This allows you to review all your uncommited files, one by one and choose if you want to commit them or not.
Then you have some options that will come up for each modification: I use the "y" for "yes I want to add this file" and the "n" for "no, I will commit this one later".
Stage this hunk [y,n,q,a,d,K,g,/,e,?]?
As for the other options which are ( q,a,d,K,g,/,e,? ), I'm not sure what they do, but I guess the "?" might help you out if you need to go deeper into details.
The great thing about this is that you can then push your work, and create a new branch after and all the uncommited work will follow you on that new branch. Very useful if you have coded many different things and that you actually want to reorganise your work on github before pushing it.
Hope this helps, I have not seen it said previously (if it was mentionned, my bad)
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
To search for commit content (i.e., actual lines of source, as opposed to commit messages and the like), you need to do:
git grep <regexp> $(git rev-list --all)
git rev-list --all | xargs git grep <expression>
will work if you run into an "Argument list too long" error.
If you want to limit the search to some subtree (for instance, "lib/util"), you will need to pass that to the rev-list
subcommand and grep
as well:
git grep <regexp> $(git rev-list --all -- lib/util) -- lib/util
This will grep through all your commit text for regexp
.
The reason for passing the path in both commands is because rev-list
will return the revisions list where all the changes to lib/util
happened, but also you need to pass to grep
so that it will only search in lib/util
.
Just imagine the following scenario: grep
might find the same <regexp>
on other files which are contained in the same revision returned by rev-list
(even if there was no change to that file on that revision).
Here are some other useful ways of searching your source:
Search working tree for text matching regular expression regexp:
git grep <regexp>
Search working tree for lines of text matching regular expression regexp1 or regexp2:
git grep -e <regexp1> [--or] -e <regexp2>
Search working tree for lines of text matching regular expression regexp1 and regexp2, reporting file paths only:
git grep -l -e <regexp1> --and -e <regexp2>
Search working tree for files that have lines of text matching regular expression regexp1 and lines of text matching regular expression regexp2:
git grep -l --all-match -e <regexp1> -e <regexp2>
Search working tree for changed lines of text matching pattern:
git diff --unified=0 | grep <pattern>
Search all revisions for text matching regular expression regexp:
git grep <regexp> $(git rev-list --all)
Search all revisions between rev1 and rev2 for text matching regular expression regexp:
git grep <regexp> $(git rev-list <rev1>..<rev2>)
Combining the earlier suggestions to determine your personal permissions (ie 'USER' permissions), then use this:
-- your permissions
select * from USER_ROLE_PRIVS where USERNAME= USER;
select * from USER_TAB_PRIVS where Grantee = USER;
select * from USER_SYS_PRIVS where USERNAME = USER;
-- granted role permissions
select * from ROLE_ROLE_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_TAB_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
select * from ROLE_SYS_PRIVS where ROLE IN (select granted_role from USER_ROLE_PRIVS where USERNAME= USER);
Can you try this:
select convert(nvarchar(max),convert(varbinary(max),blob_column)) from table_name
This code example may do what you want:
If you get an OutOfMemoryError then it's usually too late to call the garbage collector...
Here is quote from Android Developer:
Most of the time, garbage collection occurs because of tons of small, short-lived objects and some garbage collectors, like generational garbage collectors, can optimize the collection of these objects so that the application does not get interrupted too often. The Android garbage collector is unfortunately not able to perform such optimizations and the creation of short-lived objects in performance critical code paths is thus very costly for your application.
So to my understanding, there is no urgent need to call the gc. It's better to spend more effort in avoiding the unnecessary creation of objects (like creation of objects inside loops)
If you decide to use Underscore.js you better do
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
keys.push(key);
});
console.log(keys);
I would suggest using the members of string, but with an explicit encoding:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset
instead. Using Guava I'd really use:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
Use this:
android:scrollbarAlwaysDrawHorizontalTrack="true"
Example:
<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawHorizontalTrack="true" />
Unlimited loop in one-line command for use in cmd
windows:
FOR /L %N IN () DO @echo Oops
I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.
I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.
I don't get the magic in your save() method either. How is the data saved?
In production I configure spring like this:
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />
along with the reference in web.xml
For unit testing I do this:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>
Some special characters give this type of error, so use
$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";
this code works great for me :
echo str_replace(array_keys($data), array_values($data), $query->queryString);
Don't forget to replace $data and $query by your names
Suppose I have committed changes to master branch.I will get the commit id(xyz) of the commit now i have to go to branch for which i need to push my commits.
Single commit id xyx
git checkout branch-name
git cherry-pick xyz
git push origin branch-name
Multiple commit id's xyz abc qwe
git checkout branch-name
git cherry-pick xyz abc qwe
git push origin branch-name
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
This type of question has been asked previously.
The type of sorting you are talking about is called "Natural Sorting". The data on which you want to do sort is alphanumeric. It would be better to create a new column for sorting.
For further help check natural-sort-in-mysql
Little addition in answer if you have different user rather then dbo
then do like this.
EXEC [ServerName].[DatabaseName].dbo.sp_HelpText '[user].[storedProcName]'
All these answers with .ReadAllBytes()
. Another, similar (I won't say duplicate, since they were trying to refactor their code) question was asked on SO here: Best way to read a large file into a byte array in C#?
A comment was made on one of the posts regarding .ReadAllBytes()
:
File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file
and it failed) – juanjo.arana Mar 13 '13 at 1:31
A better approach, to me, would be something like this, with BinaryReader
:
public static byte[] FileToByteArray(string fileName)
{
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName))
{
var binaryReader = new BinaryReader(fs);
fileData = binaryReader.ReadBytes((int)fs.Length);
}
return fileData;
}
But that's just me...
Of course, this all assumes you have the memory to handle the byte[]
once it is read in, and I didn't put in the File.Exists
check to ensure the file is there before proceeding, as you'd do that before calling this code.
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
if (listView1.Items.Count > 0)
{
listView1.FocusedItem = listView1.Items[0];
listView1.Items[0].Selected = true;
listView1.Select();
}
per the mysql documentation, the DATE() function will pull the date part of a datetime feild, and TIME() for the time portion. so I would try:
select DATE(dateTimeField) as Date, TIME(dateTimeField) as Time, col2, col3, FROM Table1 ...
If you have something like this:
$stuff = array();
$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');
$stuff[1] = array('story' => 'Foo');
You could simply count()
:
foreach ($stuff as $value) {
if (count($value) == 2) {
// story and message
} else {
// only story
}
}
This only works if you know for sure that you ONLY have these array keys, and nothing else.
Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:
foreach ($stuff as $value) {
if (array_key_exists('story', $value) && array_key_exists('message', $value) {
// story and message
} else {
// either one or both keys missing
}
}
array_key_exists()
returns true if the key is present in the array, but it is a real function and a lot to type. The language construct isset()
will almost do the same, except if the tested value is NULL:
foreach ($stuff as $value) {
if (isset($value['story']) && isset($value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Additionally isset allows to check multiple variables at once:
foreach ($stuff as $value) {
if (isset($value['story'], $value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Now, to optimize the test for stuff that is set, you'd better use this "if":
foreach ($stuff as $value) {
if (isset($value['story']) {
if (isset($value['message']) {
// story and message
} else {
// only story
}
} else {
// No story - but message not checked
}
}
JVM heap size can be growable and shrinkable by the Garbage-Collection mechanism. But, it can't allocate over maximum memory size: Runtime.maxMemory. This is the meaning of maximum memory. Total memory means the allocated heap size. And free memory means the available size in total memory.
example) java -Xms20M -Xmn10M -Xmx50M ~~~. This means that jvm should allocate heap 20M on start(ms). In this case, total memory is 20M. free memory is 20M-used size. If more heap is needed, JVM allocate more but can't over 50M(mx). In the case of maximum, total memory is 50M, and free size is 50M-used size. As for minumum size(mn), if heap is not used much, jvm can shrink heap size to 10M.
This mechanism is for efficiency of memory. If small java program run on huge fixed size heap memory, so much memory may be wasteful.
To anyone else looking for this, I wasn't able to use certutil -importpfx
into a specific store, and I didn't want to download the importpfx tool supplied by jaspernygaard's answer in order to avoid the requirement of copying the file to a large number of servers. I ended up finding my answer in a powershell script shown here.
The code uses System.Security.Cryptography.X509Certificates
to import the certificate and then moves it into the desired store:
function Import-PfxCertificate {
param([String]$certPath,[String]$certRootStore = “localmachine”,[String]$certStore = “My”,$pfxPass = $null)
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
if ($pfxPass -eq $null)
{
$pfxPass = read-host "Password" -assecurestring
}
$pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet")
$store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
}
You can use the following class to pinpoint transitivity bugs in your Comparators:
/**
* @author Gili Tzabari
*/
public final class Comparators
{
/**
* Verify that a comparator is transitive.
*
* @param <T> the type being compared
* @param comparator the comparator to test
* @param elements the elements to test against
* @throws AssertionError if the comparator is not transitive
*/
public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements)
{
for (T first: elements)
{
for (T second: elements)
{
int result1 = comparator.compare(first, second);
int result2 = comparator.compare(second, first);
if (result1 != -result2)
{
// Uncomment the following line to step through the failed case
//comparator.compare(first, second);
throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 +
" but swapping the parameters returns " + result2);
}
}
}
for (T first: elements)
{
for (T second: elements)
{
int firstGreaterThanSecond = comparator.compare(first, second);
if (firstGreaterThanSecond <= 0)
continue;
for (T third: elements)
{
int secondGreaterThanThird = comparator.compare(second, third);
if (secondGreaterThanThird <= 0)
continue;
int firstGreaterThanThird = comparator.compare(first, third);
if (firstGreaterThanThird <= 0)
{
// Uncomment the following line to step through the failed case
//comparator.compare(first, third);
throw new AssertionError("compare(" + first + ", " + second + ") > 0, " +
"compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " +
firstGreaterThanThird);
}
}
}
}
}
/**
* Prevent construction.
*/
private Comparators()
{
}
}
Simply invoke Comparators.verifyTransitivity(myComparator, myCollection)
in front of the code that fails.
Even when i was learning node.js for the first time where i started learning it over web-app, i was having all these things done in well manner in my form, still i was not able to receive values in post request. After long debugging, i came to know that in the form i have provided enctype="multipart/form-data"
due to which i was not able to get values. I simply removed it and it worked for me.
I had problems installing the 64-bit version of MySQLdb on Windows via Pip (problem compiling sources) [32bit version installed ok]. Managed to install the compiled MySQLdb from the .whl file available from http://www.lfd.uci.edu/~gohlke/pythonlibs/
The .whl file can then be installed via pip as document in https://pip.pypa.io/en/latest/user_guide/#installing-from-wheels
For example if you save in C:/
the you can install via
pip install c:/MySQL_python-1.2.5-cp27-none-win_amd64.whl
Follow-up: if you have a 64bit version of Python installed, then you want to install the 64-bit AMD version of MySQLdb from the link above [i.e. even if you have a Intel processor]. If you instead try and install the 32-bit version, I think you get the unsupported wheel error in comments below.
Hate to add yet another answer, but my particular scenario isn't quite covered here. I had a local repo with a history of changes I wanted to preserve, and a non-empty repo created for me on Github (that is, with the default README.md). Yes, you can always re-create the Github repo as an empty repo, but in my case someone else has the permissions to create this particular repo, and I didn't want to trouble him, if there was an easy workaround.
In this scenario, you will encounter this error when you attempt to git push
after setting the remote origin:
! [rejected] master -> master (fetch first)
error: failed to push some refs to '[email protected]:<my repo>.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
As the error indicates, I needed to do a git pull
after setting the remote origin, but I needed to specify the --allow-unrelated-histories
option. Without this option, git pull
complains warning: no common commits
.
So here is the exact sequence of commands that worked for me:
git remote add origin <github repo url>
cp README.md README.md-save
git pull origin master --allow-unrelated-histories
mv README.md-save README.md
git commit -a
git push
Make sure Anonymous access is enabled on IIS -> Authentication.
But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).
Your use case would be :
$ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
return $user->getActive() === TRUE;
});
if you add ->first() you'll get only the first entry returned, which is not what you want.
@ Sjwdavies You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:
$member->getComments()->filter( function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
});
After reading many articles I decided to put all the attributes information together:
- atomic //default
- nonatomic
- strong=retain //default
- weak= unsafe_unretained
- retain
- assign //default
- unsafe_unretained
- copy
- readonly
- readwrite //default
Below is a link to the detailed article where you can find these attributes.
Many thanks to all the people who give best answers here!!
Here is the Sample Description from Article
Example :
@property (retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Explain:
Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Strong & Weak Explanation, Thanks to BJ Homer:
Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
unsafe_unretained
-unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.
Example:
@property (nonatomic, unsafe_unretained) NSString *nickName;
@synthesize nickName;
Example:
@property (nonatomic, copy) NSArray *myArray;
@synthesize myArray;
According to this post, you should enable it in XCode.
public Date addMonths(String dateAsString, int nbMonths) throws ParseException {
String format = "MM/dd/yyyy" ;
SimpleDateFormat sdf = new SimpleDateFormat(format) ;
Date dateAsObj = sdf.parse(dateAsString) ;
Calendar cal = Calendar.getInstance();
cal.setTime(dateAsObj);
cal.add(Calendar.MONTH, nbMonths);
Date dateAsObjAfterAMonth = cal.getTime() ;
System.out.println(sdf.format(dateAsObjAfterAMonth));
return dateAsObjAfterAMonth ;
}`
stat() works on Linux., UNIX and Windows as well:
#include <sys/types.h>
#include <sys/stat.h>
struct stat info;
if( stat( pathname, &info ) != 0 )
printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR ) // S_ISDIR() doesn't exist on my windows
printf( "%s is a directory\n", pathname );
else
printf( "%s is no directory\n", pathname );
If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]"
does the matching, result will be in $Matches[0]
Here is another way to reproduce this error in Python2.7 with numpy:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b) #note the lack of tuple format for a and b
print(c)
The np.concatenate
method produces an error:
TypeError: only length-1 arrays can be converted to Python scalars
If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b)) #surround a and b with parens, packaging them as a tuple
print(c)
Then it prints:
[1 2 3 4 5 6]
What's going on here?
That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".
In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.
When you declare a reference variable (i.e., an object), you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int
:
int x;
x = 10;
In this example, the variable x
is an int
and Java will initialize it to 0
for you. When you assign the value of 10
on the second line, your value of 10
is written into the memory location referred to by x
.
But, when you try to declare a reference type, something different happens. Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num
, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is Integer
which is a reference type). Since you have not yet said what to point to, Java sets it to null
, which means "I am pointing to nothing".
In the second line, the new
keyword is used to instantiate (or create) an object of type Integer
, and the pointer variable num
is assigned to that Integer
object.
The NullPointerException
(NPE) occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable (called dereferencing). So you are pointing to something that does not actually exist.
Dereferencing usually happens when using .
to access a method or field, or using [
to index an array.
If you attempt to dereference num
before creating the object you get a NullPointerException
. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized
," but sometimes you may write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}
In which case, you are not creating the object obj
, but rather assuming that it was created before the doSomething()
method was called. Note, it is possible to call the method like this:
doSomething(null);
In which case, obj
is null
, and the statement obj.myMethod()
will throw a NullPointerException
.
If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException
because it's a programmer error and the programmer will need that information for debugging purposes.
In addition to NullPointerException
s thrown as a result of the method's logic, you can also check the method arguments for null
values and throw NPEs explicitly by adding something like the following near the beginning of a method:
// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");
Note that it's helpful to say in your error message clearly which object cannot be null
. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj
is reassigned, it is not null and can be dereferenced safely.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething()
could be written as:
/**
* @param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically
Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006. The following is 2 minutes read to understand this amazing language feature.
https://jfeatures.com/blog/NullPointerException
In Java 14, the following is a sample NullPointerException Exception message:
in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null
I found this piece of information and got it to work correctly. The data given to me was in string format so I needed to parse the string using kendo.parseDate
before formatting it with kendo.toString
.
columns: [
{
field: "FirstName",
title: "FIRST NAME"
},
{
field: "LastName",
title: "LAST NAME"
},
{
field: "DateOfBirth",
title: "DATE OF BIRTH",
template: "#= kendo.toString(kendo.parseDate(DateOfBirth, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
},
...
The problem is not with extract
, which can certainly handle 'military time'. It looks like you have a default timestamp format which has HH
instead of HH24
; or at least that's the only way I can see to recreate this:
SQL> select value from nls_session_parameters
2 where parameter = 'NLS_TIMESTAMP_FORMAT';
VALUE
--------------------------------------------------------------------------------
DD-MON-RR HH24.MI.SSXFF
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
alter session set nls_timestamp_format = 'DD-MON-YYYY HH:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') as timestamp)) from dual
*
ERROR at line 1:
ORA-01849: hour must be between 1 and 12
So the simple 'fix' is to set the format to something that does recognise 24-hours:
SQL> alter session set nls_timestamp_format = 'DD-MON-YYYY HH24:MI:SS';
Session altered.
SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
2 as timestamp)) from dual;
EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
15
Although you don't need the to_char
at all:
SQL> select extract(hour from cast(sysdate as timestamp)) from dual;
EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
-----------------------------------------
15
This will give you the second row of each group (zero indexed, nth(0) is the same as first()):
df.groupby('id').nth(1)
Documentation: http://pandas.pydata.org/pandas-docs/stable/groupby.html#taking-the-nth-row-of-each-group
From the standard (p. ii):
It is expected that other standards will refer to this one, strictly adhering to the JSON text format, while imposing restrictions on various encoding details. Such standards may require specific behaviours. JSON itself specifies no behaviour.
Further down in the standard (p. 2), the specification for a JSON object:
An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs. A name is a string. A single colon token follows each name, separating the name from the value. A single comma token separates a value from a following name.
It does not make any mention of duplicate keys being invalid or valid, so according to the specification I would safely assume that means they are allowed.
That most implementations of JSON libraries do not accept duplicate keys does not conflict with the standard, because of the first quote.
Here are two examples related to the C++ standard library. When deserializing some JSON object into a std::map
it would make sense to refuse duplicate keys. But when deserializing some JSON object into a std::multimap
it would make sense to accept duplicate keys as normal.
I know this is old. But yeah. I prefer much shorter solution, than Giona answer
[contenteditable] {
border-bottom: 1px solid transparent;
&:focus {outline: none; border-bottom: 1px dashed #000;}
}
Just to clarify, be aware bracket placement is important!
These can be added to any HTML tags... span, div, table, p, tr, td etc.
AngularJS
ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
Angular2+
*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.
boolean check1 = Your conditional check here...
...
Annotating with @JsonAlias
which got introduced with Jackson 2.9+, without mentioning @JsonProperty
on the item to be deserialized with more than one alias(different names for a json property) works fine.
I used com.fasterxml.jackson.annotation.JsonAlias
for package consistency with com.fasterxml.jackson.databind.ObjectMapper
for my use-case.
For e.g.:
@Data
@Builder
public class Chair {
@JsonAlias({"woodenChair", "steelChair"})
private String entityType;
}
@Test
public void test1() {
String str1 = "{\"woodenChair\":\"chair made of wood\"}";
System.out.println( mapper.readValue(str1, Chair.class));
String str2 = "{\"steelChair\":\"chair made of steel\"}";
System.out.println( mapper.readValue(str2, Chair.class));
}
just works fine.
Beside of read.csv(url("..."))
you also can use read.table("http://...")
.
Example:
> sample <- read.table("http://www.ats.ucla.edu/stat/examples/ara/angell.txt")
> sample
V1 V2 V3 V4 V5
1 Rochester 19.0 20.6 15.0 E
2 Syracuse 17.0 15.6 20.2 E
...
43 Atlanta 4.2 70.6 32.6 S
>
This is useful when textfield superview is view
class AdminLoginViewController: UIViewController,
UITextFieldDelegate{
@IBOutlet weak var txtUserName: UITextField!
@IBOutlet weak var txtUserPassword: UITextField!
@IBOutlet weak var btnAdminLogin: UIButton!
private var activeField : UIView?
var param:String!
var adminUser : Admin? = nil
var kbHeight: CGFloat!
override func viewDidLoad()
{
self.addKeyBoardObserver()
self.addGestureForHideKeyBoard()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addGestureForHideKeyBoard()
{
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("hideKeyboard"))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
}
func hideKeyboard() {
self.view.endEditing(true)
}
func addKeyBoardObserver(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeKeyboardFrame:",
name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeKeyboardFrame:",
name:UIKeyboardWillHideNotification, object: nil)
}
func removeObserver(){
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//MARK:- textfiled Delegate
func textFieldShouldBeginEditing(textField: UITextField) -> Bool
{
activeField = textField
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool
{
if activeField == textField
{
activeField = nil
}
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if txtUserName == textField
{
txtUserPassword.becomeFirstResponder()
}
else if (textField == txtUserPassword)
{
self.btnAdminLoginAction(nil)
}
return true;
}
func willChangeKeyboardFrame(aNotification : NSNotification)
{
if self.activeField != nil && self.activeField!.isFirstResponder()
{
if let keyboardSize = (aNotification.userInfo![UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
{
let dy = (self.activeField?.superview?.convertRect((self.activeField?.frame)!, toView: view).origin.y)!
let height = (self.view.frame.size.height - keyboardSize.size.height)
if dy > height
{
var frame = self.view.frame
frame.origin.y = -((dy - height) + (self.activeField?.frame.size.height)! + 20)
self.view.frame = frame
}
}
}
else
{
var frame = self.view.frame
frame.origin.y = 0
self.view.frame = frame
}
} }
I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->
return .Cell(i,1) <> Empty
JoshAdel's solution uses np.newaxis to add a dimension. An alternative is to use reshape() to align the dimensions in preparation for broadcasting.
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
vector = np.array([1,2,3])
data
# array([[1, 1, 1],
# [2, 2, 2],
# [3, 3, 3]])
vector
# array([1, 2, 3])
data.shape
# (3, 3)
vector.shape
# (3,)
data / vector.reshape((3,1))
# array([[1, 1, 1],
# [1, 1, 1],
# [1, 1, 1]])
Performing the reshape() allows the dimensions to line up for broadcasting:
data: 3 x 3
vector: 3
vector reshaped: 3 x 1
Note that data/vector
is ok, but it doesn't get you the answer that you want. It divides each column of array
(instead of each row) by each corresponding element of vector
. It's what you would get if you explicitly reshaped vector
to be 1x3
instead of 3x1
.
data / vector
# array([[1, 0, 0],
# [2, 1, 0],
# [3, 1, 1]])
data / vector.reshape((1,3))
# array([[1, 0, 0],
# [2, 1, 0],
# [3, 1, 1]])
My issue was similar to Q---ten's, but in my case it was that I had forgotten to provide the self argument to a class function:
class A:
def fn(a, b, c=True):
pass
Should become
class A:
def fn(self, a, b, c=True):
pass
This faulty implementation is hard to see when calling the class method as:
a_obj = A()
a.fn(a_val, b_val, c=False)
Which will yield a TypeError: got multiple values for argument
. Hopefully, the rest of the answers here are clear enough for anyone to be able to quickly understand and fix the error. If not, hope this answer helps you!
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
1st download jquery.form.js file from below url
http://plugins.jquery.com/form/
Write below code in cshtml
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" }))
{
<div id="uploadTemplate">
<input type="text" value="Asif" id="txtname" name="txtName" />
<div id="dvAddTemplate">
Add Template
<br />
<input type="file" name="file" id="file" tabindex="2" />
<br />
<input type="submit" value="Submit" />
<input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" />
</div>
<div id="TemplateTree" style="overflow-x: auto;"></div>
</div>
<div id="progressBarDiv" style="display: none;">
<img id="loading-image" src="~/Images/progress-loader.gif" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
debugger;
alert('sample');
var status = $('#status');
$('#frmTemplateUpload').ajaxForm({
beforeSend: function () {
if ($("#file").val() != "") {
//$("#uploadTemplate").hide();
$("#btnAction").hide();
$("#progressBarDiv").show();
//progress_run_id = setInterval(progress, 300);
}
status.empty();
},
success: function () {
showTemplateManager();
},
complete: function (xhr) {
if ($("#file").val() != "") {
var millisecondsToWait = 500;
setTimeout(function () {
//clearInterval(progress_run_id);
$("#uploadTemplate").show();
$("#btnAction").show();
$("#progressBarDiv").hide();
}, millisecondsToWait);
}
status.html(xhr.responseText);
}
});
});
</script>
Action method :-
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public void Upload(HttpPostedFileBase file, string txtname )
{
try
{
string attachmentFilePath = file.FileName;
string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1);
}
catch (Exception ex)
{
}
}
In my case, setting httpErrors
and the like in Web.config did not help to identify the issue.
Instead I did:
I then saw an entry with a detailed exception information. In my case it was
\?\C:\Websites\example.com\www\web.config ( 592) :Cannot add duplicate collection entry of type 'mimeMap' with unique key attribute 'fileExtension' set to '.json'
I now was able to resolve it and fix the error. After that I deactivated "Failed Request Tracing" again.