The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.
The only difference is that std::endl
flushes the output buffer, and '\n'
doesn't. If you don't want the buffer flushed frequently, use '\n'
. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl
.
This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):
function getXY(evt) {
var element = document.getElementById('elementId'); //replace elementId with your element's Id.
var rect = element.getBoundingClientRect();
var scrollTop = document.documentElement.scrollTop?
document.documentElement.scrollTop:document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft?
document.documentElement.scrollLeft:document.body.scrollLeft;
var elementLeft = rect.left+scrollLeft;
var elementTop = rect.top+scrollTop;
if (document.all){ //detects using IE
x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
y = event.clientY+scrollTop-elementTop;
}
else{
x = evt.pageX-elementLeft;
y = evt.pageY-elementTop;
}
It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.
Some great answers above, using that info here is what I did today to solve the same issue:
$to_array = explode(',', $to);
foreach($to_array as $address)
{
$mail->addAddress($address, 'Web Enquiry');
}
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
How about using Pandas to read the csv file into a DataFrame (pd.read_csv), then manipulating the columns if you want (dropping them or updating values) and finally converting the DataFrame back to JSON (pd.DataFrame.to_json).
Note: I haven't checked how efficient this will be but this is definitely one of the easiest ways to manipulate and convert a large csv to json.
I would just use get_the_post_thumbnail_url()
instead of get_the_post_thumbnail()
<img src="<?php echo get_the_post_thumbnail_url($loop->post->ID); ?>" class="img-responsive" alt=""/>
use the full-featured .ajax
jQuery function.
compare with https://stackoverflow.com/a/3543713/1689451 for an example.
without testing, just merging your code with the referenced SO question:
target = $(this).attr('data-target');
$.ajax({
url: $(this).attr('href'),
type: "GET",
timeout: 2000,
success: function(response) { $(target).modal({
show: true
}); },
error: function(x, t, m) {
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
}
});?
You can do this by comparing each field using the NULL-safe equals operator <=>
and then negating the result using NOT
.
The complete trigger would become:
DROP TRIGGER IF EXISTS `my_trigger_name`;
DELIMITER $$
CREATE TRIGGER `my_trigger_name` AFTER UPDATE ON `my_table_name` FOR EACH ROW
BEGIN
/*Add any fields you want to compare here*/
IF !(OLD.a <=> NEW.a AND OLD.b <=> NEW.b) THEN
INSERT INTO `my_other_table` (
`a`,
`b`
) VALUES (
NEW.`a`,
NEW.`b`
);
END IF;
END;$$
DELIMITER ;
(Based on a different answer of mine.)
I was facing the same problems and found a easy solution now.
Using pathman.
pathman /as %M2%
Adds for example %M2% to the system path. Nothing more and nothing less. No more problems getting a mixture of user PATH and system PATH. No more hardly trying to get the correct values from registry...
Tried at Windows 10
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
Every once and a while the suggestions above stop working, if I restart Visual Studio they start working again though.
I ran into this same issue trying to install the dbf package in Python 2.7. The problem is that the enum package wasn't added to Python until version 3.4.
It has been backported to versions 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4, you just need the package from here: https://pypi.python.org/pypi/enum34#downloads
In C and C++, the &&
and ||
operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to &&
is false, or the first to ||
is true, the rest will not be evaluated.
The code you posted is safe, though I question why you'd include an empty else
block.
You have to define which type of exception you want to catch. So write except Exception, e:
instead of except, e:
for a general exception (that will be logged anyway).
Other possibility is to write your whole try/except code this way:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
logger.error('Failed to upload to ftp: '+ str(e))
in Python 3.x and modern versions of Python 2.x use except Exception as e
instead of except Exception, e
:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
logger.error('Failed to upload to ftp: '+ str(e))
Your have dropped the Project in your workspace, and then trying to import it, that's the problem.
This has two solutions:
1. More your project folder outside your workspace in some other location and then try.
2. Go to File ---> new Project ---> Select the existing project radio button ---> browse to the project folder in your workspace ---> finish
Assume D:\MyDirectory\MyWorkSpace - Path of your WorkSpace
Drop your project which you want to import in Eclipse in MyDirectory folder Not in MyWorkSpace, and try.
Here's my take on it. I needed to create a URL by collecting the value from a text box , when the user presses a Submit button.
<html>_x000D_
<body>_x000D_
_x000D_
Hi everyone_x000D_
_x000D_
<p id="result"></p>_x000D_
_x000D_
<textarea cols="40" id="SearchText" rows="2"></textarea>_x000D_
_x000D_
<button onclick="myFunction()" type="button">Submit!</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
var result = document.getElementById("SearchText").value;_x000D_
document.getElementById("result").innerHTML = result;_x000D_
document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;_x000D_
} _x000D_
</script>_x000D_
_x000D_
_x000D_
<a href="#" id="abc">abc</a>_x000D_
_x000D_
</body>_x000D_
<html>
_x000D_
check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully
After using the wrong quotation mark characters in install.packages()
, correcting the quote marks yielded the "cannot remove prior installation" error. Closing and restarting R worked.
pDialog = new ProgressDialog(this);
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
// Show progressbar
pDialog.show();
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(mVideoView);
Uri videoUri = Uri.parse(videoUrl);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(videoUri);
} catch (Exception e) {
e.printStackTrace();
}
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
finish();
}
});
Get items when the date is between fromdate and toDate.
where convert(date, fromdate, 103 ) <= '2016-07-26' and convert(date, toDate, 103) >= '2016-07-26'
If you're using Twitter Bootstrap styling and base JS for a drop down menu:
.child{ display:none; }
.parent:hover .child{ display:block; }
This is the missing piece to create sticky-dropdowns (that aren't annoying)
I'm running Eclipse Indigo 64 bit on Windows 7 64 bit and I kept getting missing dependency errors associated with Maven and other plugins using the JBoss Tools 3.3.X latest download. Here is the link.
So, I opted to only install Hibernate Tools with nothing else by typing in "hibernate" at the top of the install software dialog in eclipse. Only 4 items showed up, so that is all I installed. It worked fine with no problems. Here is the tutorial that I used to get it installed properly after several failed attempts.
I don't know if part of this was due to having a lot of plugins already installed or if this is the best solution or not, but I thought I'd share it with everyone.
The following will find all product_id that are used more than once. You only get a single record for each product_id.
SELECT product_id FROM oc_product_reward GROUP BY product_id HAVING count( product_id ) >1
Code taken from : http://chandreshrana.blogspot.in/2014/12/find-duplicate-records-based-on-any.html
Yes, simply use something like:
ul {
padding-left: 10px;
}
And it will bump each successive ul
by 10 pixels.
A method group is the name for a set of methods (that might be just one) - i.e. in theory the ToString
method may have multiple overloads (plus any extension methods): ToString()
, ToString(string format)
, etc - hence ToString
by itself is a "method group".
It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.
Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
You should have a look at moment
which is a python port of the excellent js lib momentjs
.
One advantage of it is the support of ISO 8601
strings formats, as well as a generic "% format" :
import moment
time_string='2012-10-09T19:00:55Z'
m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday
Result:
2012-10-09 19:10
2
You can run specific test class(es) and method(s) using the following syntax:
full package : mvn test -Dtest="com.oracle.tests.**"
all method in a class : mvn test -Dtest=CLASS_NAME1
single method from single class :mvn test -Dtest=CLASS_NAME1#METHOD_NAME1
multiple method from multiple class : mvn test -Dtest=CLASS_NAME1#METHOD_NAME1,CLASS_NAME2#METHOD_NAME2
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Sorry for posing this as an answer, but the code block
support in comments is rather limited.)
In VB.NET, you don't even need a variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
(This is paraphrased from the MS Access help files. I'm sure XL has something similar.) Basically, TimerInterval is a form-level property. Once set, use the sub Form_Timer to carry out your intended action.
Sub Form_Load()
Me.TimerInterval = 1000 '1000 = 1 second
End Sub
Sub Form_Timer()
'Do Stuff
End Sub
I am surprised that no one has given reference to Otto event Bus library
I have been using this in my android apps and it works seamlessly.
hm ... use the type of a stylsheet for printing ... eg:
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
print.css:
div { display: none; }
#yourdiv { display: block; }
This is the script I use. A bit tricky but it works. Tested on SQL Server 2012.
DECLARE @backupPath nvarchar(400);
DECLARE @sourceDb nvarchar(50);
DECLARE @sourceDb_log nvarchar(50);
DECLARE @destDb nvarchar(50);
DECLARE @destMdf nvarchar(100);
DECLARE @destLdf nvarchar(100);
DECLARE @sqlServerDbFolder nvarchar(100);
SET @sourceDb = 'db1'
SET @sourceDb_log = @sourceDb + '_log'
SET @backupPath = 'E:\tmp\' + sourceDb + '.bak' --ATTENTION: file must already exist and SQL Server must have access to it
SET @sqlServerDbFolder = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\'
SET @destDb = 'db2'
SET @destMdf = @sqlServerDbFolder + @destDb + '.mdf'
SET @destLdf = @sqlServerDbFolder + @destDb + '_log' + '.ldf'
BACKUP DATABASE @sourceDb TO DISK = @backupPath
RESTORE DATABASE @destDb FROM DISK = @backupPath
WITH REPLACE,
MOVE @sourceDb TO @destMdf,
MOVE @sourceDb_log TO @destLdf
Now that the full screen APIs are more widespread and appear to be maturing, why not try Screenfull.js? I used it for the first time yesterday and today our app goes truly full screen in (almost) all browsers!
Be sure to couple it with the :fullscreen
pseudo-class in CSS. See https://www.sitepoint.com/use-html5-full-screen-api/ for more.
I noticed that almost every solution posted involved ax.imshow(im, ...)
and did not normalize the colors displayed to the colorbar for the multiple subfigures. The im
mappable is taken from the last instance, but what if the values of the multiple im
-s are different? (I'm assuming these mappables are treated in the same way that the contour-sets and surface-sets are treated.) I have an example using a 3d surface plot below that creates two colorbars for a 2x2 subplot (one colorbar per one row). Although the question asks explicitly for a different arrangement, I think the example helps clarify some things. I haven't found a way to do this using plt.subplots(...)
yet because of the 3D axes unfortunately.
If only I could position the colorbars in a better way... (There is probably a much better way to do this, but at least it should be not too difficult to follow.)
import matplotlib
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
cmap = 'plasma'
ncontours = 5
def get_data(row, col):
""" get X, Y, Z, and plot number of subplot
Z > 0 for top row, Z < 0 for bottom row """
if row == 0:
x = np.linspace(1, 10, 10, dtype=int)
X, Y = np.meshgrid(x, x)
Z = np.sqrt(X**2 + Y**2)
if col == 0:
pnum = 1
else:
pnum = 2
elif row == 1:
x = np.linspace(1, 10, 10, dtype=int)
X, Y = np.meshgrid(x, x)
Z = -np.sqrt(X**2 + Y**2)
if col == 0:
pnum = 3
else:
pnum = 4
print("\nPNUM: {}, Zmin = {}, Zmax = {}\n".format(pnum, np.min(Z), np.max(Z)))
return X, Y, Z, pnum
fig = plt.figure()
nrows, ncols = 2, 2
zz = []
axes = []
for row in range(nrows):
for col in range(ncols):
X, Y, Z, pnum = get_data(row, col)
ax = fig.add_subplot(nrows, ncols, pnum, projection='3d')
ax.set_title('row = {}, col = {}'.format(row, col))
fhandle = ax.plot_surface(X, Y, Z, cmap=cmap)
zz.append(Z)
axes.append(ax)
## get full range of Z data as flat list for top and bottom rows
zz_top = zz[0].reshape(-1).tolist() + zz[1].reshape(-1).tolist()
zz_btm = zz[2].reshape(-1).tolist() + zz[3].reshape(-1).tolist()
## get top and bottom axes
ax_top = [axes[0], axes[1]]
ax_btm = [axes[2], axes[3]]
## normalize colors to minimum and maximum values of dataset
norm_top = matplotlib.colors.Normalize(vmin=min(zz_top), vmax=max(zz_top))
norm_btm = matplotlib.colors.Normalize(vmin=min(zz_btm), vmax=max(zz_btm))
cmap = cm.get_cmap(cmap, ncontours) # number of colors on colorbar
mtop = cm.ScalarMappable(cmap=cmap, norm=norm_top)
mbtm = cm.ScalarMappable(cmap=cmap, norm=norm_btm)
for m in (mtop, mbtm):
m.set_array([])
# ## create cax to draw colorbar in
# cax_top = fig.add_axes([0.9, 0.55, 0.05, 0.4])
# cax_btm = fig.add_axes([0.9, 0.05, 0.05, 0.4])
cbar_top = fig.colorbar(mtop, ax=ax_top, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_top)
cbar_top.set_ticks(np.linspace(min(zz_top), max(zz_top), ncontours))
cbar_btm = fig.colorbar(mbtm, ax=ax_btm, orientation='vertical', shrink=0.75, pad=0.2) #, cax=cax_btm)
cbar_btm.set_ticks(np.linspace(min(zz_btm), max(zz_btm), ncontours))
plt.show()
plt.close(fig)
## orientation of colorbar = 'horizontal' if done by column
Answering my own question.
curl -X GET --basic --user username:password \
https://www.example.com/mobile/resource
curl -X DELETE --basic --user username:password \
https://www.example.com/mobile/resource
curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
-d 'param2_name=param2_value' https://www.example.com/mobile/resource
POSTing a file and additional parameter
curl -X POST -F 'param_name=@/filepath/filename' \
-F 'extra_param_name=extra_param_value' --basic --user username:password \
https://www.example.com/mobile/resource
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
// this will give all the forms on the page.
$('form')
// If you know the name of form then.
$('form[name="myFormName"]')
// If you don't know know the name but the position (starts with 0)
$('form:eq(1)') // 2nd form will be fetched.
Make sure Tomcat is not currently running and the PID file is removed. Them you should start Tomcat successfully.
If you start fresh then:
setenv.sh
file in <CATALINA_HOME>/bin
.CATALINA_PID=/tmp/tomcat.pid
(or other directory of your choice) so you have more control over the Tomcat process.Then to start Tomcat find catalina.sh
in <CATALINA_HOME>/bin
and execute:
./catalina.sh start
and to stop it run:
./catalina.sh stop 10 -force
From catalina.sh
script's doc:
./catalina.sh
Usage: catalina.sh ( commands ... )
commands:
start Start Catalina in a separate window
stop Stop Catalina, waiting up to 5 seconds for the process to end
stop n Stop Catalina, waiting up to n seconds for the process to end
stop -force Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running
stop n -force Stop Catalina, wait up to n seconds and then use kill -KILL if still running
Note: If you want to use -force
flag then setting CATALINA_PID
is mandatory.
but.onclick = function() { yourjavascriptfunction();};
or
but.onclick = function() { functionwithparam(param);};
For shortened hex code like #fff or #000
int red = "colorString".charAt(1) == '0' ? 0 :
"colorString".charAt(1) == 'f' ? 255 : 228;
int green =
"colorString".charAt(2) == '0' ? 0 : "colorString".charAt(2) == 'f' ?
255 : 228;
int blue = "colorString".charAt(3) == '0' ? 0 :
"colorString".charAt(3) == 'f' ? 255 : 228;
Color.rgb(red, green,blue);
df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])
df
A B
100 a 54
200 b 67
300 c 89
In [19]:
df.loc[100]
Out[19]:
A a
B 54
Name: 100, dtype: object
In [20]:
df.iloc[0]
Out[20]:
A a
B 54
Name: 100, dtype: object
In [24]:
df2 = df.set_index([df.index,'A'])
df2
Out[24]:
B
A
100 a 54
200 b 67
300 c 89
In [25]:
df2.ix[100, 'a']
Out[25]:
B 54
Name: (100, a), dtype: int64
Neither of the most up-voted answers will reliably return the server's public address. Generally $_SERVER['SERVER_ADDR']
will be correct, but if you're accessing the server via a VPN it will likely return the internal network address rather than a public address, and even when not on the same network some configurations will will simply be blank or have some other specified value.
Likewise, there are scenarios where $host= gethostname(); $ip = gethostbyname($host);
won't return the correct values because it's relying on on both DNS (either internally configured or external records) and the server's hostname settings to extrapolate the server's IP address. Both of these steps are potentially faulty. For instance, if the hostname of the server is formatted like a domain name (i.e. HOSTNAME=yahoo.com
) then (at least on my php5.4/Centos6 setup) gethostbyname
will skip straight to finding Yahoo.com's address rather than the local server's.
Furthermore, because gethostbyname
falls back on public DNS records a testing server with unpublished or incorrect public DNS records (for instance, you're accessing the server by localhost
or IP address, or if you're overriding public DNS using your local hosts
file) then you'll get back either no IP address (it will just return the hostname) or even worse it will return the wrong address specified in the public DNS records if one exists or if there's a wildcard for the domain.
Depending on the situation, you can also try a third approach by doing something like this:
$external_ip = exec('curl http://ipecho.net/plain; echo');
This has its own flaws (relies on a specific third-party site, and there could be network settings that route outbound connections through a different host or proxy) and like gethostbyname
it can be slow. I'm honestly not sure which approach will be correct most often, but the lesson to take to heart is that specific scenarios/configurations will result in incorrect outputs for all of these approaches... so if possible verify that the approach you're using is returning the values you expect.
Inline sample;
public static String strrev(String str) {
return !str.equals("") ? strrev(str.substring(1)) + str.charAt(0) : str;
}
To transfer images from your local Docker installation to a minikube VM:
docker save <image> | (eval $(minikube docker-env) && docker load)
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
Had this issue on my Nexus 7,Nexus 10 & Pixel as well that means in all the emulators.
After days of struggling with this issue, I figured it out finally. Well, there are a lot of answers above which may work or may not for you because their configuration may vary slightly than yours.
I'll tell you my solution:
When creating those emulators, I checked Hardware - GLES 2.0 in Graphics for better performance. And for me it was the issue.
If you've done the same then,
Go to AVD Manager -> Select your emulator -> Click on Edit configuration (in Actions column marked as pencil) -> in Emulated performance - Graphics -> Select Software - GLES 2.0.
Then click on Show Advanced Settings -> Set none for both Front and Back camera
and hit Finish
.
Now select your emulator in AVD Manager and click on Dropdown arrow in Actions column -> select Cold Boot Now
.
And yay you're ready to go
I started Eclipse as admin, and it worked.
I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)
As soon as they view your page that includes the picture or video, the item is downloaded into the temporary folder of their browser. So if you don't want it downloaded, don't post it.
How about this solution:
str="Hello World" (as stated in problem) srr = str+ ""
The command I've used:
find . -type d -name "__pycache__" -exec rm -r {} +
Explains:
First finds all __pycache__
folders in current directory.
Execute rm -r {} +
to delete each folder at step above ({}
signify for placeholder and +
to end the command)
Edited 1:
I'm using Linux, to reuse the command I've added the line below to the ~/.bashrc
file
alias rm-pycache='find . -type d -name "__pycache__" -exec rm -r {} +'
Edited 2:
If you're using VS Code, you don't need to remove __pycache__
manually.
You can add the snippet below to settings.json
file. After that, VS Code will hide all __pycache__
folders for you
"files.exclude": {
"**/__pycache__": true
}
Hope it helps !!!
You can also convert by creating a dictionary of elements and then directly converting to a data frame:
import xml.etree.ElementTree as ET
import pandas as pd
# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags> <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" /> <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" /> <row Id="3" TagName="elicitation" Count="10" /> <row Id="5" TagName="open-source" Count="16" /> </tags>
root = ET.parse('test.xml').getroot()
tags = {"tags":[]}
for elem in root:
tag = {}
tag["Id"] = elem.attrib['Id']
tag["TagName"] = elem.attrib['TagName']
tag["Count"] = elem.attrib['Count']
tags["tags"]. append(tag)
df_users = pd.DataFrame(tags["tags"])
df_users.head()
First you have to get the localVisible rectangle of the view
For eg:
Rect rectf = new Rect();
//For coordinates location relative to the parent
anyView.getLocalVisibleRect(rectf);
//For coordinates location relative to the screen/display
anyView.getGlobalVisibleRect(rectf);
Log.d("WIDTH :", String.valueOf(rectf.width()));
Log.d("HEIGHT :", String.valueOf(rectf.height()));
Log.d("left :", String.valueOf(rectf.left));
Log.d("right :", String.valueOf(rectf.right));
Log.d("top :", String.valueOf(rectf.top));
Log.d("bottom :", String.valueOf(rectf.bottom));
Hope this will help
If you need more information than just the name of the printer you can use the System.Management
API to query them:
var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
var name = printer.GetPropertyValue("Name");
var status = printer.GetPropertyValue("Status");
var isDefault = printer.GetPropertyValue("Default");
var isNetworkPrinter = printer.GetPropertyValue("Network");
Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}",
name, status, isDefault, isNetworkPrinter);
}
I am a retired engineer who grew up with DOS, Fortran, IBM360, etc. in the 60's and like others on this blog I sorely miss the loss of a command line editor in 64-bit Windows. After spending a week browsing the internet and testing editors, I wanted to share my best solution: Notepad++. It's a far cry from DOS EDIT, but there are some side benefits. It is unfortunately a screen editor, requires a mouse, and is consequently slow. On the other hand it is a decent Fortran source editor and has row and column numbers displayed. It can keep multiple tabs for files being edited and even remembers where the cursor was last. I of course keep typing keyboard codes (50 years of habit) but surprisingly at least some of them work. Maybe not a documented feature. I renamed the editor to EDIT.EXE, set up a path to it, and invoke it from command line. It's not too bad. I'm living with it. BTW be careful not to use the tab key in Fortran source. Puts an ASCII 6 in the text. It's invisible and gFortran, at least, can't deal with it. Notepad++ probably has a lot of features that I don't have time to mess with.
This approach, fixed up, will give the correct output (it's highly inefficient, but that's not a problem unless you're scaling up dramatically.)
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length ; j++)
{
if(array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + " occurs " + count);
Console.ReadKey();
}
I counted 5 errors in the OP code, noted below.
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1; // 1. have to put "count" in the inner loop so it gets reset
// 2. have to start count at 0
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++) // 3. have to cover the entire loop
// for (int j=0 ; j<array.Length ; j++)
{
if(array[j] == array[j+1]) // 4. compare outer to inner loop values
// if (array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
// 5. It's spelled "occurs" :)
Console.ReadKey();
}
Edit
For a better approach, use a Dictionary
to keep track of the counts. This allows you to loop through the array just once, and doesn't print duplicate counts to the console.
var counts = new Dictionary<int, int>();
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int currentVal = array[i];
if (counts.ContainsKey(currentVal))
counts[currentVal]++;
else
counts[currentVal] = 1;
}
foreach (var kvp in counts)
Console.WriteLine("\t\n " + kvp.Key + " occurs " + kvp.Value);
The other answers either present a manual string replacement, URLEncoder which actually encodes for HTML format, Apache's abandoned URIUtil, or using Guava's UrlEscapers. The last one is fine, except it doesn't provide a decoder.
Apache Commons Lang provides the URLCodec, which encodes and decodes according to URL format rfc3986.
String encoded = new URLCodec().encode(str);
String decoded = new URLCodec().decode(str);
If you are already using Spring, you can also opt to use its UriUtils class as well.
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
I know this is very late but for future readers ...
Beware of the approaches above that are based only on the name of the class of A, B, C ... :
Unless you can guarantee that A, B, C ... (all subclasses or implementers of Base) are final then subclasses of A, B, C ... will not be dealt with.
Even though the if, elseif, elseif .. approach is slower for large number of subclasses/implementers, it is more accurate.
Actualy the .*?
only works in perl
. I am not sure what the equivalent grep extended regexp syntax would be. Fortunately you can use perl syntax with grep so grep -P
would work but grep -E
which is same as egrep
would not work (it would be greedy).
See also: http://blog.vinceliu.com/2008/02/non-greedy-regular-expression-matching.html
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}
"ABABAB".replace(/B/g, "A");
As always: don't use regex unless you have to. For a simple string replace, the idiom is:
'ABABAB'.split('B').join('A')
Then you don't have to worry about the quoting issues mentioned in Gracenotes's answer.
For this simple use case, you can simply join the strings with comma. If you use Java 8:
String csv = String.join("\t", yourArray);
otherwise commons-lang has a join() method:
String csv = org.apache.commons.lang3.StringUtils.join(yourArray, "\t");
I find this to be the superior solution, at least when dealing with web applications. The idea is this: convert the HTML page to a PDF document and send that to a printer via gsprint
.
Even though gsprint
is no longer in development, it works really, really well. You can choose the printer and the page orientation and size among several other options.
I convert the web page to PDF using Puppeteer, Chrome's headless browser. But you need to pass in the session cookie to maintain credentials.
if you are writing styles in styles.xml then
remove android:inputType property and add below lines
<item name="android:capitalize">words</item>
Add the below to your manifest:
<activity android:name=".AppPreferenceActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
On newer versions of Symfony2 (using a parameters.yml
instead of parameters.ini
), you can store objects or arrays instead of key-value pairs, so you can manage your globals this way:
config.yml (edited only once):
# app/config/config.yml
twig:
globals:
project: %project%
parameters.yml:
# app/config/parameters.yml
project:
name: myproject.com
version: 1.1.42
And then in a twig file, you can use {{ project.version }}
or {{ project.name }}
.
Note: I personally dislike adding things to app
, just because that's the Symfony's variable and I don't know what will be stored there in the future.
Finally, I found a solution to this problem without reinstalling npm and I'm posting it because in future it will help someone, Most of the time this error occurs javascript heap went out of the memory. As the error says itself this is not a problem with npm. Only we have to do is
instead of,
npm run build -prod
extend the javascript memory by following,
node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod
When working with fragments, instead of using this
or refering to the context, always use getActivity()
. You should call
getActivity().finish();
to finish your activity from fragment.
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
In my case the site that I'm connecting to has upgraded to TLS 1.2. As a result I had to install .net 4.5.2 on my web server in order to support it.
if it's inside the transaction, the database locking system will take care of concurrency issues. of course, if you use one (the mssql default is that it uses lock, so it states if you don't override that)
Hope this will help someone. It worked for me -
RestClient client = new RestClient("http://www.example.com/");
RestRequest request = new RestRequest("login", Method.POST);
request.AddHeader("Accept", "application/json");
var body = new
{
Host = "host_environment",
Username = "UserID",
Password = "Password"
};
request.AddJsonBody(body);
var response = client.Execute(request).Content;
Here is a synchronous version without jQuery:
function myRequire( url ) {
var ajax = new XMLHttpRequest();
ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
ajax.onreadystatechange = function () {
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4) {
switch( ajax.status) {
case 200:
eval.apply( window, [script] );
console.log("script loaded: ", url);
break;
default:
console.log("ERROR: script not loaded: ", url);
}
}
};
ajax.send(null);
}
Note that to get this working cross-domain, the server will need to set allow-origin
header in its response.
Here are all the Rails 4 (ActiveRecord migration) datatypes:
:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:bigint
:primary_key
:references
:string
:text
:time
:timestamp
Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column
These are the same as with Rails 3.
If you use PostgreSQL, you can also take advantage of these:
:hstore
:json
:jsonb
:array
:cidr_address
:ip_address
:mac_address
They are stored as strings if you run your app with a not-PostgreSQL database.
Edit, 2016-Sep-19:
There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.
The reason is that the data doesn't match the datatype. I have come across the same issues that I forgot to make the fields match. Though my case is not same as yours, but it shows the similar error message.
The situation is that I copy a table, but accidently I misspell one field, so I change it using the ALTER
after creating the database. And the order of fields in both table is not identical. so when I use the INSERT INTO TableName SELECT * FROM TableName
, the result showed the similar errors: Operand type clash: datetime is incompatible with uniqueidentifier
This is a simiple example:
use example
go
create table Test1 (
id int primary key,
item uniqueidentifier,
inserted_at datetime
)
go
create table Test2 (
id int primary key,
inserted_at datetime
)
go
alter table Test2 add item uniqueidentifier;
go
--insert into Test1 (id, item, inserted_at) values (1, newid(), getdate()), (2, newid(), getdate());
insert into Test2 select * from Test1;
select * from Test1;
select * from Test2;
The error message is:
Msg 206, Level 16, State 2, Line 24
Operand type clash: uniqueidentifier is incompatible with datetime
First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”
In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.
The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
I also faced this issue on a PR that has been merged to the master branch of a GitHub repo.
Since I just wanted to modify some modified files but not the whole changes the PR brought, I had to amend
the merge commit
with git commit --am
.
Steps:
git add *
or git add <file>
git commit --am
and validategit push -f
Why it's interesting:
The currently accepted answer by "Justin Ethier" is not a correct answer as pointed out by "Protector one".
As far as I can see, as of now, no other answer or comment provides the equivalent of BOTTOM(x) the question author asked for.
First, let's consider a scenario where this functionality would be needed:
SELECT * FROM Split('apple,orange,banana,apple,lime',',')
This returns a table of one column and five records:
As you can see: we don't have an ID column; we can't order by the returned column; and we can't select the bottom two records using standard SQL like we can do for the top two records.
Here is my attempt to provide a solution:
SELECT * INTO #mytemptable FROM Split('apple,orange,banana,apple,lime',',')
ALTER TABLE #mytemptable ADD tempID INT IDENTITY
SELECT TOP 2 * FROM #mytemptable ORDER BY tempID DESC
DROP TABLE #mytemptable
And here is a more complete solution:
SELECT * INTO #mytemptable FROM Split('apple,orange,banana,apple,lime',',')
ALTER TABLE #mytemptable ADD tempID INT IDENTITY
DELETE FROM #mytemptable WHERE tempID <= ((SELECT COUNT(*) FROM #mytemptable) - 2)
ALTER TABLE #mytemptable DROP COLUMN tempID
SELECT * FROM #mytemptable
DROP TABLE #mytemptable
I am by no means claiming that this is a good idea to use in all circumstances, but it provides the desired results.
The only solution that works for me (and keeps submodules working) is
git checkout --orphan newBranch
git add -A # Add all files and commit them
git commit
git branch -D master # Deletes the master branch
git branch -m master # Rename the current branch to master
git push -f origin master # Force push master branch to github
git gc --aggressive --prune=all # remove the old files
Deleting .git/
always causes huge issues when I have submodules.
Using git rebase --root
would somehow cause conflicts for me (and take long since I had a lot of history).
Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)
It means "no value". You use void
to indicate that a function doesn't return a value or that it has no parameters or both. Pretty much consistent with typical uses of word void in English.
This line is a problem:
ADD ../../home/ubuntu/.ssh/id_rsa /root/.ssh/id_rsa
When specifying the files you want to copy into the image you can only use relative paths - relative to the directory where your Dockerfile is. So you should instead use:
ADD id_rsa /root/.ssh/id_rsa
And put the id_rsa file into the same directory where your Dockerfile is.
Check this out for more details: http://docs.docker.io/reference/builder/#add
if(isset($_POST['submit']))
{
if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
{
$uname = $_POST['login_username'];
$pass = $_POST['login_password'];
$res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and password='$pass' ";
$query=mysql_query($res)or die (mysql_error());
list($result,$uname,$role) = mysql_fetch_row($query);
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
{
if($result>0)
{
header ('Location:Dashboard.php');
}
else
{
header ('Location:loginform.php');
}
}
If Xcode complains when linking, e.g. Library not found for -lPods, it doesn't detect the implicit dependencies.
Go to Product > Edit Scheme Click on Build Add the Pods static library, and make sure it's at the top of the list Clean and build again If that doesn't work, verify that the source for the spec you are trying to include has been pulled from github. Do this by looking in /Pods/. If it is empty (it should not be), verify that the ~/.cocoapods/master//.podspec has the correct git hub url in it. If still doesn't work, check your XCode build locations settings. Go to Preferences -> Locations -> Derived Data -> Advanced and set build location to “Relative to Workspace”.
If t
is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )
or
x = exp( -t.*t )
Try:
#!/bin/bash
if [ "$#" -eq "0" ]
then
echo "No arguments supplied"
else
echo "Hello world"
fi
For NodeJS
Download required node version msi from here and install
for Npm
Run PowerShell as Administrator
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade
As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.
So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:
Sub MasterMacro()
Call Macro1
Call Macro2
Call Macro3
Call Macro4
End Sub
I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.
Require critical parts, like authorization and include all others.
Multiple includes are just very bad design and must be avoided at all. So, *_once doesn't really matter.
Try this snippet:
jQuery(function($) {
// Your code.
})
It worked for me, maybe it will help you too.
Try this scenario:
Array = A1:C7
. A1-A3
have values, B2-B6
have value and C1
, C3
and C6
have values.
To get a count of the number of rows add a column D
(you can hide it after formulas are set up) and in D1
put formula =If(Sum(A1:C1)>0,1,0)
. Copy the formula from D1
through D7
(for others searching who are not excel literate, the numbers in the sum formula will change to the row you are on and this is fine).
Now in C8
make a sum formula that adds up the D
column and the answer should be 6
. For visually pleasing purposes hide column D
.
git log --oneline | grep PATTERN
StringTokenizer is totally unsuited to the task of breaking a string into its individual characters. With String#split()
you can do that easily by using a regex that matches nothing, e.g.:
String[] theChars = str.split("|");
But StringTokenizer doesn't use regexes, and there's no delimiter string you can specify that will match the nothing between characters. There is one cute little hack you can use to accomplish the same thing: use the string itself as the delimiter string (making every character in it a delimiter) and have it return the delimiters:
StringTokenizer st = new StringTokenizer(str, str, true);
However, I only mention these options for the purpose of dismissing them. Both techniques break the original string into one-character strings instead of char primitives, and both involve a great deal of overhead in the form of object creation and string manipulation. Compare that to calling charAt() in a for loop, which incurs virtually no overhead.
I'm answering on specific to this error code(08s01).
usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".
1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.
2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days
3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.
In netbean Right click on your project, then you click on Libraries, then Run tab, add library, then select mysql connector
Maybe this answer here will help you. Seems that you want to dispose of the context periodically. This is because the context gets bigger and bigger as the attached entities grows.
There are two pages: Pageone.html :
<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>
PageTwo.html :
<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>
Hope it helps!
You can use jade + express:
app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });
above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.
Unlimited string readed:
String content = "";
char character;
while(Serial.available()) {
character = Serial.read();
content.concat(character);
}
if (content != "") {
Serial.println(content);
}
Here's a function from the user comments on the date() function page in the PHP manual. It's an improvement of an earlier function in the comments that adds support for leap years.
Enter the starting and ending dates, along with an array of any holidays that might be in between, and it returns the working days as an integer:
<?php
//The function returns the no. of business days between two dates and it skips the holidays
function getWorkingDays($startDate,$endDate,$holidays){
// do strtotime calculations just once
$endDate = strtotime($endDate);
$startDate = strtotime($startDate);
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = ($endDate - $startDate) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N", $startDate);
$the_last_day_of_week = date("N", $endDate);
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week) {
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else {
// (edit by Tokes to fix an edge case where the start day was a Sunday
// and the end day was NOT a Saturday)
// the day of the week for start is later than the day of the week for end
if ($the_first_day_of_week == 7) {
// if the start date is a Sunday, then we definitely subtract 1 day
$no_remaining_days--;
if ($the_last_day_of_week == 6) {
// if the end date is a Saturday, then we subtract another day
$no_remaining_days--;
}
}
else {
// the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
// so we skip an entire weekend and subtract 2 days
$no_remaining_days -= 2;
}
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
return $workingDays;
}
//Example:
$holidays=array("2008-12-25","2008-12-26","2009-01-01");
echo getWorkingDays("2008-12-22","2009-01-02",$holidays)
// => will return 7
?>
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
For images if your using Web Pages v2 use the WebImage Class
var webImage = new System.Web.Helpers.WebImage(Request.Files[0].InputStream);
byte[] imgByteArray = webImage.GetBytes();
I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.
This class is pretty easy to use. Just create a number as a type of New BaseNumber
, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double
and Long
where ever possible).
I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.
For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.
Public Class BaseNumber
Private _CharacterArray As List(Of Char)
Private _BaseXNumber As String
Private _Base10Number As Double?
Private NumberBaseLow As Integer
Private NumberBaseHigh As Integer
Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator
Public Sub UseCapsLetters()
'http://unicodelookup.com
TrySetBaseSet(65, 90)
End Sub
Public Function GetCharacterArray() As List(Of Char)
Return _CharacterArray
End Function
Public Sub SetCharacterArray(CharacterArray As String)
_CharacterArray = New List(Of Char)
_CharacterArray.AddRange(CharacterArray.ToList)
TrySetBaseSet(_CharacterArray)
End Sub
Public Sub SetCharacterArray(CharacterArray As List(Of Char))
_CharacterArray = CharacterArray
TrySetBaseSet(_CharacterArray)
End Sub
Public Sub SetNumber(Value As String)
_BaseXNumber = Value
_Base10Number = Nothing
End Sub
Public Sub SetNumber(Value As Double)
_Base10Number = Value
_BaseXNumber = Nothing
End Sub
Public Function GetBaseXNumber() As String
If _BaseXNumber IsNot Nothing Then
Return _BaseXNumber
Else
Return ToBaseString()
End If
End Function
Public Function GetBase10Number() As Double
If _Base10Number IsNot Nothing Then
Return _Base10Number
Else
Return ToBase10()
End If
End Function
Private Sub TrySetBaseSet(Values As List(Of Char))
For Each value As Char In _BaseXNumber
If Not Values.Contains(value) Then
Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
_CharacterArray.Clear()
DetermineNumberBase()
End If
Next
_CharacterArray = Values
End Sub
Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)
Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()
If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
_CharacterArray.Clear()
DetermineNumberBase()
End If
NumberBaseLow = LowValue
NumberBaseHigh = HighValue
End Sub
Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
If Values Is Nothing Then
Values = _BaseXNumber.ToList
End If
Dim lowestValue As Integer = Convert.ToInt32(Values(0))
Dim highestValue As Integer = Convert.ToInt32(Values(0))
Dim currentValue As Integer
For Each value As Char In Values
If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
currentValue = Convert.ToInt32(value)
If currentValue > highestValue Then
highestValue = currentValue
End If
If currentValue < lowestValue Then
currentValue = lowestValue
End If
End If
Next
Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)
End Function
Public Sub New(BaseXNumber As String)
_BaseXNumber = BaseXNumber
DetermineNumberBase()
End Sub
Public Sub New(BaseXNumber As String, NumberBase As Integer)
Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
End Sub
Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
_BaseXNumber = BaseXNumber
Me.NumberBaseLow = NumberBaseLow
Me.NumberBaseHigh = NumberBaseHigh
End Sub
Public Sub New(Base10Number As Double)
_Base10Number = Base10Number
End Sub
Private Sub DetermineNumberBase()
Dim highestValue As Integer
Dim currentValue As Integer
For Each value As Char In _BaseXNumber
currentValue = Convert.ToInt32(value)
If currentValue > highestValue Then
highestValue = currentValue
End If
Next
NumberBaseHigh = highestValue
NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest
End Sub
Private Function ToBaseString() As String
Dim Base10Number As Double = _Base10Number
Dim intPart As Long = Math.Truncate(Base10Number)
Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")
Dim intPartString As String = ConvertIntToString(intPart)
Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")
Return intPartString & fracPartString
End Function
Private Function ToBase10() As Double
Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")
Dim intPart As Long = ConvertStringToInt(intPartString)
Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))
Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)
End Function
Private Function ConvertIntToString(ValueToConvert As Long) As String
Dim result As String = String.Empty
Dim targetBase As Long = GetEncodingCharsLength()
Do
result = GetEncodedChar(ValueToConvert Mod targetBase) & result
ValueToConvert = ValueToConvert \ targetBase
Loop While ValueToConvert > 0
Return result
End Function
Private Function ConvertStringToInt(ValueToConvert As String) As Long
Dim result As Long
Dim targetBase As Integer = GetEncodingCharsLength()
Dim startBase As Integer = GetEncodingCharsStartBase()
Dim value As Char
For x As Integer = 0 To ValueToConvert.Length - 1
value = ValueToConvert(x)
result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
Next
Return result
End Function
Private Function GetEncodedChar(index As Integer) As Char
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return _CharacterArray(index)
Else
Return Convert.ToChar(index + NumberBaseLow)
End If
End Function
Private Function GetDecodedChar(character As Char) As Integer
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return _CharacterArray.IndexOf(character)
Else
Return Convert.ToInt32(character) - NumberBaseLow
End If
End Function
Private Function GetEncodingCharsLength() As Integer
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return _CharacterArray.Count
Else
Return NumberBaseHigh - NumberBaseLow + 1
End If
End Function
Private Function GetEncodingCharsStartBase() As Integer
If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
Return GetHighLow.Key
Else
Return NumberBaseLow
End If
End Function
End Class
And now for the code to loop through Excel columns:
Public Function GetColumnList(DataSheetID As String) As List(Of String)
Dim workingColumn As New BaseNumber("A")
workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Dim listOfPopulatedColumns As New List(Of String)
Dim countOfEmptyColumns As Integer
Dim colHasData As Boolean
Dim cellHasData As Boolean
Do
colHasData = True
cellHasData = False
For r As Integer = 1 To GetMaxRow(DataSheetID)
cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
Next
colHasData = colHasData And cellHasData
'keep trying until we get 4 empty columns in a row
If colHasData Then
listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
countOfEmptyColumns = 0
Else
countOfEmptyColumns += 1
End If
'we are already starting with column A, so increment after we check column A
Do
workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
Loop Until Not workingColumn.GetBaseXNumber.Contains("@")
Loop Until countOfEmptyColumns > 3
Return listOfPopulatedColumns
End Function
You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).
I agree with Sam and Xaser and have actually taken this a bit farther. I don't think you should be implementing the INotifyPropertyChanged
interface in a UserControl
at all...the control is already a DependencyObject
and therefore already comes with notifications. Adding INotifyPropertyChanged
to a DependencyObject
is redundant and "smells" wrong to me.
What I did is implement both properties as DependencyProperties
, as Sam suggests, but then simply had the PropertyChangedCallback
from the "first" dependency property alter the value of the "second" dependency property. Since both are dependency properties, both will automatically raise change notifications to any interested subscribers (e.g. data binding etc.)
In this case, dependency property A is the string InviteText
, which triggers a change in dependency property B, the Visibility
property named ShowInvite
. This would be a common use case if you have some text that you want to be able to hide completely in a control via data binding.
public string InviteText
{
get { return (string)GetValue(InviteTextProperty); }
set { SetValue(InviteTextProperty, value); }
}
public static readonly DependencyProperty InviteTextProperty =
DependencyProperty.Register("InviteText", typeof(string), typeof(InvitePrompt), new UIPropertyMetadata(String.Empty, OnInviteTextChanged));
private static void OnInviteTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
InvitePrompt prompt = d as InvitePrompt;
if (prompt != null)
{
string text = e.NewValue as String;
prompt.ShowInvite = String.IsNullOrWhiteSpace(text) ? Visibility.Collapsed : Visibility.Visible;
}
}
public Visibility ShowInvite
{
get { return (Visibility)GetValue(ShowInviteProperty); }
set { SetValue(ShowInviteProperty, value); }
}
public static readonly DependencyProperty ShowInviteProperty =
DependencyProperty.Register("ShowInvite", typeof(Visibility), typeof(InvitePrompt), new PropertyMetadata(Visibility.Collapsed));
Note I'm not including the UserControl
signature or constructor here because there is nothing special about them; they don't need to subclass from INotifyPropertyChanged
at all.
I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.
I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.
Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff
Base ond defualt config of 5.7.5 ONLY_FULL_GROUP_BY You should use all the not aggregate column in your group by
select libelle,credit_initial,disponible_v,sum(montant) as montant
FROM fiche,annee,type
where type.id_type=annee.id_type
and annee.id_annee=fiche.id_annee
and annee = year(current_timestamp)
GROUP BY libelle,credit_initial,disponible_v order by libelle asc
Most of the solutions are working but why take so efforts while we also can get mime type very easily. In System.Web assembly, there is method for getting the mime type from file name. eg:
string mimeType = MimeMapping.GetMimeMapping(filename);
Here is my complete Java code that supports both HTTP and HTTPS requests using SOCKS proxy.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
/**
* How to send a HTTP or HTTPS request via SOCKS proxy.
*/
public class ClientExecuteSOCKS {
public static void main(String[] args) throws Exception {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new MyHTTPConnectionSocketFactory())
.register("https", new MyHTTPSConnectionSocketFactory(SSLContexts.createSystemDefault
()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build()) {
InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);
HttpHost target = new HttpHost("www.example.com/", 80, "http");
HttpGet request = new HttpGet("/");
System.out.println("Executing request " + request + " to " + target + " via SOCKS " +
"proxy " + socksaddr);
try (CloseableHttpResponse response = httpclient.execute(target, request, context)) {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity(), StandardCharsets
.UTF_8));
}
}
}
static class MyHTTPConnectionSocketFactory extends PlainConnectionSocketFactory {
@Override
public Socket createSocket(final HttpContext context) throws IOException {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
}
static class MyHTTPSConnectionSocketFactory extends SSLConnectionSocketFactory {
public MyHTTPSConnectionSocketFactory(final SSLContext sslContext) {
super(sslContext);
}
@Override
public Socket createSocket(final HttpContext context) throws IOException {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
}
}
This is an old post, but this is what works best for me:
A[np.random.choice(A.shape[0], num_rows_2_sample, replace=False)]
change the replace=False to True to get the same thing, but with replacement.
public nameOfTheClass() {
final Container c = this.getContentPane();
public void actionPerformed(ActionEvent e) {
c.setBackground(Color.white);
}
}
When we want to replace the new line character \n
with the space:
xargs < file
xargs
has own limits on the number of characters per line and the number of all characters combined, but we can increase them. Details can be found by running this command: xargs --show-limits
and of course in the manual: man xargs
When we want to replace one character with another exactly one character:
tr '\n' ' ' < file
When we want to replace one character with many characters:
tr '\n' '~' < file | sed s/~/many_characters/g
First, we replace the newline characters \n
for tildes ~
(or choose another unique character not present in the text), and then we replace the tilde characters with any other characters (many_characters
) and we do it for each tilde (flag g
).
You can use a similar construct by using the sys.columns
table io sys.objects
.
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(N'[dbo].[Person]')
AND name = 'ColumnName'
)
To know when and what to escape without attempts is necessary to understand precisely the chain of contexts the string pass through. You will specify the string from the farthest side to its final destination which is the memory handled by the regexp parsing code.
Be aware how the string in memory is processed: if can be a plain string inside the code, or a string entered to the command line, but a could be either an interactive command line or a command line stated inside a shell script file, or inside a variable in memory mentioned by the code, or an (string)argument through further evaluation, or a string containing code generated dynamically with any sort of encapsulation...
Each of this context assigned some characters with special functionality.
When you want to pass the character literally without using its special function (local to the context), than that's the case you have to escape it, for the next context... which might need some other escape characters which might additionally need to be escaped in the preceding context(s). Furthermore there can be things like character encoding (the most insidious is utf-8 because it look like ASCII for common characters, but might be optionally interpreted even by the terminal depending on its settings so it might behave differently, then the encoding attribute of HTML/XML, it's necessary to understand the process precisely right.
E.g. A regexp in the command line starting with perl -npe
, needs to be transferred to a set of exec system calls connecting as pipe the file handles, each of this exec system calls just has a list of arguments that were separated by (non escaped)spaces, and possibly pipes(|) and redirection (> N> N>&M), parenthesis, interactive expansion of *
and ?
, $(())
... (all this are special characters used by the *sh which might appear to interfere with the character of the regular expression in the next context, but they are evaluated in order: before the command line. The command line is read by a program as bash/sh/csh/tcsh/zsh, essentially inside double quote or single quote the escape is simpler but it is not necessary to quote a string in the command line because mostly the space has to be prefixed with backslash and the quote are not necessary leaving available the expand functionality for characters * and ?, but this parse as different context as within quote. Then when the command line is evaluated the regexp obtained in memory (not as written in the command line) receives the same treatment as it would be in a source file.
For regexp there is character-set context within square brackets [ ], perl regular expression can be quoted by a large set of non alfa-numeric characters (E.g. m// or m:/better/for/path: ...).
You have more details about characters in other answer, which are very specific to the final regexp context. As I noted you mention that you find the regexp escape with attempts, that's probably because different context has different set of character that confused your memory of attempts (often backslash is the character used in those different context to escape a literal character instead of its function).
Shouldnt we be using OG?
The chosen answer is good but doesn't work when a site is redirected (very common!), and doesn't return OG tags, which are the new industry standard. Here's a little function which is a bit more usable in 2018. It tries to get OG tags and falls back to meta tags if it cant them:
function getSiteOG( $url, $specificTags=0 ){
$doc = new DOMDocument();
@$doc->loadHTML(file_get_contents($url));
$res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;
foreach ($doc->getElementsByTagName('meta') as $m){
$tag = $m->getAttribute('name') ?: $m->getAttribute('property');
if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = $m->getAttribute('content');
}
return $specificTags? array_intersect_key( $res, array_flip($specificTags) ) : $res;
}
How to use it:
/////////////
//SAMPLE USAGE:
print_r(getSiteOG("http://www.stackoverflow.com")); //note the incorrect url
/////////////
//OUTPUT:
Array
(
[title] => Stack Overflow - Where Developers Learn, Share, & Build Careers
[description] => Stack Overflow is the largest, most trusted online community for developers to learn, shareâ âtheir programming âknowledge, and build their careers.
[type] => website
[url] => https://stackoverflow.com/
[site_name] => Stack Overflow
[image] => https://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded
)
What i did:
I added the following line inside of ROOT/index.jsp
<meta http-equiv="refresh" content="0;url=/somethingelse/index.jsp"/>
Also check the local firewall, service firewalld status
If it's running, just stop it service firewalld stop
And then give it a try.
I experienced the very same problem and it turned out I was on a different (local) branch than I thought I was AND the correct local branch was behind in commits from remote.
My solution: checkout the correct branch, cherry-pick the commit from the other local branch, git pull and git push
ToggleImageButton
which implements Checkable
interface and supports OnCheckedChangeListener
and android:checked
xml attribute:
public class ToggleImageButton extends ImageButton implements Checkable {
private OnCheckedChangeListener onCheckedChangeListener;
public ToggleImageButton(Context context) {
super(context);
}
public ToggleImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
setChecked(attrs);
}
public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChecked(attrs);
}
private void setChecked(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
a.recycle();
}
@Override
public boolean isChecked() {
return isSelected();
}
@Override
public void setChecked(boolean checked) {
setSelected(checked);
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, checked);
}
}
@Override
public void toggle() {
setChecked(!isChecked());
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
public OnCheckedChangeListener getOnCheckedChangeListener() {
return onCheckedChangeListener;
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
}
}
res/values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ToggleImageButton">
<attr name="android:checked" />
</declare-styleable>
</resources>
You can specify the constraints and defaults in a CREATE TABLE AS SELECT, but the syntax is as follows
create table t1 (id number default 1 not null);
insert into t1 (id) values (2);
create table t2 (id default 1 not null)
as select * from t1;
That is, it won't inherit the constraints from the source table/select. Only the data type (length/precision/scale) is determined by the select.
in hibernate 5.x, you should add set hibernate.id.new_generator_mappings to false in hibernate.cfg.xml
<session-factory>
......
<property name="show_sql">1</property>
<property name="hibernate.id.new_generator_mappings">false</property>
......
</session-factory>
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
You can configure your build.gradle file for proguard implementation. It can be at module level or the project level.
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
The configuration shown is for debug level but you can write you own build flavors like shown below inside buildTypes:
myproductionbuild{
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
Better to have your debug with minifyEnabled false
and productionbuild and other builds as minifyEnabled true
.
Copy your proguard-rules.txt file in the root of your module or project folder like
$YOUR_PROJECT_DIR\YoutProject\yourmodule\proguard-rules.txt
You can change the name of your file as you want. After configuration use one of the three options available to generate your build as per the buildType
Go to gradle task in right panel and search for assembleRelease/assemble(#your_defined_buildtype)
under module tasks
Go to Build Variant in Left Panel and select the build from drop down
Go to project root directory in File Explorer and open cmd/terminal and run
Linux ./gradlew assembleRelease or assemble(#your_defined_buildtype)
Windows gradlew assembleRelease or assemble(#your_defined_buildtype)
You can find apk in your module/build directory.
More about the configuration and proguard files location is available at the link
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Running-ProGuard
The safest way to do this is to prompt for the password beforehand and then pipe it into the command. Prompting for the password will avoid having the password saved anywhere in your code and it also won't show up in your bash history. Here's an example:
from getpass import getpass
from subprocess import Popen, PIPE
password = getpass("Please enter your password: ")
# sudo requires the flag '-S' in order to take input from stdin
proc = Popen("sudo -S apach2ctl restart".split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())
compgen -c python | grep -P '^python\d'
This lists some other python things too, But hey, You can identify all python versions among them.
My experience is the same as the benchmarks. Python can be slow and uses more memory. I write much, much less code and it works the first time with much less debugging. Since it manages memory for me, I don't have to do any memory management, saving hours of chasing down core leaks.
What's your question?
Now, sometimes you already have less
open, and you can't use cat
on it. For example, you did a | less
, and you can't just reopen a file, as that's actually a stream.
If all you need is to identify end of line, one easy way is to search for the last character on the line: /.$
. The search will highlight the last character, even if it is a blank, making it easy to identify it.
That will only help with the end of line case. If you need other special characters, you can use the cat -vet
solution above with marks and pipe:
ma
mb
'a
cat -vet
and view the result in another less command: |bcat -vet | less
This will open another less
process, which shows the result of running cat -vet
on the text that lies between marks a and b.
If you want the whole thing, instead, do g|$cat -vet | less
, to go to the first line and filter all lines through cat
.
The advantage of this method over less
options is that it does not mess with the output you see on the screen.
One would think that eight years after this question was originally posted, less
would have that feature... But I can't even see a feature request for it on https://github.com/gwsw/less/issues
If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:
launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"
To directly answer your question, you can add launchctl line in your ~/.bash_profile
As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.
from __future__ import with_statement
try:
with open( "a.txt" ) as f :
print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
print 'oops'
If you want different handling for errors from the open call vs the working code you could do:
try:
f = open('foo.txt')
except IOError:
print('error')
else:
with f:
print f.readlines()
It helps in correct sorting in the case that you will need to concatenate this "integer" with something else (another number or text) which will require to be sorted as a "text" then.
for example,
if you will need to use the integer field numbers (let's say 5) concatenated as A-005 or 10/0005
You could use array_map(), set the first parameter to 'strtolower' (including the quotes) and the second parameter to $lower_case_array.
A safer and more direct way, assuming:
Swift 4.1:
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextTag = textField.tag + 1
guard let nextTextField = textField.superview?.viewWithTag(nextTag) else {
textField.resignFirstResponder()
return false
}
nextTextField.becomeFirstResponder()
return false
}
}
You can also convert your array to a list and call remove on the list. You can then convert back to your array.
int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);
This worked for me:
JSONObject jsonObj = new JSONObject();
jsonObj.put("phonetype","N95");
jsonObj.put("cat","WP");
jsonObj to Hashmap as following using gson
HashMap<String, Object> hashmap = new Gson().fromJson(jsonObj.toString(), HashMap.class);
package used
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
Yahoo is very easy to use and provides customized data. Use the following page to learn more.
finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv
WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.
Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv
I used a version of os.walk
and on a larger directory got times around 3.5 sec. I tried two random solutions with no great improvement, then just did:
paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()]
While it's POSIX-only, I got 0.25 sec.
From this, I believe it's entirely possible to optimise whole searching a lot in a platform-independent way, but this is where I stopped the research.
select * from
(select
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
def skip_elements(elements):
# Initialize variables
i = 0
new_list=elements[::2]
return new_list
# Should be ['a', 'c', 'e', 'g']:
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
# Should be ['Orange', 'Strawberry', 'Peach']:
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
# Should be []:
print(skip_elements([]))
If you use the 'Export Data' wizard there is an option to store the configuration as an 'Integration Services Projects' within the SQL Server database . To edit this package follow the instructions from "mikeTheLiar" but instead of searching for a file make a connection to the database and export package.
From "mikeTheLiar": File->New Project->Integration Services Project - Now in solution explorer there is a SSIS Packages folder, right click it and select "Add Existing Package".
Using the default dialog make a connection to the database and open the export package. The package can now be edited.
Enterprise Architect will build a UML diagram from imported source code.
We solved this issue here at work by applying a .dropup class to the dropdown when the dropdown is close to the bottom of a table.enter image description here
Make sure you don't connect your android device with usb while trying to run the emulator
Looks like its looking for VC compilers, so you could try to mention compiler type with -c mingw32
, since you have msys
python setup.py install -c mingw32
In my case, I had to install an older version of openCV (windows 10, Python 3.6.8)
pip install opencv-python==3.3.0.9
firstly, in your main page use a loading icon
then, delete your </body>
and </HTML>
from your main page and replace it by
<?php include('footer.php');?>
in the footer.php file type :
<?php
$iconPath="myIcon.ico" // myIcon is the final icon
echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
echo '</body>';
echo '</HTML>';
?>
This chunk should do the work:
plot(var2 ~ var1, data=subset(dataframe, var3 < 150))
My best regards.
How this works:
Simple implementation of BST in Python
class TreeNode:
def __init__(self, value):
self.left = None
self.right = None
self.data = value
class Tree:
def __init__(self):
self.root = None
def addNode(self, node, value):
if(node==None):
self.root = TreeNode(value)
else:
if(value<node.data):
if(node.left==None):
node.left = TreeNode(value)
else:
self.addNode(node.left, value)
else:
if(node.right==None):
node.right = TreeNode(value)
else:
self.addNode(node.right, value)
def printInorder(self, node):
if(node!=None):
self.printInorder(node.left)
print(node.data)
self.printInorder(node.right)
def main():
testTree = Tree()
testTree.addNode(testTree.root, 200)
testTree.addNode(testTree.root, 300)
testTree.addNode(testTree.root, 100)
testTree.addNode(testTree.root, 30)
testTree.printInorder(testTree.root)
Here is the minimal code to have a nice looking graph with just 3 lines of code :
from sklearn import tree
import pydotplus
dot_data=tree.export_graphviz(dt,filled=True,rounded=True)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_png('tree.png')
plt.imshow(plt.imread('tree.png'))
I have added the plt.imgshow
to view the graph it Jupyter Notebook. You can ignore it if you are only interested in saving the png file.
I installed the following dependencies:
pip3 install graphviz
pip3 install pydotplus
For MacOs the pip version of Graphviz did not work. Following Graphviz's official documentation I installed it with brew and everything worked fine.
brew install graphviz
I think the shortcut that you're looking for is:
Ctrl+Shift+R on Windows and Linux/Ubuntu
Cmd+Shift+R on Mac OS X
ref: source
Try following code will Add one day to current date
select DateAdd(day, 1, GetDate())
And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function
An easier solution has been outlined here: Validate select box
Make the value be empty and add the required attribute
<select id="select" class="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
//this is the code you have to use in you controller
$config['upload_path'] = './uploads/';
// directory (http://localhost/codeigniter/index.php/your directory)
$config['allowed_types'] = 'gif|jpg|png|jpeg';
//Image type
$config['max_size'] = 0;
// I have chosen max size no limit
$new_name = time() . '-' . $_FILES["txt_file"]['name'];
//Added time function in image name for no duplicate image
$config['file_name'] = $new_name;
//Stored the new name into $config['file_name']
$this->load->library('upload', $config);
if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('production/create_images', $error);
} else {
$upload_data = $this->upload->data();
}
To capture both stdout & stderr from your docker container to a single log file run the following:
docker logs container > container.log 2>&1
use ejs instead of jade
npm install ejs
app.js
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
./routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'ejs' });};
Actually, you can also do it with the iteration method. Because sometimes we might need to use the iteration method instead of the built-in epochs method to visualize the training results after each iteration.
history = [] #Creating a empty list for holding the loss later
for iteration in range(1, 3):
print()
print('-' * 50)
print('Iteration', iteration)
result = model.fit(X, y, batch_size=128, nb_epoch=1) #Obtaining the loss after each training
history.append(result.history['loss']) #Now append the loss after the training to the list.
start_index = random.randint(0, len(text) - maxlen - 1)
print(history)
This way allows you to get the loss you want while maintaining your iteration method.
I had a the same error but for one file. In IntelliJ IDEA I was able to make a copy of the file, then go into the project and delete the file in question, then commit successfully. Then, I made a new file with the same name and copy the contents back into it. I guess you would lose the revision history but it does work.
Create a static member in your Activity class. Then assign the value during the onPostExecute
For example, if the result of your AsyncTask is a String, create a public static string in your Activity
public static String dataFromAsyncTask;
Then, in the onPostExecute
of the AsyncTask, simply make a static call to your main class and set the value.
MainActivity.dataFromAsyncTask = "result blah";
the answer for those with shared hosting. Best to use this little script which I just used to import a 300mb DB file to my server. The script is called Big Dump.
provides a script to import large DB's on resource-limited servers
This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
<input name="files[]" type="file" multiple="multiple" />
PHP part:
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
Use this function to disable right click.You can disable left click and tap also by checking 1 and 0
corresponding
document.onmousedown = rightclickD;
function rightclickD(e)
{
e = e||event;
console.log(e);
if (e.button == 2) {
//alert('Right click disabled!!!');
return false; }
}
Bootstrap 4.0
Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex
, and drop the xs
to allow bootstrap to automatically detect the viewport.
<div class="container-fluid">
<table id="productSizes" class="table">
<thead>
<tr class="d-flex">
<th class="col-1">Size</th>
<th class="col-3">Bust</th>
<th class="col-3">Waist</th>
<th class="col-5">Hips</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-1">6</td>
<td class="col-3">79 - 81</td>
<td class="col-3">61 - 63</td>
<td class="col-5">89 - 91</td>
</tr>
<tr class="d-flex">
<td class="col-1">8</td>
<td class="col-3">84 - 86</td>
<td class="col-3">66 - 68</td>
<td class="col-5">94 - 96</td>
</tr>
</tbody>
</table>
Bootstrap 3.2
Table column width use the same layout as grids do; using col-[viewport]-[size]
. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12
in this example.
<thead>
<tr>
<th class="col-xs-1">Size</th>
<th class="col-xs-3">Bust</th>
<th class="col-xs-3">Waist</th>
<th class="col-xs-5">Hips</th>
</tr>
</thead>
Remember to set the <th>
elements rather than the <td>
elements so it sets the whole column. Here is a working BOOTPLY.
Thanks to @Dan for reminding me to always work mobile view (col-xs-*
) first.
weekText = (EditText) layout.findViewById(R.id.weekEditText);
weekText.setInputType(InputType.TYPE_NULL);
Get rid of the notion of vector entirely
template< typename IT, typename VT>
int index_of(IT begin, IT end, const VT& val)
{
int index = 0;
for (; begin != end; ++begin)
{
if (*begin == val) return index;
}
return -1;
}
This will allow you more flexibility and let you use constructs like
int squid[] = {5,2,7,4,1,6,3,0};
int sponge[] = {4,2,4,2,4,6,2,6};
int squidlen = sizeof(squid)/sizeof(squid[0]);
int position = index_of(&squid[0], &squid[squidlen], 3);
if (position >= 0) { std::cout << sponge[position] << std::endl; }
You could also search any other container sequentially as well.
you can change that using label property in property panel. This screen shot is example that
Maybe you can filter rows by possible columns like this :
DataRow[] filteredRows =
datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));
Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.
In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.
Refer django docs on static files.
In settings.py:
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
Then place your js and css files static folder in your project. Not in media folder.
In views.py:
from django.shortcuts import render_to_response, RequestContext
def view_name(request):
#your stuff goes here
return render_to_response('template.html', locals(), context_instance = RequestContext(request))
In template.html:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>
In urls.py:
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
Project file structure can be found here in imgbin.
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
ioctl(<socketfd>, SIOCGIFCONF, (struct ifconf)&buffer);
Read /usr/include/linux/if.h
for information on the ifconf
and ifreq
structures. This should give you the IP address of each interface on the system. Also read /usr/include/linux/sockios.h
for additional ioctls.
No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.
Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.
More information also in this great answer
The way that worked for me, was to use my external IP Address.
If you don't know what it is, just google What's My IP
Then use your IP address and set this in your domains for the captcha and it should start working ok.
What they mean by non-false is:
return true;
So this code:
var arr = ["one", "two", "three", "four", "five"];_x000D_
$.each(arr, function(i) {_x000D_
if (arr[i] == 'three') {_x000D_
return true;_x000D_
}_x000D_
console.log(arr[i]);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
will log one
, two
, four
, five
.
There is Mozilla official solution: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
(function() {
/**Array*/
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (null === this || undefined === this) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
})();
Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':
yourcode_dir$ pydoc -w original.py no Python documentation found for 'original.py' yourcode_dir$ pydoc -w original wrote original.html
You could read from a blocking queue in one thread and write to it in another thread.
In my case the problem was introduced when I fixed a static analysis error that the return value of a method was not used.
Old working code in my Application.java was:
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
New code that introduced the problem was:
public static void main(String[] args) {
try (ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args)) {
LOG.trace("context: " + context);
}
}
Obviously, the try with resource block will close the context after starting the application which will result in the application exiting with status 0. This was a case where the resource leak error reported by snarqube static analysis should be ignored.
Start Jenkins from cmd line with this command :
java -jar jenkins.war --httpPort=8081
I am using MySQL 5.6 on AWS RDS. I updated following in parameter group.
innodb_file_per_table=1
innodb_file_format = Barracuda
I had to reboot DB instance for parameter group changes to be in effect.
Also, ROW_FORMAT=COMPRESSED was not supported. I used DYNAMIC as below and it worked fine.
ALTER TABLE nombre_tabla ENGINE=InnoDB ROW_FORMAT=DYNAMIC KEY_BLOCK_SIZE=8
export class MyComponent implements OnInit {_x000D_
_x000D_
items: any[] = [_x000D_
{ id: 1, name: 'one' },_x000D_
{ id: 2, name: 'two' },_x000D_
{ id: 3, name: 'three' },_x000D_
{ id: 4, name: 'four' },_x000D_
{ id: 5, name: 'five' },_x000D_
{ id: 6, name: 'six' }_x000D_
];_x000D_
selected: number = 1;_x000D_
_x000D_
constructor() {_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
}_x000D_
_x000D_
selectOption(id: number) {_x000D_
//getted from event_x000D_
console.log(id);_x000D_
//getted from binding_x000D_
console.log(this.selected)_x000D_
}_x000D_
_x000D_
}
_x000D_
<div>_x000D_
<select (change)="selectOption($event.target.value)"_x000D_
[(ngModel)]="selected">_x000D_
<option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>_x000D_
</select>_x000D_
</div>
_x000D_
Adding to DarVar's answer:
git for-each-ref --format='%(committerdate) %09 %(authorname) %09 %(refname)' | sort -k5n -k2M -k3n -k4n | awk '{print $7 $8}'
P.S.: We used AWK to pretty print the author and the remote branch.
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
Sort a two dimensional array based on one column
The first column is a date of format "yyyy.MM.dd HH:mm" and the second column is a String.
Since you say 2-D array, I assume "date of format ..." means a String. Here's code for sorting a 2-D array of String[][]:
import java.util.Arrays;
import java.util.Comparator;
public class Asdf {
public static void main(final String[] args) {
final String[][] data = new String[][] {
new String[] { "2009.07.25 20:24", "Message A" },
new String[] { "2009.07.25 20:17", "Message G" },
new String[] { "2009.07.25 20:25", "Message B" },
new String[] { "2009.07.25 20:30", "Message D" },
new String[] { "2009.07.25 20:01", "Message F" },
new String[] { "2009.07.25 21:08", "Message E" },
new String[] { "2009.07.25 19:54", "Message R" } };
Arrays.sort(data, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
for (final String[] s : data) {
System.out.println(s[0] + " " + s[1]);
}
}
}
Output:
2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E
Jonny 5 beat me to it. I was going to suggest using the \W+
without the \s
as in text.replace(/\W+/g, " ")
. This covers white space as well.
!==
This is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:
a !== b
a !== "2"
4 !== '4'
The first one. Those file paths are relative from where your .gitignore file is.
First Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create a pointer that points to random memory address
*ptr = 20; //Dereference that pointer,
// and assign a value to random memory address.
//Depending on external (not inside your program) state
// this will either crash or SILENTLY CORRUPT another
// data structure in your program.
printf("%d", *ptr); //Print contents of same random memory address
// May or may not crash, depending on who owns this address
return 0;
}
Second Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create pointer to random memory address
int q = 50; //Create local variable with contents int 50
ptr = &q; //Update address targeted by above created pointer to point
// to local variable your program properly created
printf("%d", *ptr); //Happily print the contents of said local variable (q)
return 0;
}
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.
The SSL is not properly configured. Those trustAnchor errors usually mean that the trust store cannot be found. Check your configuration and make sure you are actually pointing to the trust store and that it is in place.
Make sure you have a -Djavax.net.ssl.trustStore
system property set and then check that the path actually leads to the trust store.
You can also enable SSL debugging by setting this system property -Djavax.net.debug=all
. Within the debug output you will notice it states that it cannot find the trust store.
Maybe it is not what you are looking for, but I had a similar problem and i solved it including JSON 2 to my application:
https://github.com/douglascrockford/JSON-js
Other browsers natively implements JSON but IE < 8 (also IE 8 compatibility mode) does not, that's why you need to include it.
Here is a related question: JSON on IE6 (IE7)
UPDATE
the JSON parser has been updated so you should use the new one: http://bestiejs.github.io/json3/