I had this issue because of VS Code Insiders. The path variable was there but I needed to rename the code-insiders.cmd inside to code.cmd .
Maybe this is useful to someone.
A Build Lifecycle is Made Up of Phases
Each of these build lifecycles is defined by a different list of build phases, wherein a build phase represents a stage in the lifecycle.
For example, the default lifecycle comprises of the following phases (for a complete list of the lifecycle phases, refer to the Lifecycle Reference):
These lifecycle phases (plus the other lifecycle phases not shown here) are executed sequentially to complete the default lifecycle. Given the lifecycle phases above, this means that when the default lifecycle is used, Maven will first validate the project, then will try to compile the sources, run those against the tests, package the binaries (e.g. jar), run integration tests against that package, verify the integration tests, install the verified package to the local repository, then deploy the installed package to a remote repository.
Source: https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
GIFs store colors as one of x number of possible colors in a palette. Read about the gif limited color palette. So PIL is giving you the palette index, rather than the color information of that palette color.
Edit: Removed link to a blog post solution that had a typo. Other answers do the same thing without the typo.
I had the same issue, so tried a few things. One of which seemed to work for me - removing the width and adding a float to the body tag.
May not work for all instances, but in the scenario I recently had, hiding overflow on content elements was a no go...
The above solutions work if you are compressing all white space in the XML document. Other quick options are JDOM (using Format.getCompactFormat()) and dom4j (using OutputFormat.createCompactFormat()) when outputting the XML document.
However, I had a unique requirement to preserve the white space contained within the element's text value and these solutions did not work as I needed. All I needed was to remove the 'pretty-print' formatting added to the XML document.
The solution that I came up with can be explained in the following 3-step/regex process ... for the sake of understanding the algorithm for the solution.
String regex, updatedXml;
// 1. remove all white space preceding a begin element tag:
regex = "[\\n\\s]+(\\<[^/])";
updatedXml = originalXmlStr.replaceAll( regex, "$1" );
// 2. remove all white space following an end element tag:
regex = "(\\</[a-zA-Z0-9-_\\.:]+\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
// 3. remove all white space following an empty element tag
// (<some-element xmlns:attr1="some-value".... />):
regex = "(/\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
NOTE: The pseudo-code is in Java ... the '$1' is the replacement string which is the 1st capture group.
This will simply remove the white space used when adding the 'pretty-print' format to an XML document, yet preserve all other white space when it is part of the element text value.
A simple bash one liner. I used this to remove rst extension from all files in pwd
for each in `ls -1 *.rst`
do
a=$(echo $each | wc -c)
echo $each | cut -c -$(( $a-5 )) >> blognames
done
What it does ?
1) ls -1 *.rst
will list all the files on stdout in new line (try).
2) echo $each | wc -c
counts the number of characters in each filename .
3) echo $each | cut -c -$(( $a-5 ))
selects up to last 4 characters, i.e, .rst
.
Use the Out-File
cmdlet
Compare-Object ... | Out-File C:\filename.txt
Optionally, add -Encoding utf8
to Out-File
as the default encoding is not really ideal for many uses.
Update 1: There is a CSS3 spec for CSS level 3 nesting. It's currently a draft. https://tabatkins.github.io/specs/css-nesting/
Update 2 (2019): We now have a CSSWG draft https://drafts.csswg.org/css-nesting-1/
If approved, the syntax would look like this:
table.colortable {
& td {
text-align:center;
&.c { text-transform:uppercase }
&:first-child, &:first-child + td { border:1px solid black }
}
& th {
text-align:center;
background:black;
color:white;
}
}
.foo {
color: red;
@nest & > .bar {
color: blue;
}
}
.foo {
color: red;
@nest .parent & {
color: blue;
}
}
Status: The original 2015 spec proposal was not approved by the Working Group.
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
Reflection is pretty "heavy"
Perhaps try this solution:
C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing)) 'possible function
End If
Next
End If
Reflection slows down +/- 1000 x the speed of a method call, shown in The Performance of Everyday Things
Also if your working directory is different than you can use lpDirectory
procInfo = ShellExecuteEx(nShow=showCmd,
lpVerb=lpVerb,
lpFile=cmd,
lpDirectory= unicode(direc),
lpParameters=params)
Will come handy if changing the path is not a desirable option remove unicode for python 3.X
Page 2 is in a new tab/window ? If it's this, use the code bellow :
try {
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
String act = driver.getCurrentUrl();
}
}catch(Exception e){
System.out.println("fail");
}
Hitting F11 may work for you.(Full-screen mode)
It appears that the hiding the address bar without going full screen is no longer an option:http://productforums.google.com/forum/#!topic/chrome/d7LfleRNX7M
In case of array like
result = [ '2015', '2014', '2013', '2011' ],
it gets tricky if you are using escape sequence like:
result = [ \'2015\', \'2014\', \'2013\', \'2011\' ].
Instead, good way to do it is to wrap the array with single quotes as follows:
result = "'"+result+"'";
I think this is the easiest way to do this:
class MyController extends Controller
{
public function myAction($_route)
{
var_dump($_route);
}
.....
We should first read the documentation on proxy_pass carefully and fully.
The URI passed to upstream server is determined based on whether "proxy_pass" directive is used with URI or not. Trailing slash in proxy_pass directive means that URI is present and equal to /
. Absense of trailing slash means hat URI is absent.
Proxy_pass with URI:
location /some_dir/ {
proxy_pass http://some_server/;
}
With the above, there's the following proxy:
http:// your_server/some_dir/ some_subdir/some_file ->
http:// some_server/ some_subdir/some_file
Basically, /some_dir/
gets replaced by /
to change the request path from /some_dir/some_subdir/some_file
to /some_subdir/some_file
.
Proxy_pass without URI:
location /some_dir/ {
proxy_pass http://some_server;
}
With the second (no trailing slash): the proxy goes like this:
http:// your_server /some_dir/some_subdir/some_file ->
http:// some_server /some_dir/some_subdir/some_file
Basically, the full original request path gets passed on without changes.
So, in your case, it seems you should just drop the trailing slash to get what you want.
Caveat
Note that automatic rewrite only works if you don't use variables in proxy_pass. If you use variables, you should do rewrite yourself:
location /some_dir/ {
rewrite /some_dir/(.*) /$1 break;
proxy_pass $upstream_server;
}
There are other cases where rewrite wouldn't work, that's why reading documentation is a must.
Reading your question again, it seems I may have missed that you just want to edit the html output.
For that, you can use the sub_filter directive. Something like ...
location /admin/ {
proxy_pass http://localhost:8080/;
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
Basically, the string you want to replace and the replacement string
If you are using C++ 17 you can just use the inline
specifier (see https://stackoverflow.com/a/11711082/55721)
If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y
unsigned char test::X;
unsigned char test::Y;
somewhere. You might want to also initialize a static member
unsigned char test::X = 4;
and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)
This Twilio blog page made on March 24, 2017 by Marcos Placona may be helpful.
Google Spreadsheets and .NET Core
It references Google.Api.Sheets.v4 and OAuth2.
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return stackoverflow.com if called from this page
Here's the complete breakdown
Yes. You can use reflection. Something like this:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
Following solutions will first read the whole content to memory before writing it to disc (for more i/o efficient solutions look at the other answers).
You can use open-uri, which is a one liner
require 'open-uri'
content = open('http://example.com').read
Or by using net/http
require 'net/http'
File.write("file_name", Net::HTTP.get(URI.parse("http://url.com")))
Normally set does not keep the order, such as HashSet in order to quickly find a emelent, but you can try LinkedHashSet it will keep the order which you put in.
Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
Check the column collation. This script might change the collation to the table default. Add the current collation to the script.
You should use LoadXml method, not Load:
xmlDoc.LoadXml(myXML);
Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
}
Another gotcha I recently came across is that in IE 8, "abcd".substr(-1)
erroneously returns "abcd"
, whereas Firefox 3.6 returns "d"
as it should. slice
works correctly on both.
More on this topic can be found here.
What is the len
of the equivalent nested list?
len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])
With the more general concept of shape
, numpy
developers choose to implement __len__
as the first dimension. Python maps len(obj)
onto obj.__len__
.
X.shape
returns a tuple, which does have a len
- which is the number of dimensions, X.ndim
. X.shape[i]
selects the ith
dimension (a straight forward application of tuple indexing).
simple to use.
1.Install
2.press ctrl + alt + f (default)
Thats it.
You have to use (without @)
npm uninstall -g angular/cli
because
If you're using Angular CLI beta.28 or less, you need to uninstall angular-cli package. It should be done due to changing of package's name and scope from angular-cli to @angular/cli https://github.com/angular/angular-cli
This worked for me:
import re
text = 'how are u? umberella u! u. U. U@ U# u '
rex = re.compile(r'\bu\b', re.IGNORECASE)
print(rex.sub('you', text))
It pre-compiles the regular expression and makes use of re.IGNORECASE so that we don't have to worry about case in our regular expression! BTW, I love the funky spelling of umbrella! :-)
That's not the behavior I'm seeing:
irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]
Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?
It is the severity level of the error
. The levels are from 11 - 20 which throw an error in SQL
. The higher the level, the more severe the level and the transaction
should be aborted.
You will get the syntax error when you do:
RAISERROR('Cannot Insert where salary > 1000').
Because you have not specified the correct parameters
(severity level
or state
).
If you wish to issue a warning and not an exception
, use levels 0 - 10.
From MSDN:
severity
Is the user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage. Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required.
state
Is an integer from 0 through 255. Negative values or values larger than 255 generate an error. If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors. For detailed description here
The default port 1433 is used when there is only one SQL Server named instance running on the computer.
When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.
The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:
The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?
This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.
In other words, the feature is missing to remove the temptation to use the feature insecurely.
The high spike that you have is due to the DC (non-varying, i.e. freq = 0) portion of your signal. It's an issue of scale. If you want to see non-DC frequency content, for visualization, you may need to plot from the offset 1 not from offset 0 of the FFT of the signal.
Modifying the example given above by @PaulH
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = 10 + np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
plt.subplot(2, 1, 1)
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
plt.subplot(2, 1, 2)
plt.plot(xf[1:], 2.0/N * np.abs(yf[0:N/2])[1:])
The output plots:
Another way, is to visualize the data in log scale:
Using:
plt.semilogy(xf, 2.0/N * np.abs(yf[0:N/2]))
Will show:
Mederr's context transform works perfectly. If you need to extract orientation only use this function - you don't need any EXIF-reading libs. Below is a function for re-setting orientation in base64 image. Here's a fiddle for it. I've also prepared a fiddle with orientation extraction demo.
function resetOrientation(srcBase64, srcOrientation, callback) {
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
case 7: ctx.transform(0, -1, -1, 0, height, width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: break;
}
// draw image
ctx.drawImage(img, 0, 0);
// export base64
callback(canvas.toDataURL());
};
img.src = srcBase64;
};
We can solve this problem in 3 different ways.
1) Using php.ini file
2) Using .htaccess file
3) Using Wp-config.php file ( for Wordpress )
Its better to go through the Recommended Microsoft's Way to download Visual Studio 2015 Update 3 ISO (Community Edition).
The instructions below will help you to download any version of Visual Studio or even SQL Server etc provided by Microsoft in an easy to remember way. Though I recommend people using VS 2017 as there are not much big differences between 2015 and 2017.
Please follow the steps as mentioned below.
Visit the standard URL www.visualstudio.com/downloads
Scroll down and click on encircled below as shown in snapshot down
After that join Visual Studio Web Dev essentials for Free as shown below. Try loggin in with your microsoft account and see that if it works otherwise click on Join
In Firefox, SpiderMonkey and Rhino you can wrap any code into an anonymous function and call its toSource
method, which will give you a nicely formatted source of the function.
toSource
also strips comments.
E. g.:
(function () { /* Say hello. */ var x = 'Hello!'; print(x); }).toSource()
Will be converted to a string:
function () {
var x = "Hello!";
print(x);
}
P. S.: It's not an "online tool", but all questions about general beautifying techniques are closed as duplicates of this one.
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
In case when the enum members have different values, you can apply something like this:
public static MyGender? MapToMyGender(this Gender gender)
{
return gender switch
{
Gender.Male => MyGender.Male,
Gender.Female => MyGender.Female,
Gender.Unknown => null,
_ => throw new InvalidEnumArgumentException($"Invalid gender: {gender}")
};
}
Then you can call: var myGender = gender.MapToMyGender();
Update: This previous code works only with C# 8. For older versions of C#, you can use the switch statement instead of the switch expression:
public static MyGender? MapToMyGender(this Gender gender)
{
switch (gender)
{
case Gender.Male:
return MyGender.Male;
case Gender.Female:
return MyGender.Female;
case Gender.Unknown:
return null;
default:
throw new InvalidEnumArgumentException($"Invalid gender: {gender}")
};
}
encodeURI
and encodeURIComponent
:encodeURIComponent(value)
is mainly used to encode queryString parameter values, and it encodes every applicable character in value
. encodeURI
ignores protocol prefix (http://
) and domain name.
In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! *
, then
you might use:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
(source)
This is pure JavaScript, based on the answer by @Fontas but with safety code to return an empty string (and avoid a TypeError
) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
<input>
type, (b) has a name
attribute of genderS
, and (c) is checked.genderSRadio
variable is truthy if Line 1 finds the control and null/falsey if it doesn't.For JQuery, use @jbabey's answer, and note that if there isn't a selected radio button it will return undefined
.
If your build path is correct, the ctrl + click will work
I found this in the Cheetah source code (here)
htmlCodes = [
['&', '&'],
['<', '<'],
['>', '>'],
['"', '"'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
""" Returns the ASCII decoded version of the given HTML string. This does
NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
for code in codes:
s = s.replace(code[1], code[0])
return s
not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)
i noticed your title asked for encode too, so here is Cheetah's encode function.
def htmlEncode(s, codes=htmlCodes):
""" Returns the HTML encoded version of the given string. This is useful to
display a plain ASCII text string on a web page."""
for code in codes:
s = s.replace(code[0], code[1])
return s
There is a npm sync module also. which is used for synchronize the process of executing the query.
When you want to run parallel queries in synchronous way then node restrict to do that because it never wait for response. and sync module is much perfect for that kind of solution.
Sample code
/*require sync module*/
var Sync = require('sync');
app.get('/',function(req,res,next){
story.find().exec(function(err,data){
var sync_function_data = find_user.sync(null, {name: "sanjeev"});
res.send({story:data,user:sync_function_data});
});
});
/*****sync function defined here *******/
function find_user(req_json, callback) {
process.nextTick(function () {
users.find(req_json,function (err,data)
{
if (!err) {
callback(null, data);
} else {
callback(null, err);
}
});
});
}
reference link: https://www.npmjs.com/package/sync
The following helped me in Win10.
%M3_HOME%\bin;
as value for Path variable under User Variables.M3_HOME
variable under System Variables.%M3_HOME%\bin;
as value for Path variable under System Variables.mvn -version
It will work.
After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']);
. Or you can just return the array return array('success' => 'hi, atiq');
which will be rendered as json in Laravel version 5.2 .
Here i post some quick solution function with intent handling
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
<script>
window.location.hash = "no-back-button";
// Again because Google Chrome doesn't insert
// the first hash into the history
window.location.hash = "Again-No-back-button";
window.onhashchange = function(){
window.location.hash = "no-back-button";
}
</script>
This naming convention is lifted from Scheme.
1.3.5 Naming conventions
By convention, the names of procedures that always return a boolean value usually end in ``?''. Such procedures are called predicates.
By convention, the names of procedures that store values into previously allocated locations (see section 3.4) usually end in ``!''. Such procedures are called mutation procedures. By convention, the value returned by a mutation procedure is unspecified.
Update ListView's contents by below code:
private ListView listViewBuddy;
private BuddyAdapter mBuddyAdapter;
private ArrayList<BuddyModel> buddyList = new ArrayList<BuddyModel>();
onCreate():
listViewBuddy = (ListView)findViewById(R.id.listViewBuddy);
mBuddyAdapter = new BuddyAdapter();
listViewBuddy.setAdapter(mBuddyAdapter);
onDataGet (After webservice call or from local database or otherelse):
mBuddyAdapter.setData(buddyList);
mBuddyAdapter.notifyDataSetChanged();
BaseAdapter:
private class BuddyAdapter extends BaseAdapter {
private ArrayList<BuddyModel> mArrayList = new ArrayList<BuddyModel>();
private LayoutInflater mLayoutInflater= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private ViewHolder holder;
public void setData(ArrayList<BuddyModel> list){
mArrayList = list;
}
@Override
public int getCount() {
return mArrayList.size();
}
@Override
public BuddyModel getItem(int position) {
return mArrayList.get(position);
}
@Override
public long getItemId(int pos) {
return pos;
}
private class ViewHolder {
private TextView txtBuddyName, txtBuddyBadge;
}
@SuppressLint("InflateParams")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.row_buddy, null);
// bind views
holder.txtBuddyName = (TextView) convertView.findViewById(R.id.txtBuddyName);
holder.txtBuddyBadge = (TextView) convertView.findViewById(R.id.txtBuddyBadge);
// set tag
convertView.setTag(holder);
} else {
// get tag
holder = (ViewHolder) convertView.getTag();
}
holder.txtBuddyName.setText(mArrayList.get(position).getFriendId());
int badge = mArrayList.get(position).getCount();
if(badge!=0){
holder.txtBuddyBadge.setVisibility(View.VISIBLE);
holder.txtBuddyBadge.setText(""+badge);
}else{
holder.txtBuddyBadge.setVisibility(View.GONE);
}
return convertView;
}
}
Whenever you want to Update Listview just call below two lines code:
mBuddyAdapter.setData(Your_Updated_ArrayList);
mBuddyAdapter.notifyDataSetChanged();
Done
In short:
static_cast<>()
gives you a compile time checking ability, C-Style
cast doesn't.static_cast<>()
is more readable and can be spotted easily
anywhere inside a C++ source code, C_Style cast is'nt.More Explanation:
The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer ( a pointer to 4-byte datatype) pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
You can also check this page on more explanation on C++ casts : Click Here
To avoid saying everything Mark Ingram already said a little tip for using namespaces:
Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.
I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.
Sometimes namespaces are used in bigger C++ projects to hide implementation details.
Additional note to the using directive: Some people prefer using "using" just for single elements:
using std::cout;
using std::endl;
Better make the google object convert as a javascript readable object first.
Create two functions like below and call it passing google map return object.
function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}
Then user can access names like below.
var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka
All address parts are like below.
administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"
Here's code for Python 3.x:
print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!', end='\r')
The end=
keyword is what does the work here -- by default, print()
ends in a newline (\n
) character, but this can be replaced with a different string. In this case, ending the line with a carriage return instead returns the cursor to the start of the current line. Thus, there's no need to import the sys
module for this sort of simple usage. print()
actually has a number of keyword arguments which can be used to greatly simplify code.
To use the same code on Python 2.6+, put the following line at the top of the file:
from __future__ import print_function
A git rebase workflow does not protect you from people who are bad at conflict resolution or people who are used to a SVN workflow, like suggested in Avoiding Git Disasters: A Gory Story. It only makes conflict resolution more tedious for them and makes it harder to recover from bad conflict resolution. Instead, use diff3 so that it's not so difficult in the first place.
I am very pro-rebase for cleaning up history. However if I ever hit a conflict, I immediately abort the rebase and do a merge instead! It really kills me that people are recommending a rebase workflow as a better alternative to a merge workflow for conflict resolution (which is exactly what this question was about).
If it goes "all to hell" during a merge, it will go "all to hell" during a rebase, and potentially a lot more hell too! Here's why:
When you rebase instead of merge, you will have to perform conflict resolution up to as many times as you have commits to rebase, for the same conflict!
I branch off of master to refactor a complicated method in a branch. My refactoring work is comprised of 15 commits total as I work to refactor it and get code reviews. Part of my refactoring involves fixing the mixed tabs and spaces that were present in master before. This is necessary, but unfortunately it will conflict with any change made afterward to this method in master. Sure enough, while I'm working on this method, someone makes a simple, legitimate change to the same method in the master branch that should be merged in with my changes.
When it's time to merge my branch back with master, I have two options:
git merge: I get a conflict. I see the change they made to master and merge it in with (the final product of) my branch. Done.
git rebase: I get a conflict with my first commit. I resolve the conflict and continue the rebase. I get a conflict with my second commit. I resolve the conflict and continue the rebase. I get a conflict with my third commit. I resolve the conflict and continue the rebase. I get a conflict with my fourth commit. I resolve the conflict and continue the rebase. I get a conflict with my fifth commit. I resolve the conflict and continue the rebase. I get a conflict with my sixth commit. I resolve the conflict and continue the rebase. I get a conflict with my seventh commit. I resolve the conflict and continue the rebase. I get a conflict with my eighth commit. I resolve the conflict and continue the rebase. I get a conflict with my ninth commit. I resolve the conflict and continue the rebase. I get a conflict with my tenth commit. I resolve the conflict and continue the rebase. I get a conflict with my eleventh commit. I resolve the conflict and continue the rebase. I get a conflict with my twelfth commit. I resolve the conflict and continue the rebase. I get a conflict with my thirteenth commit. I resolve the conflict and continue the rebase. I get a conflict with my fourteenth commit. I resolve the conflict and continue the rebase. I get a conflict with my fifteenth commit. I resolve the conflict and continue the rebase.
You have got to be kidding me if this is your preferred workflow. All it takes is a whitespace fix that conflicts with one change made on master, and every commit will conflict and must be resolved. And this is a simple scenario with only a whitespace conflict. Heaven forbid you have a real conflict involving major code changes across files and have to resolve that multiple times.
With all the extra conflict resolution you need to do, it just increases the possibility that you will make a mistake. But mistakes are fine in git since you can undo, right? Except of course...
I think we can all agree that conflict resolution can be difficult, and also that some people are very bad at it. It can be very prone to mistakes, which why it's so great that git makes it easy to undo!
When you merge a branch, git creates a merge commit that can be discarded or amended if the conflict resolution goes poorly. Even if you have already pushed the bad merge commit to the public/authoritative repo, you can use git revert
to undo the changes introduced by the merge and redo the merge correctly in a new merge commit.
When you rebase a branch, in the likely event that conflict resolution is done wrong, you're screwed. Every commit now contains the bad merge, and you can't just redo the rebase*. At best, you have to go back and amend each of the affected commits. Not fun.
After a rebase, it's impossible to determine what was originally part of the commits and what was introduced as a result of bad conflict resolution.
*It can be possible to undo a rebase if you can dig the old refs out of git's internal logs, or if you create a third branch that points to the last commit before rebasing.
Take this conflict for example:
<<<<<<< HEAD
TextMessage.send(:include_timestamp => true)
=======
EmailMessage.send(:include_timestamp => false)
>>>>>>> feature-branch
Looking at the conflict, it's impossible to tell what each branch changed or what its intent was. This is the biggest reason in my opinion why conflict resolution is confusing and hard.
diff3 to the rescue!
git config --global merge.conflictstyle diff3
When you use the diff3, each new conflict will have a 3rd section, the merged common ancestor.
<<<<<<< HEAD
TextMessage.send(:include_timestamp => true)
||||||| merged common ancestor
EmailMessage.send(:include_timestamp => true)
=======
EmailMessage.send(:include_timestamp => false)
>>>>>>> feature-branch
First examine the merged common ancestor. Then compare each side to determine each branch's intent. You can see that HEAD changed EmailMessage to TextMessage. Its intent is to change the class used to TextMessage, passing the same parameters. You can also see that feature-branch's intent is to pass false instead of true for the :include_timestamp option. To merge these changes, combine the intent of both:
TextMessage.send(:include_timestamp => false)
In general:
Finally, some conflicts are terrible to understand even with diff3. This happens especially when diff finds lines in common that are not semantically common (eg. both branches happened to have a blank line at the same place!). For example, one branch changes the indentation of the body of a class or reorders similar methods. In these cases, a better resolution strategy can be to examine the change from either side of the merge and manually apply the diff to the other file.
Let's look at how we might resolve a conflict in a scenario where merging origin/feature1
where lib/message.rb
conflicts.
Decide whether our currently checked out branch (HEAD
, or --ours
) or the branch we're merging (origin/feature1
, or --theirs
) is a simpler change to apply. Using diff with triple dot (git diff a...b
) shows the changes that happened on b
since its last divergence from a
, or in other words, compare the common ancestor of a and b with b.
git diff HEAD...origin/feature1 -- lib/message.rb # show the change in feature1
git diff origin/feature1...HEAD -- lib/message.rb # show the change in our branch
Check out the more complicated version of the file. This will remove all conflict markers and use the side you choose.
git checkout --ours -- lib/message.rb # if our branch's change is more complicated
git checkout --theirs -- lib/message.rb # if origin/feature1's change is more complicated
With the complicated change checked out, pull up the diff of the simpler change (see step 1). Apply each change from this diff to the conflicting file.
alias jsonp='pbpaste | python -m json.tool'
This will pretty print JSON that's on the clipboard in OSX. Just Copy it then call the alias from a Bash prompt.
In cases where you're somewhere behind on a branch,
it is safer to rebase any local changes you may have:
git pull --rebase
This help prevent unnecessary merge-commits.
1) check if service declaration in manifest is nested in application tag
<application>
<service android:name="" />
</application>
2) check if your service.java
is in the same package or diff package as the activity
<application>
<!-- service.java exists in diff package -->
<service android:name="com.package.helper.service" />
</application>
<application>
<!-- service.java exists in same package -->
<service android:name=".service" />
</application>
On the side bar of the PHP 7 alpha download page, it does say this:
VC9, VC11 & VC14 More recent versions of PHP are built with VC9, VC11 or VC14 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.
The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed
The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed
The VC14 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed
There's been a problem with some of those links, so the files are also available from Softpedia.
In the case of the PHP 7 alpha, it's the last option that's required.
I think that the placement of this information is poor, as it's kind of marginalized (i.e.: it's basically literally in the margin!) whereas it's actually critical for the software to run.
I documented my experiences of getting PHP 7 alpha up and running on Windows 8.1 in PHP: getting PHP7 alpha running on Windows 8.1, and it covers some more symptoms that might crop up. They're out of scope for this question but might help other people.
Other symptom of this issue:
php7apache2_4.dll
is missing despite it definitely being in place, and offering nothing else in any log.php-cgi.exe - The FastCGI process exited unexpectedly
(as per @ftexperts's comment below)Attempted solution:
php7apache2_4.dll
file from an earlier PHP 7 dev build. This did not work.(I include those for googleability.)
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Try to reinstall it with the following code:
!pip install --proxy http://username:[email protected]:8080 --upgrade --force-reinstall cx_Oracle
There is no need to use foreign libraries.
Convert a BitmapImage to Bitmap:
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
// BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));
using(MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapImage));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
return new Bitmap(bitmap);
}
}
To convert the Bitmap back to a BitmapImage:
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapImage retval;
try
{
retval = (BitmapImage)Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(hBitmap);
}
return retval;
}
You can try,
<?php
if (isset($_POST["mail"])) {
echo "Yes, mail is set";
}else{
echo "N0, mail is not set";
}
?>
You will need to Build
and Archive
your project. You may need to check what code signing settings you have in the project and executable.
Use the Organiser to select your archive version and then you can Share
that version of your project. You will need to select the correct code signing again. It will allow you to save the .ipa
file where you want.
Drag and drop the .ipa
file into iTunes and then sync with your iPhone.
EDIT: Here are some more detailed instructions including screenshots;
It happens that LINQ doesn't like properties such as DateTime.Date
. It just can't convert to SQL queries. So I figured out a way of comparing dates using Jon's answer, but without that naughty DateTime.Date
. Something like this:
var q = db.Games.Where(t => t.StartDate.CompareTo(DateTime.Today) >= 0).OrderBy(d => d.StartDate);
This way, we're comparing a full database DateTime, with all that date and time stuff, like 2015-03-04 11:49:45.000 or something like this, with a DateTime that represents the actual first millisecond of that day, like 2015-03-04 00:00:00.0000.
Any DateTime we compare to that DateTime.Today
will return us safely if that date is later or the same. Unless you want to compare literally the same day, in which case I think you should go for Caesar's answer.
The method DateTime.CompareTo()
is just fancy Object-Oriented stuff. It returns -1 if the parameter is earlier than the DateTime you referenced, 0 if it is LITERALLY EQUAL (with all that timey stuff) and 1 if it is later.
according me, it is not possible
solution:
import .sql file on mysql server
after
import mysql.connector
import pandas as pd
and then you use .sql file by convert to dataframe
Switch from Blank Activity and use Empty Activity. Change your theme to for example Holo.Light.NoActionBar.
Unlike Blank, Empty is more stripped down thus you may need to add some stuff yourself. Such as add the 2 Override methods onCreateOptionsMenu and onOptionsItemSelected yourself if you need to manipulate controls on the ActionBar and such. Otherwise, no other significant difference.
These posts may be in the wrong order! This is #2 in a series of 3 posts. Sorry.
I've "taken a few liberties" with Lie Ryan's code, implementing a linked list so individual elements of his vector can be accessed via a linked list. This allows access, but admittedly it is time-consuming to access individual elements due to search overhead, i.e. walking down the list until you find the right element. I'll cure this by maintaining an address vector containing subscripts 0 through whatever paired with memory addresses. This is still not as efficient as a plain-and-simple array would be, but at least you don't have to "walk the list" searching for the proper item.
// Based on code from https://stackoverflow.com/questions/3536153/c-dynamically-growing-array
typedef struct STRUCT_SS_VECTOR
{ size_t size; // # of vector elements
void** items; // makes up one vector element's component contents
int subscript; // this element's subscript nmbr, 0 thru whatever
struct STRUCT_SS_VECTOR* this_element; // linked list via this ptr
struct STRUCT_SS_VECTOR* next_element; // and next ptr
} ss_vector;
ss_vector* vector; // ptr to vector of components
ss_vector* ss_init_vector(size_t item_size) // item_size is size of one array member
{ vector= malloc(sizeof(ss_vector));
vector->this_element = vector;
vector->size = 0; // initialize count of vector component elements
vector->items = calloc(1, item_size); // allocate & zero out memory for one linked list element
vector->subscript=0;
vector->next_element=NULL;
// If there's an array of element addresses/subscripts, install it now.
return vector->this_element;
}
ss_vector* ss_vector_append(ss_vector* vec_element, int i)
// ^--ptr to this element ^--element nmbr
{ ss_vector* local_vec_element=0;
// If there is already a next element, recurse to end-of-linked-list
if(vec_element->next_element!=(size_t)0)
{ local_vec_element= ss_vector_append(vec_element->next_element,i); // recurse to end of list
return local_vec_element;
}
// vec_element is NULL, so make a new element and add at end of list
local_vec_element= calloc(1,sizeof(ss_vector)); // memory for one component
local_vec_element->this_element=local_vec_element; // save the address
local_vec_element->next_element=0;
vec_element->next_element=local_vec_element->this_element;
local_vec_element->subscript=i; //vec_element->size;
local_vec_element->size=i; // increment # of vector components
// If there's an array of element addresses/subscripts, update it now.
return local_vec_element;
}
void ss_vector_free_one_element(int i,gboolean Update_subscripts)
{ // Walk the entire linked list to the specified element, patch up
// the element ptrs before/next, then free its contents, then free it.
// Walk the rest of the list, updating subscripts, if requested.
// If there's an array of element addresses/subscripts, shift it along the way.
ss_vector* vec_element;
struct STRUCT_SS_VECTOR* this_one;
struct STRUCT_SS_VECTOR* next_one;
vec_element=vector;
while((vec_element->this_element->subscript!=i)&&(vec_element->next_element!=(size_t) 0)) // skip
{ this_one=vec_element->this_element; // trailing ptr
next_one=vec_element->next_element; // will become current ptr
vec_element=next_one;
}
// now at either target element or end-of-list
if(vec_element->this_element->subscript!=i)
{ printf("vector element not found\n");return;}
// free this one
this_one->next_element=next_one->next_element;// previous element points to element after current one
printf("freeing element[%i] at %lu",next_one->subscript,(size_t)next_one);
printf(" between %lu and %lu\n",(size_t)this_one,(size_t)next_one->next_element);
vec_element=next_one->next_element;
free(next_one); // free the current element
// renumber if requested
if(Update_subscripts)
{ i=0;
vec_element=vector;
while(vec_element!=(size_t) 0)
{ vec_element->subscript=i;
i++;
vec_element=vec_element->next_element;
}
}
// If there's an array of element addresses/subscripts, update it now.
/* // Check: temporarily show the new list
vec_element=vector;
while(vec_element!=(size_t) 0)
{ printf(" remaining element[%i] at %lu\n",vec_element->subscript,(size_t)vec_element->this_element);
vec_element=vec_element->next_element;
} */
return;
} // void ss_vector_free_one_element()
void ss_vector_insert_one_element(ss_vector* vec_element,int place)
{ // Walk the entire linked list to specified element "place", patch up
// the element ptrs before/next, then calloc an element and store its contents at "place".
// Increment all the following subscripts.
// If there's an array of element addresses/subscripts, make a bigger one,
// copy the old one, then shift appropriate members.
// ***Not yet implemented***
} // void ss_vector_insert_one_element()
void ss_vector_free_all_elements(void)
{ // Start at "vector".Walk the entire linked list, free each element's contents,
// free that element, then move to the next one.
// If there's an array of element addresses/subscripts, free it.
ss_vector* vec_element;
struct STRUCT_SS_VECTOR* next_one;
vec_element=vector;
while(vec_element->next_element!=(size_t) 0)
{ next_one=vec_element->next_element;
// free(vec_element->items) // don't forget to free these
free(vec_element->this_element);
vec_element=next_one;
next_one=vec_element->this_element;
}
// get rid of the last one.
// free(vec_element->items)
free(vec_element);
vector=NULL;
// If there's an array of element addresses/subscripts, free it now.
printf("\nall vector elements & contents freed\n");
} // void ss_vector_free_all_elements()
// defining some sort of struct, can be anything really
typedef struct APPLE_STRUCT
{ int id; // one of the data in the component
int other_id; // etc
struct APPLE_STRUCT* next_element;
} apple; // description of component
apple* init_apple(int id) // make a single component
{ apple* a; // ptr to component
a = malloc(sizeof(apple)); // memory for one component
a->id = id; // populate with data
a->other_id=id+10;
a->next_element=NULL;
// don't mess with aa->last_rec here
return a; // return pointer to component
};
int return_id_value(int i,apple* aa) // given ptr to component, return single data item
{ printf("was inserted as apple[%i].id = %i ",i,aa->id);
return(aa->id);
}
ss_vector* return_address_given_subscript(ss_vector* vec_element,int i)
// always make the first call to this subroutine with global vbl "vector"
{ ss_vector* local_vec_element=0;
// If there is a next element, recurse toward end-of-linked-list
if(vec_element->next_element!=(size_t)0)
{ if((vec_element->this_element->subscript==i))
{ return vec_element->this_element;}
local_vec_element= return_address_given_subscript(vec_element->next_element,i); // recurse to end of list
return local_vec_element;
}
else
{ if((vec_element->this_element->subscript==i)) // last element
{ return vec_element->this_element;}
// otherwise, none match
printf("reached end of list without match\n");
return (size_t) 0;
}
} // return_address_given_subscript()
int Test(void) // was "main" in the original example
{ ss_vector* local_vector;
local_vector=ss_init_vector(sizeof(apple)); // element "0"
for (int i = 1; i < 10; i++) // inserting items "1" thru whatever
{ local_vector=ss_vector_append(vector,i);}
// test search function
printf("\n NEXT, test search for address given subscript\n");
local_vector=return_address_given_subscript(vector,5);
printf("finished return_address_given_subscript(5) with vector at %lu\n",(size_t)local_vector);
local_vector=return_address_given_subscript(vector,0);
printf("finished return_address_given_subscript(0) with vector at %lu\n",(size_t)local_vector);
local_vector=return_address_given_subscript(vector,9);
printf("finished return_address_given_subscript(9) with vector at %lu\n",(size_t)local_vector);
// test single-element removal
printf("\nNEXT, test single element removal\n");
ss_vector_free_one_element(5,FALSE); // without renumbering subscripts
ss_vector_free_one_element(3,TRUE);// WITH renumbering subscripts
// ---end of program---
// don't forget to free everything
ss_vector_free_all_elements();
return 0;
}
to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php
$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");
$json_object = json_decode($unparsed_json);
then json_decode() parses JSON into a PHP object, or an array if you pass true
to the second parameter.
http://php.net/manual/en/function.json-decode.php
For example:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // Object
var_dump(json_decode($json, true)); // Associative array
For Swift 5
Remove Cell
let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
yourArray.remove(at: buttonTag)
self.tableView.beginUpdates()
self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
self.tableView.endUpdates()
self.tableView.reloadData()// Not mendatory, But In my case its requires
Add new cell
yourArray.append(4)
tableView.beginUpdates()
tableView.insertRows(at: [
(NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
tableView.endUpdates()
I'm not sure you understand what "exit" states
Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.
It's normal to do that, it must clear it's memmory of all the variables and functions you called before. Not doing this would mean your memmory would remain stuck and ocuppied in your RAM, and if this would happen several times you would need to reboot and flush your RAM in order to have any left.
If you are trying to create a self signed certificate that lets you go http://localhost/mysite
Then here is a way to create it
makecert -r -n "CN=localhost" -b 01/01/2000 -e 01/01/2099 -eku 1.3.6.1.5.5.7.3.1 -sv localhost.pvk localhost.cer
cert2spc localhost.cer localhost.spc
pvk2pfx -pvk localhost.pvk -spc localhost.spc -pfx localhost.pfx
From http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/32bc5a61-1f7b-4545-a514-a11652f11200
Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).
The reason I wanted that version in particular is because that's what ships with MVC currently.
Here's the code:
$(document).ready(function() {
$("#topBar").css("position", "absolute");
});
$(window).scroll(function() {
$("#topBar").css("top", $(window).scrollTop() + "px");
});
Here's a short function that uses some of the newer JavaScript array methods to flatten an n-dimensional array.
function flatten(arr) {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
Usage:
flatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5]
flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5]
Try this little trick to coax grep
into thinking it is dealing with multiple files, so that it displays the filename:
grep 'pattern' file /dev/null
To also get the line number:
grep -n 'pattern' file /dev/null
Based in @tomvon, I finished using the following (pick your case):
a) Resizing height (I know the new width, so I need the new height)
new_width = 680
new_height = new_width * height / width
b) Resizing width (I know the new height, so I need the new width)
new_height = 680
new_width = new_height * width / height
Then just:
img = img.resize((new_width, new_height), Image.ANTIALIAS)
Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:
A new config setting core.eol
is being added/evolved:
This is a replacement for the 'Add "
core.eol
" config variable' commit that's currently inpu
(the last one in my series).
Instead of implying that "core.autocrlf=true
" is a replacement for "* text=auto
", it makes explicit the fact thatautocrlf
is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.Introduce a new configuration variable, "
core.eol
", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native
", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf
" overridescore.eol
.
This means that:[core] autocrlf = true
puts CRLFs in the working directory even if
core.eol
is set to "lf
".core.eol:
Sets the line ending type to use in the working directory for files that have the
text
property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value isnative
.
Other evolutions are being considered:
For 1.8, I would consider making
core.autocrlf
just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.
git 2.8 (March 2016) improves the way core.autocrlf
influences the eol:
See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit c6b94eb, 26 Feb 2016)
convert.c
: refactorcrlf_action
Refactor the determination and usage of
crlf_action
.
Today, when no "crlf
" attribute are set on a file,crlf_action
is set toCRLF_GUESS
. UseCRLF_UNDEFINED
instead, and search for "text
" or "eol
" as before.Replace the old
CRLF_GUESS
usage:
CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT
Make more clear, what is what, by defining:
- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
and core.eol is evaluated and one of CRLF_BINARY,
CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY : No processing of line endings.
- CRLF_TEXT : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true (no attributes)
As torek adds in the comments:
all these translations (any EOL conversion from
eol=
orautocrlf
settings, and "clean
" filters) are run when files move from work-tree to index, i.e., duringgit add
rather than atgit commit
time.
(Note thatgit commit -a
or--only
or--include
do add files to the index at that time, though.)
For more on that, see "What is difference between autocrlf and eol".
It is because the framework requires that two objects that are the same must have the same hashcode. If you override the equals method to do a special comparison of two objects and the two objects are considered the same by the method, then the hash code of the two objects must also be the same. (Dictionaries and Hashtables rely on this principle).
bundle exec rake db:rollback
rails destroy model <model_name>
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run
bundle exec rake db:rollback
You should firstly put this code in your AppManifest.xml in the application tag:
android:supportsRtl="true"
then in your activity_main.xml file, put this piece of code:
android:layout_direction="rtl"
The reason I sometimes use php name-conventions with javascript variables: When doing input validation, I want to run the exact same algorithms both client-side, and server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.
(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)
You can use a transparent poster image in combination with a CSS background image to achieve this (example); however, to have a background stretched to the height and the width of a video, you'll have to use an absolutely positioned <img>
tag (example).
It is also possible to set background-size
to 100% 100%
in browsers that support background-size
(example).
A better way to do this would be to use the object-fit
CSS property as @Lars Ericsson suggests.
Use
object-fit: cover;
if you don't want to display those parts of the image that don't fit the video's aspect ratio, and
object-fit: fill;
to stretch the image to fit your video's aspect ratio
TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem();
tempItem = (TreeViewItem) treeView1.Items.GetItemAt(0); // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0); // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString(); // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true; // will expand the first node
If you want to remove all -
you can use:
.replace(new RegExp('-', 'g'),"")
Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:
> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World
Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString
and Buffer
constructor encodings are as follows:
'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.
'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
'base64' - Base64 string encoding.
'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.
reverse()
| Django documentation
Let's suppose that in your urls.py
you have defined this:
url(r'^foo$', some_view, name='url_name'),
In a template you can then refer to this url as:
<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>
<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>
This will be rendered as:
<a href="/foo/">link which calls some_view</a>
Now say you want to do something similar in your views.py
- e.g. you are handling some other url (not /foo/
) in some other view (not some_view
) and you want to redirect the user to /foo/
(often the case on successful form submission).
You could just do:
return HttpResponseRedirect('/foo/')
But what if you want to change the url in future? You'd have to update your urls.py
and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.
Instead, you can say:
from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))
This looks through all urls defined in your project for the url defined with the name url_name
and returns the actual url /foo/
.
This means that you refer to the url only by its name
attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py
.
The big difference is that the first example actually invokes the lambda f(x)
, while the second example doesn't.
Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)]
while your second example is equivalent to [f for x in range(10)]
.
The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:
git update-index --skip-worktree .classpath .gitignore
It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.
Running git rm --cached
doesn't work for the scenario mentioned in the question. If I simplify the question, it says:
How to have
.classpath
and.project
on the repo while each one can change it locally and git ignores this change?
As I commented under the accepted answer, the drawback of git rm --cached
is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath
and .project
won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.
Based on git documentaion:
Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.
More details is available here.
map(lambda s: s.strip(), mylist)
would be a little better than explicitly looping.
Or for the whole thing at once:
map(lambda s:s.strip(), string.split(','))
That's basically everything you need.
Many unix
-like systems (Linux
, the BSD
s, and OS X
, at the very least) have the fts
functions for directory traversal.
To recursively delete a directory, perform a depth-first traversal (without following symlinks) and remove every visited file:
int recursive_delete(const char *dir)
{
int ret = 0;
FTS *ftsp = NULL;
FTSENT *curr;
// Cast needed (in C) because fts_open() takes a "char * const *", instead
// of a "const char * const *", which is only allowed in C++. fts_open()
// does not modify the argument.
char *files[] = { (char *) dir, NULL };
// FTS_NOCHDIR - Avoid changing cwd, which could cause unexpected behavior
// in multithreaded programs
// FTS_PHYSICAL - Don't follow symlinks. Prevents deletion of files outside
// of the specified directory
// FTS_XDEV - Don't cross filesystem boundaries
ftsp = fts_open(files, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, NULL);
if (!ftsp) {
fprintf(stderr, "%s: fts_open failed: %s\n", dir, strerror(errno));
ret = -1;
goto finish;
}
while ((curr = fts_read(ftsp))) {
switch (curr->fts_info) {
case FTS_NS:
case FTS_DNR:
case FTS_ERR:
fprintf(stderr, "%s: fts_read error: %s\n",
curr->fts_accpath, strerror(curr->fts_errno));
break;
case FTS_DC:
case FTS_DOT:
case FTS_NSOK:
// Not reached unless FTS_LOGICAL, FTS_SEEDOT, or FTS_NOSTAT were
// passed to fts_open()
break;
case FTS_D:
// Do nothing. Need depth-first search, so directories are deleted
// in FTS_DP
break;
case FTS_DP:
case FTS_F:
case FTS_SL:
case FTS_SLNONE:
case FTS_DEFAULT:
if (remove(curr->fts_accpath) < 0) {
fprintf(stderr, "%s: Failed to remove: %s\n",
curr->fts_path, strerror(curr->fts_errno));
ret = -1;
}
break;
}
}
finish:
if (ftsp) {
fts_close(ftsp);
}
return ret;
}
@michi; define height
in your before
pseudo class
CSS:
#videos-part:before{
width: 16px;
content: " ";
background-image: url(/img/border-left3.png);
position: absolute;
left: -16px;
top: -6px;
height:20px;
}
I had the same problem for different package. I was installing pyinstaller
in conda on Mac Mojave. I did
conda create --name ai37 python=3.7
conda activate ai37
I got the mentioned error when I tried to install pyinstaller using
pip install pyinstaller
I was able to install the pyinstaller with the following command
conda install -c conda-forge pyinstaller
In my case alter column was not working so one can use 'Modify' command, like:
alter table [table_name] MODIFY column [column_name] varchar(1200);
The answer has already been here. If you don't want to use any library, you can follow these steps:
Explanation:
In onCreateViewHolder
method we can check viewType
and depending on the value (our "special" kind) inflate a special layout.
For example:
public static final int TITLE = 0;
public static final int ITEM = 1;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (context == null) {
context = parent.getContext();
}
if (viewType == TITLE) {
view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_title, parent,false);
return new TitleElement(view);
} else if (viewType == ITEM) {
view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_item, parent,false);
return new ItemElement(view);
}
return null;
}
where class ItemElement
and class TitleElement
can look like ordinary ViewHolder
:
public class ItemElement extends RecyclerView.ViewHolder {
//TextView text;
public ItemElement(View view) {
super(view);
//text = (TextView) view.findViewById(R.id.text);
}
So the idea of all of that is interesting. But i am interested if it's effectively, cause we need to sort the data list. And i think this will take the speed down. If any thoughts about it, please write me :)
And also the opened question : is how to hold the "special" layout on the top, while the items are recycling. Maybe combine all of that with CoordinatorLayout
.
A static library(.a) is a library that can be linked directly into the final executable produced by the linker,it is contained in it and there is no need to have the library into the system where the executable will be deployed.
A shared library(.so) is a library that is linked but not embedded in the final executable, so will be loaded when the executable is launched and need to be present in the system where the executable is deployed.
A dynamic link library on windows(.dll) is like a shared library(.so) on linux but there are some differences between the two implementations that are related to the OS (Windows vs Linux) :
A DLL can define two kinds of functions: exported and internal. The exported functions are intended to be called by other modules, as well as from within the DLL where they are defined. Internal functions are typically intended to be called only from within the DLL where they are defined.
An SO library on Linux doesn't need special export statement to indicate exportable symbols, since all symbols are available to an interrogating process.
Edit the android studio's Info.plist file in the package so that it uses 1.7 or whatever JVMVersion you have installed. Changing the JVMVersion to 1.6+ instead of 1.6* as hasternet answered above should work too.
The above works but is not recommended see RC3 Release Notes
As of RC 3, we have a better mechanism for customizing properties for the launchers on all three platforms. You should not edit any files in the IDE installation directory. Instead, you can customize the attributes by creating your own .properties or .vmoptions files in the following directories. (This has been possible on some platforms before, but it required you to copy and change the entire contents of the files. With the latest changes these properties are now additive instead such that you can set just the attributes you care about, and the rest will use the defaults from the IDE installation).
see Android Studio failed to load JVM on Mac OSX (Mavericks)
Assuming you are on Python 3, you can use this syntax
inputs = list(map(str,input().split()))
if you want to access individual element you can do it like that
m, n = map(str,input().split())
To adjust the size of one figure:
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(15, 15))
To change the default settings, and therefore all your plots:
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [15, 15]
.ico
, or is it just named ".ico"?The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.
If you must have it in a subdirectory, use:
<link rel="shortcut icon" href="/img/favicon.ico" />
Note the /
before img
to ensure it is anchored to the root folder.
You can try returning the variable you wish to inspect. E.g. I have this function:
--Contencates seperate date and time strings and converts to a datetime. Date should be in format 25.03.2012. Time as 9:18:25.
ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS datetime
AS
BEGIN
--select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')
declare @datetime datetime
declare @day_part nvarchar(3)
declare @month_part nvarchar(3)
declare @year_part nvarchar(5)
declare @point_ix int
set @point_ix = charindex('.', @date)
set @day_part = substring(@date, 0, @point_ix)
set @date = substring(@date, @point_ix, len(@date) - @point_ix)
set @point_ix = charindex('.', @date)
set @month_part = substring(@date, 0, @point_ix)
set @date = substring(@date, @point_ix, len(@date) - @point_ix)
set @point_ix = charindex('.', @date)
set @year_part = substring(@date, 0, @point_ix)
set @datetime = @month_part + @day_part + @year_part + ' ' + @time
return @datetime
END
When I run it.. I get: Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.
Arghh!!
So, what do I do?
ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS nvarchar(22)
AS
BEGIN
--select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')
declare @day_part nvarchar(3)
declare @point_ix int
set @point_ix = charindex('.', @date)
set @day_part = substring(@date, 0, @point_ix)
return @day_part
END
And I get '25'. So, I am off by one and so I change to..
set @day_part = substring(@date, 0, @point_ix + 1)
Voila! Now it works :)
You can also post runnable using the view from any other thread. But be sure that the view is not null:
tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});
According to the Documentation:
"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."
I found this answer super-helpful and elegant, originally from here:
matrix = [["A", "B"], ["C", "D"]]
print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in matrix]))
Output
A B
C D
Another alternative might be
Array.from(document.querySelectorAll("a")).map(x => x.href)
With your $$(
its even shorter
Array.from($$("a")).map(x => x.href)
You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate.
double d = double.Parse(b);
DateTime conv = DateTime.FromOADate(d);
In our specific case, the problem was due to having the retrolambda plugin, which forced all projects and subprojects to recompile everytime we tried to launch our application, even if no code had been altered in our core modules.
Removing retrolamba fixed it for us. Hope it helps someone.
I had a great deal of trouble linking to MySQL from a 64 bit laptop, running Windows 7, using MS Access 2010. I found the previous article very helpful, but still could not connect using odbc 3.5.1. As I had previously linked a 32 bit machine using Connector/ODBC 5.1.13, I downloaded that version and set it up using the instructions above. Success. The answer seems to be to try different versions of Connector.odbc.
You have endless loop in place:
function save() {
var filename = id('filename').value;
var name = id('name').value;
var text = id('text').value;
save(filename, name, text);
}
No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.
select tab1.name,
count(distinct tab2.id) as tab2_record_count
count(distinct tab3.id) as tab3_record_count
count(distinct tab4.id) as tab4_record_count
from tab1
left join tab2 on tab2.tab1_id = tab1.id
left join tab3 on tab3.tab1_id = tab1.id
left join tab4 on tab4.tab1_id = tab1.id
If it's about dictionaries and the like, you're looking for System.Collections.Generic.KeyValuePair<TKey, TValue>.
Given exportPath
and queryResults
as String variables, the following block creates a results.zip
file under exportPath
and writes the content of queryResults
to a results.txt
file inside the zip.
URI uri = URI.create("jar:file:" + exportPath + "/results.zip");
Map<String, String> env = Collections.singletonMap("create", "true");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path filePath = zipfs.getPath("/results.txt");
byte[] fileContent = queryResults.getBytes();
Files.write(filePath, fileContent, StandardOpenOption.CREATE);
}
Just move to the new branch. The uncommited changes get carried over.
git checkout -b ABC_1
git commit -m <message>
I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.
.directive('hoverClass', function () {
return {
restrict: 'A',
scope: {
hoverClass: '@'
},
link: function (scope, element) {
element.on('mouseenter', function() {
element.addClass(scope.hoverClass);
});
element.on('mouseleave', function() {
element.removeClass(scope.hoverClass);
});
}
};
})
then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:
<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
index="{{$index}}"><i class="{{item.icon}}"
box="course-{{$index}}"></i></li>
This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work
<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
data-ng-controller ="CourseItemController"
data-ng-class="{ selected: isSelected }">
providing of course that the li's are infact children of the parent div
Just tried updating 43 fields on a table with 44 fields, the remaining field was the primary clustered key.
The update took 8 seconds.
A Delete + Insert is faster than the minimum time interval that the "Client Statistics" reports via SQL Management Studio.
Peter
MS SQL 2008
func buttonAction(sender:UIButton!)
{
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tablevw)
let indexPath = self.tablevw.indexPathForRowAtPoint(position)
let cell: TableViewCell = tablevw.cellForRowAtIndexPath(indexPath!) as TableViewCell
println(indexPath?.row)
println("Button tapped")
}
If you're using Java 5 or higher, you can use String.format
:
urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);
See Formatter
for details.
HTML
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 option2">
<p>left column </p>
<p>The first column has to be the longest The first column has to be the longes</p>
</div>
<div class="span4 option2">
<p>middle column</p>
</div>
<div class="span4 option2">
<p>right column </p>
<p>right column </p>
<p>right column </p>
<p>right column </p>
<p>right column </p>
</div>
</div>
</div>
CSS
.option2 { background: red; border: black 1px solid; color: white; }
JS
$('.option2').css({
'height': $('.option2').height()
});
I had the same problem by using library wifi
but when i changed my network it worked perfectly.
Change your network connection
You can get all of the table data by using this query:
SHOW TABLE STATUS FROM `DatabaseName` WHERE `name` LIKE 'TableName' ;
You can get exactly this information by using this query:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
strRequest = "<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" " &_
"xmlns:tem=""http://tempuri.org/"">" &_
"<soap:Header/>" &_
"<soap:Body>" &_
"<tem:Authorization>" &_
"<tem:strCC>"&1234123412341234&"</tem:strCC>" &_
"<tem:strEXPMNTH>"&11&"</tem:strEXPMNTH>" &_
"<tem:CVV2>"&123&"</tem:CVV2>" &_
"<tem:strYR>"&23&"</tem:strYR>" &_
"<tem:dblAmount>"&1235&"</tem:dblAmount>" &_
"</tem:Authorization>" &_
"</soap:Body>" &_
"</soap:Envelope>"
EndPointLink = "http://www.trainingrite.net/trainingrite_epaysystem" &_
"/trainingrite_epaysystem/tr_epaysys.asmx"
dim http
set http=createObject("Microsoft.XMLHTTP")
http.open "POST",EndPointLink,false
http.setRequestHeader "Content-Type","text/xml"
msgbox "REQUEST : " & strRequest
http.send strRequest
If http.Status = 200 Then
'msgbox "RESPONSE : " & http.responseXML.xml
msgbox "RESPONSE : " & http.responseText
responseText=http.responseText
else
msgbox "ERRCODE : " & http.status
End If
Call ParseTag(responseText,"AuthorizationResult")
Call CreateXMLEvidence(responseText,strRequest)
'Function to fetch the required message from a TAG
Function ParseTag(ResponseXML,SearchTag)
ResponseMessage=split(split(split(ResponseXML,SearchTag)(1),"</")(0),">")(1)
Msgbox ResponseMessage
End Function
'Function to create XML test evidence files
Function CreateXMLEvidence(ResponseXML,strRequest)
Set fso=createobject("Scripting.FileSystemObject")
Set qfile=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleResponse.xml",2)
Set qfile1=fso.CreateTextFile("C:\Users\RajkumarJoshua\Desktop\DCIM\SampleReuest.xml",2)
qfile.write ResponseXML
qfile.close
qfile1.write strRequest
qfile1.close
End Function
Try this one,
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"skill":[1436517454492,1436517476993]
}
// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
I dont know if its too late, but i thought it would help someone else.
I wanted the same badly...found it eventually.
Maybe its not perfect,but to me its adequate(for my little dictionary app).
http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip
Its not a dump file, but a MYSQL .sql script file
The words are in WN_SYNSET table and the glossary/meaning in the WN_GLOSS table
I had this problem when some of the dependent assemblies are changed but locked by an other instance of visual studio (2015).
This problem is generally caused by the website/intranet URL being placed in one of:
On corporate networks, these compatibility view settings are often controlled centrally via group policy. In your case, Enterprise Mode appears to be the culprit.
Unfortunately setting META X-UA-Compatible
will not override this.
Sometimes the only way for end-users to override this is to press F12 and change the Document Mode under the Emulation Tab. However this setting is not permanent and may revert once Developer Tools is closed.
You can also try to exclude your site from the Intranet zone. But the list of domains which belong to the Intranet zone is usually also controlled by the group policy, so the chance of this working is slim.
To see the list of domains that belong to the Intranet zone, go to:
Tools -> Internet Options -> Security -> Sites -> Advanced
If the list contains your subdomain and is greyed out, then you will not be able to override compatibility view until your network admin allows it.
You really need to contact your network administrator to allow changing the compatibility view settings in the group policy.
Loading the website with Developer Tools open (F12) will often report the reason that IE is switching to an older mode.
All 3 settings mentioned above are generally controlled via Group Policy, although can sometimes be overridden on user machines.
If Enterprise Mode is the issue (as appears to be the case for the original poster), the following two articles might be helpful:
next
and break
seem to do the correct thing in this simplified example!
class Bar
def self.do_things
Foo.some_method(1..10) do |x|
next if x == 2
break if x == 9
print "#{x} "
end
end
end
class Foo
def self.some_method(targets, &block)
targets.each do |target|
begin
r = yield(target)
rescue => x
puts "rescue #{x}"
end
end
end
end
Bar.do_things
output: 1 3 4 5 6 7 8
There is no block comment in VB.NET.
You need to use a '
in front of every line you want to comment out.
In Visual Studio you can use the keyboard shortcuts that will comment/uncomment the selected lines for you:
Ctrl + K, C to comment
Ctrl + K, U to uncomment
I'm using
/etc/bash_completion.d/git
It came with Git and provides a prompt with branch name and argument completion.
It's a placeholder for a parameter much like the %s
format specifier acts within printf
.
You can start adding extra things in there to determine the format too, though that makes more sense with a numeric variable (examples here).
I personnally went for:
set wrap
,set linebreak
set breakindent
set showbreak=?
.Some explanation:
wrap
option visually wraps line instead of having to scroll horizontallylinebreak
is for wrapping long lines at a specific character instead of just anywhere when the line happens to be too long, like in the middle of a word. By default, it breaks on whitespace (word separator), but you can configure it with breakat
. It also does NOT insert EOL
in the file as the OP wanted.breakat
is the character where it will visually break the line. No need to modify it if you want to break at whitespace between two words.breakindent
enables to visually indent the line when it breaks.showbreak
enables to set the character which indicates this break.See :h <keyword>
within vim for more info.
Note that you don't need to modify textwidth
nor wrapmargin
if you go this route.
Perhaps something more like this?
declare @UpdateTime datetime
set @UpdateTime = getutcdate()
update Table1 set AlertDate = @UpdateTime where AlertDate is null
select ID from Table1 where AlertDate = @UpdateTime
It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.
Have you tried to edit to see what's wrong (I had the wrong image location)
kubectl edit pods arix-3-yjq9w
or even delete your pod?
kubectl delete arix-3-yjq9w
Have a look at the content by type web part - http://codeplex.com/eoffice - probably the most flexible viewing web part.
The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments
object.
The arguments
object contains one element for each actual parameter provided to the function. When you call a
you supply three arguments: the numbers 1
, 2
, and, 3
. So, arguments
contains [1, 2, 3]
.
function a(args){
console.log(arguments) // [1, 2, 3]
b(arguments);
}
When you call b
, however, you pass exactly one argument: a
's arguments
object. So arguments
contains [[1, 2, 3]]
(i.e. one element, which is a
's arguments
object, which has properties containing the original arguments to a
).
function b(args){
// arguments are lost?
console.log(arguments) // [[1, 2, 3]]
}
a(1,2,3);
As @Nick demonstrated, you can use apply
to provide a set arguments
object in the call.
The following achieves the same result:
function a(args){
b(arguments[0], arguments[1], arguments[2]); // three arguments
}
But apply
is the correct solution in the general case.
Why do people keep confusing php and javascript?
PHP is SERVER SIDE
JAVASCRIPT (like onclick) is CLIENT SIDE
You will have to use just javascript to redirect. Otherwise if you want PHP involved you can use an AJAX call to log a hit or whatever you like to send back a URL or additional detail.
The problem is in this method:
public static byte[] encrypt(String toEncrypt) throws Exception{
This is the method signature which pretty much says:
In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".
....
concatURL = padString(concatURL, ' ', 16);
byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
String encryptedString = bytesToHex(encrypted);
content.removeAll();
......
So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.
The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.
Try this:
public static byte[] encrypt(String toEncrypt) {
try{
String plaintext = toEncrypt;
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
} catch ( NoSuchAlgorithmException nsae ) {
// What can you do if the algorithm doesn't exists??
// this usually won't happen because you would test
// your code before shipping.
// So in this case is ok to transform to another kind
throw new IllegalStateException( nsae );
} catch ( NoSuchPaddingException nspe ) {
// What can you do when there is no such padding ( whatever that means ) ??
// I guess not much, in either case you won't be able to encrypt the given string
throw new IllegalStateException( nsae );
}
// line 109 won't say it needs a return anymore.
}
Basically in this particular case you should make sure the cryptography package is available in the system.
Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.
In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.
The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.
try {
// risky code ...
} catch( Exception e ) {
// a bomb has just exploited
// you should NOT ignore it
}
// The code continues here, but what should it do???
If the code is to fail, it is better to Fail fast
Here are some related answers:
try
block contains set of statements where an exception can occur.
catch
block will be used to used to handle the exception that occur with in try
block. A try
block is always followed by a catch
block and we can have multiple catch blocks.
finally
block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.
throw
keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.
throws
keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
// Java program to demonstrate working of throws, throw, try, catch and finally.
public class MyExample {
static void myMethod() throws IllegalAccessException
{
System.out.println("Inside myMethod().");
throw new IllegalAccessException("demo");
}
// This is a caller function
public static void main(String args[])
{
try {
myMethod();
}
catch (IllegalAccessException e) {
System.out.println("exception caught in main method.");
}
finally(){
System.out.println("I am in final block.");
}
}
}
Output:
Inside myMethod().
exception caught in main method.
I am in final block.
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
I would try to avoid changing the xticklabels
if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.
Defining the range of your grid is probably the best and with imshow
it can be done by adding the extent
keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks
with perhaps some formatter. Altering the labels directly should be the last resort.
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio
To obtain the current stable version of the NuGet package use:
https://www.nuget.org/api/v2/package/{packageID}
Console.WriteLine(DateTime.UtcNow.ToString("o"));
Console.WriteLine(DateTime.Now.ToString("o"));
Outputs:
2012-07-09T19:22:09.1440844Z
2012-07-09T12:22:09.1440844-07:00
Use findElement
instead of findElements
driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");
OR
driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");
OR using JavascriptExecutor
WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='enter the value here';", element);
OR
(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);
OR (in javascript)
driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")
Hope it will help you :)
I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.
For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"
I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.
<build>
<defaultGoal>package</defaultGoal>
<directory>${basedir}/build</directory>
<build>
I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"
I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
inputChangeHandler(event) {_x000D_
this.setState({ [event.target.name]: event.target.value });_x000D_
}
_x000D_
I thought TextMate was everyone's favourite. I haven't met a programmer using a Mac who is not using TextMate.
In order to use <Aux>
in your JSX, it needs to be a function that returns ReactElement<any> | null
. That's the definition of a function component.
However, it's currently defined as a function that returns React.ReactNode
, which is a much wider type. As React typings say:
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;
Make sure the unwanted types are neutralized by wrapping the returned value into React Fragment (<></>
):
const aux: React.FC<AuxProps> = props =>
<>{props.children}</>;
Put content from other site in iframe
<iframe src="/othersiteurl" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
From 2018:
Go to Settings -> Basic -> App Secret
(type your password and you're ready to go).
List<Integer> numbers = new TheClassName().myNumbers();
You should Remember about TERNARY operator
:
so your code will be like this,
render(){
return (
<div>
<Element1/>
<Element2/>
// note: code does not work here
{
this.props.hasImage ? // if has image
<MyImage /> // return My image tag
:
<OtherElement/> // otherwise return other element
}
</div>
)
}
PostgreSQL drivers jars are included in Central Repository of Maven:
For PostgreSQL up to 9.1, use:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>VERSION</version>
</dependency>
or for 9.2+
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>VERSION</version>
</dependency>
(Thanks to @Caspar for the correction)
This is what I used.
$('#foo').popover({
placement : 'bottom',
title : 'Title',
content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});
and for the HTML
<b id="foo" rel="popover">text goes here</b>
the command to get the effective push remote for the branch, e.g., master, is:
git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote
Here's why (from the "man git config" output):
branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]
For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote
If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.
You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.
If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.
The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.
This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.
public static bool isValidEmail(string inputEmail)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
I did it like this
SELECT
TOP 0
*
FROM
Posts
It works even in http://data.stackexchange.com whose service tables I am not aware of!
Another answer would be the NodeJS!
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Using terminal you will be able to start it using node
command.
$ node
> 2 + 4
6
>
Note: If you want to exit just type
.exit
You can also run a JavaScript file like this:
node file.js
To give you some idea:
public void paint(Graphics g) {
drawCoordinates(g);
}
private void drawCoordinates(Graphics g) {
// get width & height here (w,h)
// define grid width (dh, dv)
for (int x = 0; i < w; i += dh) {
g.drawLine(x, 0, x, h);
}
for (int y = 0; j < h; j += dv) {
g.drawLine(0, y, w, y);
}
}
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
The imshow()
function with parameters interpolation='nearest'
and cmap='hot'
should do what you want.
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({_x000D_
crossOrigin: true,_x000D_
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})
_x000D_
Please set http content type in header and also make sure the server is authenticating CORS. This is how to do it in PHP:
//NOT A TESTED CODE
header('Content-Type: application/json;charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Max-Age: 1728000');
Please refer to:
http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
You can accomplish this by setting this on the container:
ul {
display: flex;
flex-wrap: wrap;
}
And on the child you set this:
li:nth-child(2n) {
flex-basis: 100%;
}
ul {
display: flex;
flex-wrap: wrap;
list-style: none;
}
li:nth-child(4n) {
flex-basis: 100%;
}
_x000D_
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
_x000D_
This causes the child to make up 100% of the container width before any other calculation. Since the container is set to break in case there is not enough space it does so before and after this child. So you could use an empty div element to force the wrap between the element before and after it.
I just look for _sdk
, _sdk_
or sdk_
, or even just sdk
part in Build.PRODUCT
:
if(Build.PRODUCT.matches(".*_?sdk_?.*")){
//-- emulator --
}else{
//-- other device --
}
Not sure if this helps but in my app I had to check if a dictionary has changed.
Doing this will not work since basically it's still the same object:
val={'A':1,'B':2}
old_val=val
val['A']=10
if old_val != val:
print('changed')
Using copy/deepcopy works:
import copy
val={'A':1,'B':2}
old_val=copy.deepcopy(val)
val['A']=10
if old_val != val:
print('changed')
This is where you can find the answer in the job-dsl-plugin code.
Basically you can do something like this:
readFileFromWorkspace('src/main/groovy/com/groovy/jenkins/scripts/enable_safehtml.groovy')
I suggest you also add separate checkboxes or a textfield for the special flags. That way it is clear that the user does not need to add any //
's. In the case of a replace, provide two textfields. This will make your life a lot easier.
Why? Because otherwise some users will add //
's while other will not. And some will make a syntax error. Then, after you stripped the //
's, you may end up with a syntactically valid regex that is nothing like what the user intended, leading to strange behaviour (from the user's perspective).
Works for me-
function querySt(Key) {
var url = window.location.href;
KeysValues = url.split(/[\?&]+/);
for (i = 0; i < KeysValues.length; i++) {
KeyValue= KeysValues[i].split("=");
if (KeyValue[0] == Key) {
return KeyValue[1];
}
}
}
function GetQString(Key) {
if (querySt(Key)) {
var value = querySt(Key);
return value;
}
}
if i want to check if any speicfic position of command line arguement is passed or not then how to check? like for example in some scenarios 2 command line args will be passed and in some only one will be passed then how do it check wheather the specfic commnad line is passed or not?
public class check {
public static void main(String[] args) {
if(args[0].length()!=0)
{
System.out.println("entered first if");
}
if(args[0].length()!=0 && args[1].length()!=0)
{
System.out.println("entered second if");
}
}
}
So in the above code if args[1] is not passed then i get java.lang.ArrayIndexOutOfBoundsException:
so how do i tackle this where i can check if second arguement is passed or not and if passed then enter it. need assistance asap.
It's getElementsByName()
and getElementsByTagName()
- note the "s" in "Elements", indicating that both functions return a list of elements, i.e., a NodeList, which you will access like an array. Note that the second function ends with "TagName" not "Tag".
Even if the function only returns one element it will still be in a NodeList of length one. So:
var els = document.getElementsByName('frmMain');
// els.length will be the number of elements returned
// els[0] will be the first element returned
// els[1] the second, etc.
Assuming your form is the first (or only) form on the page you can do this:
document.getElementsByName('frmMain')[0].elements
document.getElementsByTagName('table')[0].elements
If you can discount transient outages on the remote server you are trying to connect to, then that just leaves the local network config as a problem.
Using the IP address instead of the hostname is only going to work for the default domain on the remote host.
What happens when you try using www.google.com (or its IP address)? If you stil can't connect, then its something to do with the network between your server and the outside world.
Another way could be to use json.dumps(X, sort_keys=True)
option:
import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison
This works for nested dictionaries and lists.
If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:
mat = [[input() for i in range (col)] for j in range (row)]
and then enter the values you want.
$(function() {
$('#clickMe').click(function(event) {
var mytext = $('#myText').val();
$('<div id="dialog">'+mytext+'</div>').appendTo('body');
event.preventDefault();
$("#dialog").dialog({
width: 600,
modal: true,
close: function(event, ui) {
$("#dialog").hide();
}
});
}); //close click
});
Better to use .hide() instead of .remove(). With .remove() it returns undefined if you have pressed the link once, then close the modal and if you press the modal link again, it returns undefined with .remove.
With .hide() it doesnt and it works like a breeze. Ty for the snippet in the first hand!
I had the same problem, because as soon as display: x;
is in animation, it won't animate.
I ended up in creating custom keyframes, first changing the display
value then the other values. May give a better solution.
Or, instead of using display: none;
use position: absolute; visibility: hidden;
It should work.
Remove ALL attributes that say autoplay
as its presence in your tag is a boolean shorthand for true.
Also, make sure you always use video
or audio
elements. Do not use object
or embed
as those elements autoplay using 3rd part plugins by default and cannot be stopped without changing settings in the browser.
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>
and the dtd:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>
First import these:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;
Here are a few variables you will need:
private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;
Here is a reader (String xml is the name of your xml file):
public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);
Element doc = dom.getDocumentElement();
role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;
} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
And here a writer:
public void saveToXML(String xml) {
Document dom;
Element e = null;
// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();
// create the root element
Element rootEle = dom.createElement("roles");
// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);
e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);
e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);
e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));
} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
getTextValue is here:
private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}
Add a few accessors and mutators and you are done!
When you want to return a JSON response in MVC .Net Core You can also use:
Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });
This will return both JSON result and HTTPStatus. I use it for returning results to jQuery.ajax().
you can use BehaviourSubject as described above or there is one more way:
you can handle EventEmitter like this: first add a selector
import {Component, Output, EventEmitter} from 'angular2/core';
@Component({
// other properties left out for brevity
selector: 'app-nav-component', //declaring selector
template:`
<div class="nav-item" (click)="selectedNavItem(1)"></div>
`
})
export class Navigation {
@Output() navchange: EventEmitter<number> = new EventEmitter();
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navchange.emit(item)
}
}
Now you can handle this event like let us suppose observer.component.html is the view of Observer component
<app-nav-component (navchange)="recieveIdFromNav($event)"></app-nav-component>
then in the ObservingComponent.ts
export class ObservingComponent {
//method to recieve the value from nav component
public recieveIdFromNav(id: number) {
console.log('here is the id sent from nav component ', id);
}
}
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see importlib.import_module
for Python 2 and and Python 3.
You can use exec
if you want to as well.
Or using __import__
you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Ripped straight from Dive Into Python.
Why not use TOP X?
SELECT pass1.* FROM
(SELECT TOP 2000000 tblA.ID, tblA.CustomerName
FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL
SELECT pass2.* FROM
(SELECT TOP 2000000 tblB.ID, tblB.CustomerName
FROM TABLE_B AS tblB ORDER BY 2) AS pass2
The TOP 2000000 is an arbitrary number, that is big enough to capture all of the data. Adjust as per your requirements.
var val = $.parseJSON(data);
if(val.success == true)
{
setTimeout(function(){ location.reload(); }, 5000);
}
A background worker is a class that works in a separate thread, but it provides additional functionality that you don't get with a simple Thread (like task progress report handling).
If you don't need the additional features given by a background worker - and it seems you don't - then a Thread would be more appropriate.
You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.
For XLS file: HSSFWorkbook
& HSSFSheet
For XLSX file: XSSFSheet
& XSSFSheet
So in place of XSSFWorkbook
use HSSFWorkbook
and in place of XSSFSheet
use HSSFSheet
.
So your code should look like this after the changes are made:
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
git init
git add .
git commit -m "Initial commit"
git remote add origin <project url>
git push -f origin master
The -f
option on git push
forces the push. If you don't use it, you'll see an error like this:
To [email protected]:roseperrone/project.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to '[email protected]:roseperrone/project.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 merge the remote changes (e.g.,
hint: 'git pull') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
$files = [
'./first.jpg',
'./second.jpg',
'./third.jpg'
];
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
} else {
// File not found.
}
}
Once I updated my Java version to 8 as suggested by browser. However I had selected to uninstall previous Java 6 version I have been used for coding my projects. When I enter the command in "java -version" in cmd it showed 1.8 and I could not start eclipse IDE run on Java 1.6.
When I installed Java 8 update for the browser it had changed the "PATH" System variable appending "C:\ProgramData\Oracle\Java\javapath" to the beginning. Newly added path pointed to Java vesion 8. So I removed that path from "PATH" System variable and everything worked fine. :)
if (str.indexOf(' ') >= 0)
would be (slightly) faster.
DECLARE @tab AS TABLE (col1 VARCHAR(10), col2 varchar(10))
INSERT into @tab EXECUTE sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'
SELECT * FROM @tab
I was able to resolve this very easily my simply enqueuing jQuery
wp_enqueue_script("jquery");
It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.
You can use require as well to render images like
//then in the render function of Jsx insert the mainLogo variable
class NavBar extends Component {
render() {
return (
<nav className="nav" style={nbStyle}>
<div className="container">
//right below here
<img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
</div>
</nav>
);
}
}