Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.
Breaking this down to a simple answer for .Net core 3.1:
If it is a MSTest project:
rename file in project to testhost.dll.config
OR
Use post-build command provided by DeepSpace101
Select your database and ready to go.
This issue could be because of wrong entity framework reference or sometimes the Class name not matching the entity name in database. Make sure the Table name matches with class name.
I think the problem is from this line:
<context type="GdpSoftware.Server.Data.GdpSoftwareDbContext, GdpSoftware.Server.Data" disableDatabaseInitialization="true">
I don't know why you are using this approach and how it works...
Maybe it's better to try to get it out from web.config and go another way
I have observed a quote '
in your 1st line and also at the end of your last line.
'using System.Collections.Generic;
Is this present in your original code or some formatting mistake?
I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" />
seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.
Just go to Web.Config
from Main
folder, not the one in Views
Folder:
configSections
section name="entityFramework" type="System.Data. .....,Version=" <strong>5</strong>.0.0.0"..
<..>
ADJUST THE VERSION OF EntityFramework you have installed, ex. like Version 6.0.0.0"
I have problem, because I don't add reference to EntityFramework.sqlServer.dll. When I develop program, it works. But when I publish app and install it, it throws error.
I just add reference and Build and Publish again.
Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.
I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.
Here are essential parts of related functions in Start class look like:
ConfigureServices method:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
Configure method:
app.UseCors(MyAllowSpecificOrigins);
Found this from:
You need to update MVC.
DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.
For me in windows server 2012 R2 I solved it by removing the duplicates from web.config file i found this line duplicated twice i removed one line and kept the other line
<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/></handlers><validation validateIntegratedModeConfiguration="false"/>
When this happened to me (out of nowhere) I was about to dive into the top answer above, and then I figured I'd close the project, close Visual Studio, and then re-open everything. Problem solved. VS bug?
The previous answer is correct but I'll give you all the code as well.
Your app.config should look like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ServicesSection" type="RT.Core.Config.ServiceConfigurationSection, RT.Core"/>
</configSections>
<ServicesSection>
<Services>
<add Port="6996" ReportType="File" />
<add Port="7001" ReportType="Other" />
</Services>
</ServicesSection>
</configuration>
Your ServiceConfig
and ServiceCollection
classes remain unchanged.
You need a new class:
public class ServiceConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("Services", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(ServiceCollection),
AddItemName = "add",
ClearItemsName = "clear",
RemoveItemName = "remove")]
public ServiceCollection Services
{
get
{
return (ServiceCollection)base["Services"];
}
}
}
And that should do the trick. To consume it you can use:
ServiceConfigurationSection serviceConfigSection =
ConfigurationManager.GetSection("ServicesSection") as ServiceConfigurationSection;
ServiceConfig serviceConfig = serviceConfigSection.Services[0];
Also, Make sure the "Copy always" option is selected for [log4net].config
The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.
Seems pretty inefficient, but there you go.
I wrote an extension method to encapsulate this:
public static class ConfigurationSectionExtensions
{
public static T GetAs<T>(this ConfigurationSection section)
{
var sectionInformation = section.SectionInformation;
var sectionHandlerType = Type.GetType(sectionInformation.Type);
if (sectionHandlerType == null)
{
throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
}
IConfigurationSectionHandler sectionHandler;
try
{
sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
}
catch (InvalidCastException ex)
{
throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
}
var rawXml = sectionInformation.GetRawXml();
if (rawXml == null)
{
return default(T);
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(rawXml);
return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
}
}
The way you would call it in your example is:
var map = new ExeConfigurationFileMap
{
ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
ConfigurationSettings.AppSettings is deprecated, see here:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx
That said, it should still work.
Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?
Try attaching a debugger and checking the following value:
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
And then opening the configuration file and verifying the section is there as you expected.
I experienced the same issue, and found out that the applicationdeployed was of .NET version 3.5, but the Application pool was using .NET 2.0. That caused the problem you described above. Hope it helps someone.
My error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information
Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x80070021
Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
Config File \\?\C:\inetpub\MyService\web.config
Requested URL http://localhost:80/MyService.svc
Physical Path C:\inetpub\DeployService\DeployService.svc
Logon Method Not yet determined
Logon User Not yet determined
Config Source
101: </modules>
102: <handlers>
103: <remove name="WebServiceHandlerFactory-Integrated"/>
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information
Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x80070021
Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
Config File \\?\C:\inetpub\DeployService\web.config
Requested URL http://localhost:80/DeployService.svc
Physical Path C:\inetpub\DeployService\DeployService.svc
Logon Method Not yet determined
Logon User Not yet determined
Config Source
101: </modules>
102: <handlers>
103: <remove name="WebServiceHandlerFactory-Integrated"/>`
If (as I understand) you're trying to completely block inheritance in the web config of your child application, I suggest you to avoid using the tag in web.config.
Instead create a new apppool and edit the applicationHost.config file (located in %WINDIR%\System32\inetsrv\Config and %WINDIR%\SysWOW64\inetsrv\config).
You just have to find the entry for your apppool and add the attribute enableConfigurationOverride="false"
like in the following example:
<add name="MyAppPool" autoStart="true" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" enableConfigurationOverride="false">
<processModel identityType="NetworkService" />
</add>
This will avoid configuration inheritance in the applications served by MyAppPool.
Matteo
Add a line to your app.config in the configSections element
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...
<log4net configSource="Config\Log4Net.config" />
In your application code, when you create the log, write
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
VSCommands didn't work for me and caused a problem when I installed Visual Studio 2010 aside of Visual Studio 2012.
After some experimentations I found the trick:
Go to HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers
and add an entry with the name "C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe"
and the value "RUNASADMIN"
.
This should solve your issue. I've also blogged about that.
I am using this code. You can also your this for getting city and other details about a Latitude and longitude :
public class getReverseGeoCoding {
private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "";
public void getAddress() {
Address1 = "";
Address2 = "";
City = "";
State = "";
Country = "";
County = "";
PIN = "";
try {
JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Global.curLatitude + ","
+ Global.curLongitude + "&sensor=true&key=YOUR_API_KEY");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject zero = Results.getJSONObject(0);
JSONArray address_components = zero.getJSONArray("address_components");
for (int i = 0; i < address_components.length(); i++) {
JSONObject zero2 = address_components.getJSONObject(i);
String long_name = zero2.getString("long_name");
JSONArray mtypes = zero2.getJSONArray("types");
String Type = mtypes.getString(0);
if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
if (Type.equalsIgnoreCase("street_number")) {
Address1 = long_name + " ";
} else if (Type.equalsIgnoreCase("route")) {
Address1 = Address1 + long_name;
} else if (Type.equalsIgnoreCase("sublocality")) {
Address2 = long_name;
} else if (Type.equalsIgnoreCase("locality")) {
// Address2 = Address2 + long_name + ", ";
City = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
County = long_name;
} else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
State = long_name;
} else if (Type.equalsIgnoreCase("country")) {
Country = long_name;
} else if (Type.equalsIgnoreCase("postal_code")) {
PIN = long_name;
}
}
// JSONArray mtypes = zero2.getJSONArray("types");
// String Type = mtypes.getString(0);
// Log.e(Type,long_name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getAddress1() {
return Address1;
}
public String getAddress2() {
return Address2;
}
public String getCity() {
return City;
}
public String getState() {
return State;
}
public String getCountry() {
return Country;
}
public String getCounty() {
return County;
}
public String getPIN() {
return PIN;
}
}
For more detail on how to get Google Map Api key
JSON PARSER CLASS
public class parser_Json {
public static JSONObject getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}
}
You can get more info from this question : Get the particular address using latitude and longitude
In my case, I use a windows 8.1 (installed jdk1.8.0_77), I did three things:
and voila got it fixed!
Here's where they're stored on Windows XP through Windows Server 2012 R2:
HKEY_CURRENT_USER\Environment
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
This is the solution how I figured out this issue:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null) {
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
Just try to run openssl.exe as administrator.
$('*[data-customerID="22"]');
You should be able to omit the *
, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.
Note that for compatibility with the Selectors API (document.querySelector{,all}
), the quotes around the attribute value (22
) may not be omitted in this case.
Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo')
, and results in a smaller file size after minification (compared to using .attr('data-foo')
).
Starting with Bootstrap v3.3.0 you can use .media-left
and .media-body
<div class="media">
<span class="media-left">
<img src="../site/img/success32.png" alt="...">
</span>
<div class="media-body">
<h3 class="media-heading">Experience</h3>
...
</div>
</div>
Documentation: https://getbootstrap.com/docs/3.3/components/#media
You could try:
<a href="<?php echo $directory ?>">The link to the file</a>
Or for PHP 5.4+ (<?=
is the PHP short echo tag):
<a href="<?= $directory ?>">The link to the file</a>
But your path is relative to the server, don't forget that.
You can use the lower
function:
Guide.where("lower(title)='attack'")
As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.
It's called on Object Literal
I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.
var formObject = {"formObject": [
{"firstName": firstName, "lastName": lastName},
{"phoneNumber": phone},
{"address": address},
]}
Although this seems to make more sense (Why do you have an array in the above literal?):
var formObject = {
firstName: firstName
...
}
Thanks to everyone's contributions to this question, I've come up with the following script. Change the values for $SvcName
and $SvrName
to suit your needs. This script will start the remote service if it is stopped, or stop it if it is started. And it uses the cool .WaitForStatus
method to wait while the service responds.
#Change this values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'remotePC'
#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
'Stopped' {
Write-host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-host "$SvcName is $($svc.status). Taking no action."}
}
if ($WaitForIt -ne "") {
Try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt,'00:02:00')
} Catch {
Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (get-service -computername $SvrName -name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}
Of course, the account you run this under will need the proper privileges to access the remote computer and start and stop services. And when executing this against older remote machines, you might first have to install WinRM 3.0 on the older machine.
Kind of late to the party here, but I have just been struggling with the exact same issue (symptoms) and cursing the lack of error detail reporting. It worked fine on IIS 8+ machines but Win 7 got these INSTANT HTTP 500.19 errors. For me it was as silly as having an unsupported configuration element in the config file:
<applicationInitialization doAppInitAfterRestart="true">
<add initializationPage="/" />
</applicationInitialization>
So while running old web.config files worked fine, I just diffed them and started chopping away at new blocks until I got the page to start loading. Had I seen this as an answer I would have gone this route immediately as I knew none of the popular solutions were relevant. So there you go :)
This is an elegant alternative to sorting the dictionary itself:
As of Swift 4 & 5
let sortedKeys = myDict.keys.sorted()
for key in sortedKeys {
// Ordered iteration over the dictionary
let val = myDict[key]
}
To get the value of cell, use the following syntax,
datagridviewName(columnFirst, rowSecond).value
But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond
approach...
Although the accepted answer is great and it works as it should, I've modified it to split offSet: CGSize
to offsetX: CGFloat
and offsetY: CGFloat
.
extension UIView {
func dropShadow(offsetX: CGFloat, offsetY: CGFloat, color: UIColor, opacity: Float, radius: CGFloat, scale: Bool = true) {
layer.masksToBounds = false
layer.shadowOffset = CGSize(width: offsetX, height: offsetY)
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowRadius = radius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.
Override activity's method onConfigurationChanged
I recently made an extension for collapsing C# code to definitions since I was also missing that feature from Visual Studio. Just look for "Fold to Definitions" and you should find it, or just follow this link.
The repository is public, so you can easily inspect the extension.ts
file and adapt it to other languages. It is nowhere near perfect, but it does the job. It uses regular expressions to find methods, properties, and classes, and then moves the selection to those lines and executes a fold command.
VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.
I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.
As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE()
. This WILL use the index on the log_timestamp column.
SELECT *
FROM some_table
WHERE
log_timestamp
BETWEEN
timestamp(CURRENT_DATE())
AND # Adds 23.9999999 HRS of seconds to the current date
timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));
I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:
SELECT *
FROM some_table
WHERE
log_timestamp >= timestamp(CURRENT_DATE()) AND
log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));
Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.
pip show <package name>
will provide the location for Windows and macOS, and I'm guessing any system. :)
For example:
> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages
Similar to other syntax above but for learning - can you sort by column names?
sort(colnames(test[1:ncol(test)] ))
Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html
dplyr
does the trick
mtcars %>%
arrange(desc(mpg)) %>%
group_by(cyl) %>% slice(1:2)
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
2 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
3 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
5 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
6 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
use this library : Print.JS
with this library you can print both HTML and PDF.
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
Complete View
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete With Latitude & Longitude </title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#pac-input {
background-color: #fff;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function initialize() {
var address = (document.getElementById('pac-input'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
/*********************************************************************/
/* var address contain your autocomplete address *********************/
/* place.geometry.location.lat() && place.geometry.location.lat() ****/
/* will be used for current address latitude and longitude************/
/*********************************************************************/
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('long').innerHTML = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>
There is no unique
method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique)
but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:
In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
d[col] = df[col].unique()
d
Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}
Yes -- use math.nan
.
>>> from math import nan
>>> print(nan)
nan
>>> print(nan + 2)
nan
>>> nan == nan
False
>>> import math
>>> math.isnan(nan)
True
Before Python 3.5, one could use float("nan")
(case insensitive).
Note that checking to see if two things that are NaN are equal to one another will always return false. This is in part because two things that are "not a number" cannot (strictly speaking) be said to be equal to one another -- see What is the rationale for all comparisons returning false for IEEE754 NaN values? for more details and information.
Instead, use math.isnan(...)
if you need to determine if a value is NaN or not.
Furthermore, the exact semantics of the ==
operation on NaN value may cause subtle issues when trying to store NaN inside container types such as list
or dict
(or when using custom container types). See Checking for NaN presence in a container for more details.
You can also construct NaN numbers using Python's decimal module:
>>> from decimal import Decimal
>>> b = Decimal('nan')
>>> print(b)
NaN
>>> print(repr(b))
Decimal('NaN')
>>>
>>> Decimal(float('nan'))
Decimal('NaN')
>>>
>>> import math
>>> math.isnan(b)
True
math.isnan(...)
will also work with Decimal objects.
However, you cannot construct NaN numbers in Python's fractions module:
>>> from fractions import Fraction
>>> Fraction('nan')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 146, in __new__
numerator)
ValueError: Invalid literal for Fraction: 'nan'
>>>
>>> Fraction(float('nan'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\fractions.py", line 130, in __new__
value = Fraction.from_float(numerator)
File "C:\Python35\lib\fractions.py", line 214, in from_float
raise ValueError("Cannot convert %r to %s." % (f, cls.__name__))
ValueError: Cannot convert nan to Fraction.
Incidentally, you can also do float('Inf')
, Decimal('Inf')
, or math.inf
(3.5+) to assign infinite numbers. (And also see math.isinf(...)
)
However doing Fraction('Inf')
or Fraction(float('inf'))
isn't permitted and will throw an exception, just like NaN.
If you want a quick and easy way to check if a number is neither NaN nor infinite, you can use math.isfinite(...)
as of Python 3.2+.
If you want to do similar checks with complex numbers, the cmath
module contains a similar set of functions and constants as the math
module:
cmath.isnan(...)
cmath.isinf(...)
cmath.isfinite(...)
(Python 3.2+)cmath.nan
(Python 3.6+; equivalent to complex(float('nan'), 0.0)
)cmath.nanj
(Python 3.6+; equivalent to complex(0.0, float('nan'))
)cmath.inf
(Python 3.6+; equivalent to complex(float('inf'), 0.0)
)cmath.infj
(Python 3.6+; equivalent to complex(0.0, float('inf'))
)You can show changes that have been staged with the --cached
flag:
$ git diff --cached
In more recent versions of git, you can also use the --staged
flag (--staged
is a synonym for --cached
):
$ git diff --staged
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto
. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
Just use a custom comparator (it's an optional 3rd argument to std::sort
)
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
then you can do this too:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
or even
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
This is one way (SQL2000)
SELECT * FROM
(
SELECT TOP (@pageSize) * FROM
(
SELECT TOP (@pageNumber * @pageSize) *
FROM tableName
ORDER BY columnName ASC
) AS t1
ORDER BY columnName DESC
) AS t2
ORDER BY columnName ASC
and this is another way (SQL 2005)
;WITH results AS (
SELECT
rowNo = ROW_NUMBER() OVER( ORDER BY columnName ASC )
, *
FROM tableName
)
SELECT *
FROM results
WHERE rowNo between (@pageNumber-1)*@pageSize+1 and @pageNumber*@pageSize
If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath()
.
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />
<script src="${pageContext.request.contextPath}/templates/js/main.js"></script>
<script>var base = "${pageContext.request.contextPath}";</script>
</head>
<body>
<a href="${pageContext.request.contextPath}/pages/foo.jsp">link</a>
</body>
If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath}
in every relative link, use the <base>
tag. Here's an example with help of JSTL functions.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
<c:set var="url">${pageContext.request.requestURL}</c:set>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
<link rel="stylesheet" href="templates/style/main.css" />
<script src="templates/js/main.js"></script>
<script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
<a href="pages/foo.jsp">link</a>
</body>
This way every relative link (i.e. not starting with /
or a scheme) will become relative to the <base>
.
This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo
func Rand(n int) (str string) {
b := make([]byte, n)
rand.Read(b)
str = fmt.Sprintf("%x", b)
return
}
You can use
call script.bat
or just
script.bat
There's no need to do this in two commits, you can add the file and mark it executable in a single commit:
C:\Temp\TestRepo>touch foo.sh
C:\Temp\TestRepo>git add foo.sh
C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:
C:\Temp\TestRepo>git update-index --chmod=+x foo.sh
C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
And now the file is mode 0755 (executable).
C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100755 foo.sh
And now we have a single commit with a single executable file.
Adding result for quick reference
window.location;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
document.location
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
window.location.pathname
"/questions/1034621/get-the-current-url-with-javascript"
window.location.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
location.hostname
"stackoverflow.com"
function parameter string value image dynamically from JSON. Since item.product_image2 is a URL string, you need to put it in quotes when you call changeImage inside parameter.
My Function Onclick
items+='<img src='+item.product_image1+' id="saleDetailDivGetImg">';
items+="<img src="+item.product_image2+" onclick='changeImage(\""+item.product_image2+"\");'>";
My Function
<script type="text/javascript">
function changeImage(img)
{
document.getElementById("saleDetailDivGetImg").src=img;
alert(img);
}
</script>
This is cleaner and will put in a csv.
Import-Module ActiveDirectory
$Groups = (Get-AdGroup -filter * | Where {$_.name -like "**"} | select name -expandproperty name)
$Table = @()
$Record = [ordered]@{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\temp\SecurityGroups.csv" -NoTypeInformation
HTML
<div class="close-orange"></div>
CSS
.close-orange {
height: 100px;
width: 100px;
background-color: #FA6900;
border-radius: 5px;
}
.close-orange:before,.close-orange:after{
content:'';
position:absolute;
width: 50px;
height: 4px;
background-color:white;
border-radius:2px;
top: 55px;
}
.close-orange:before{
-webkit-transform:rotate(45deg);
-moz-transform:rotate(45deg);
transform:rotate(45deg);
left: 32.5px;
}
.close-orange:after{
-webkit-transform:rotate(-45deg);
-moz-transform:rotate(-45deg);
transform:rotate(-45deg);
left: 32.5px;
}
I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.
You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula
=$B2>$C2
by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down
Try 'build-essential' instead.
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
Try this:
Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help +extension name Enable extension -extension name Disable extension
borrowed this shamely from here
Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
More information here
Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:
phoneNumber = Regex.Replace(phoneNumber, "\\D", String.Empty);
check if the div exists with a certain class
if ($(".mydivclass").length > 0) //it exists
{
}
git log currentbranch..otherbranch
will give you the list of commits that will go into the current branch if you do a merge. The usual arguments to log which give details on the commits will give you more information.
git diff currentbranch otherbranch
will give you the diff between the two commits that will become one. This will be a diff that gives you everything that will get merged.
Would these help?
int(hexstring, 16)
does the trick, and works with and without the 0x prefix:
>>> int("a", 16)
10
>>> int("0xa", 16)
10
YES
Through macros
3 Parameters:
#define my_func2(...) my_func3(__VA_ARGS__, 0.5)
#define my_func1(...) my_func2(__VA_ARGS__, 10)
#define VAR_FUNC(_1, _2, _3, NAME, ...) NAME
#define my_func(...) VAR_FUNC(__VA_ARGS__, my_func3, my_func2, my_func1)(__VA_ARGS__)
void my_func3(char a, int b, float c) // b=10, c=0.5
{
printf("a=%c; b=%d; c=%f\n", a, b, c);
}
If you want 4th argument, then an extra my_func3 needs to be added. Notice the changes in VAR_FUNC, my_func2 and my_func
4 Parameters:
#define my_func3(...) my_func4(__VA_ARGS__, "default") // <== New function added
#define my_func2(...) my_func3(__VA_ARGS__, (float)1/2)
#define my_func1(...) my_func2(__VA_ARGS__, 10)
#define VAR_FUNC(_1, _2, _3, _4, NAME, ...) NAME
#define my_func(...) VAR_FUNC(__VA_ARGS__, my_func4, my_func3, my_func2, my_func1)(__VA_ARGS__)
void my_func4(char a, int b, float c, const char* d) // b=10, c=0.5, d="default"
{
printf("a=%c; b=%d; c=%f; d=%s\n", a, b, c, d);
}
Only exception that float variables cannot be given default values (unless if it is the last argument as in the 3 parameters case), because they need period ('.'), which is not accepted within macro arguments. But can figure out a work around as seen in my_func2 macro (of 4 parameters case)
Program
int main(void)
{
my_func('a');
my_func('b', 20);
my_func('c', 200, 10.5);
my_func('d', 2000, 100.5, "hello");
return 0;
}
Output:
a=a; b=10; c=0.500000; d=default
a=b; b=20; c=0.500000; d=default
a=c; b=200; c=10.500000; d=default
a=d; b=2000; c=100.500000; d=hello
If your data set is too large first select required rows by Select(). it will stop further looping.
DataRow[] selected = table.Select("Product_id = 2")
Then loop through subset and update
foreach (DataRow row in selected)
{
row["Product_price"] = "<new price>";
}
A good way to have a synthetic view of what's going on "origin" is:
git remote show origin
I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open
, then open
has to be wrapped in a try
. If the call to open
is in the header of a with
, then the with
has to be in a try
to catch the exception. There's no way around that.
So the answer is either: "Tim's way" or "No, you're doing it correctly.".
Previous unhelpful answer to which all the comments refer:
import os
if os.path.exists(fName):
with open(fName, 'rb') as f:
try:
# do stuff
except : # whatever reader errors you care about
# handle error
The easiest way is to make a "fake show" by using jquery.
element.delay(1000).fadeIn(0); // This will work
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.
This program will accept more than one character and output their ASCII value:
using System;
class ASCII
{
public static void Main(string [] args)
{
string s;
Console.WriteLine(" Enter your sentence: ");
s = Console.ReadLine();
foreach (char c in s)
{
Console.WriteLine((int)c);
}
}
}
Using JavaScriptSerializer() is less strict than the generic solution offered : public static T Deserialize(string json)
That might come handy when passing json to the server that does not match exactly the Object definition you are trying to convert to.
Added @TABLE(name = "TABLE_NAME")
annotation and fixed. Check your annotations and hibernate.cfg.xml file. This is the sample entity file that works:
import javax.persistence.*;
@Entity
@Table(name = "VENDOR")
public class Vendor {
//~ --- [INSTANCE FIELDS] ------------------------------------------------------------------------------------------
private int id;
private String name;
//~ --- [METHODS] --------------------------------------------------------------------------------------------------
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Vendor vendor = (Vendor) o;
if (id != vendor.id) {
return false;
}
if (name != null ? !name.equals(vendor.name) : vendor.name != null) {
return false;
}
return true;
}
//~ ----------------------------------------------------------------------------------------------------------------
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public int getId() {
return id;
}
@Basic
@Column(name = "NAME")
public String getName() {
return name;
}
public void setId(final int id) {
this.id = id;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
Perhaps:
Sub dateCNV()
Dim N As Long, r As Range, s As String
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
Set r = Cells(i, "A")
s = r.Text
r.Clear
r.Value = DateSerial(Left(s, 4), Mid(s, 6, 2), Right(s, 2))
Next i
End Sub
This assumes that column A contains text values like 2013-12-25 with no header cell.
With gawk
, you can use match function:
x="hey there how are you"
echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
ere are
If you are ok with perl
, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.
echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how
This can also be applied to words instead of just characters.Following will print one word before the actual matching string.
echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey
Following will print one word after the pattern:
echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how
Following will print one word before the pattern , then the actual word and then one word after the pattern:
echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how
From the docs:
To extract the files from a jar file, use
x
, as in:C:\Java> jar xf myFile.jar
To extract only certain files from a jar file, supply their filenames:
C:\Java> jar xf myFile.jar foo bar
The folder where jar
is probably isn't C:\Java
for you, on my Windows partition it's:
C:\Program Files (x86)\Java\jdk[some_version_here]\bin
Unless the location of jar
is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.
EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html
Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [
and ]
and then split the string
You can create two configs for webpack, one that minifies the code and one that doesn't (just remove the optimize.UglifyJSPlugin line) and then run both configurations at the same time $ webpack && webpack --config webpack.config.min.js
Try that
First place
global $var;
$var = 'value';
Second place
global $var;
if (isset($_POST['save_exit']))
{
echo $var;
}
Or if you want to be more explicit you can use the globals array:
$GLOBALS['var'] = 'test';
// after that
echo $GLOBALS['var'];
And here is third options which has nothing to do with PHP global that is due to the lack of clarity and information in the question. So if you have form in HTML and you want to pass "variable"/value to another PHP script you have to do the following:
HTML form
<form action="script.php" method="post">
<input type="text" value="<?php echo $var?>" name="var" />
<input type="submit" value="Send" />
</form>
PHP script ("script.php")
<?php
$var = $_POST['var'];
echo $var;
?>
It's a bug in Managed ODP.net - 'Bug 21113901 : MANAGED ODP.NET RAISE ORA-1008 USING SINGLE QUOTED CONST + BIND VAR IN SELECT' fixed in patch 23530387 superseded by patch 24591642
Component code:
import { Component } from "@angular/core";
@Component({
templateUrl:"home.html"
})
export class HomePage {
public items: Array<string>;
constructor() {
this.items = ["item1", "item2", "item3"]
}
public open(event, item) {
alert('Open ' + item);
}
}
View:
<ion-header>
<ion-navbar primary>
<ion-title>
<span>My App</span>
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let item of items" (click)="open($event, item)">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)"
and sending both the event and the item (declared in the *ngFor
) to the open()
method (declared in the component code).
If you just want to show the item and you don't need to get info from the event, you can just do (click)="open(item)"
and modify the open
method like this public open(item) { ... }
Try the following (note that there should not be a space between the VAR
, =
, and GREG
).
SET VAR=GREG
ECHO %VAR%
PAUSE
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
def f(x) -> 123:
return x
My summary:
Simply ->
is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107
This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.
You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.
You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.
I tried using:
Range(cells(1, 1), cells(lastRow, lastColumn)).Select
where lastRow
and lastColumn
are integers, but received run-time error 1004. I'm using an older VB (6.5).
What did work was to use the following:
Range(Chr(64 + firstColumn) & firstRow & ":" & Chr(64 + lastColumn) & firstColumn).Select.
if you would use octave you could do it like this - but sadly matlab does not support this possibility
function hello (who = "World")
printf ("Hello, %s!\n", who);
endfunction
(taken from the doc)
Here's an extension to find the nearest vector in an array of vectors.
import numpy as np
def find_nearest_vector(array, value):
idx = np.array([np.linalg.norm(x+y) for (x,y) in array-value]).argmin()
return array[idx]
A = np.random.random((10,2))*100
""" A = array([[ 34.19762933, 43.14534123],
[ 48.79558706, 47.79243283],
[ 38.42774411, 84.87155478],
[ 63.64371943, 50.7722317 ],
[ 73.56362857, 27.87895698],
[ 96.67790593, 77.76150486],
[ 68.86202147, 21.38735169],
[ 5.21796467, 59.17051276],
[ 82.92389467, 99.90387851],
[ 6.76626539, 30.50661753]])"""
pt = [6, 30]
print find_nearest_vector(A,pt)
# array([ 6.76626539, 30.50661753])
Alternatively to usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard defines nanosleep()
:
nanosleep
- high resolution sleep#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
The
nanosleep()
function shall cause the current thread to be suspended from execution until either the time interval specified by therqtp
argument has elapsed or a signal is delivered to the calling thread, and its action is to invoke a signal-catching function or to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified byrqtp
, as measured by the system clock CLOCK_REALTIME.The use of the
nanosleep()
function has no effect on the action or blockage of any signal.
simple answer:
let str = 'this is string, length is >26';_x000D_
_x000D_
console.log([...str]);
_x000D_
In linear regression, the outcome (dependent variable) is continuous. It can have any one of an infinite number of possible values. In logistic regression, the outcome (dependent variable) has only a limited number of possible values.
For instance, if X contains the area in square feet of houses, and Y contains the corresponding sale price of those houses, you could use linear regression to predict selling price as a function of house size. While the possible selling price may not actually be any, there are so many possible values that a linear regression model would be chosen.
If, instead, you wanted to predict, based on size, whether a house would sell for more than $200K, you would use logistic regression. The possible outputs are either Yes, the house will sell for more than $200K, or No, the house will not.
LEFT OUTER JOIN
SELECT * FROM A, B WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT * FROM A, B WHERE A.column (+)= B.column
valid json string must have double quote.
JSON.parse({"u1":1000,"u2":1100}) // will be ok
no quote cause error
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
single quote cause error
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
You must valid json string at https://jsonlint.com
I tested in my version on PyCharm 2017.1.2. I used interactive (True) and show (block=True).
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1//2000',periods=1000))
ts = ts.cumsum()
plt.interactive(True)
ts.plot()
plt.show(block=True)
For a simple use of slice
, use my extension to Array Class:
Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};
Then:
var bigArr = ["a", "b", "c", "fd", "ze"];
Test1:
bigArr.subarray(1, -1);
< ["b", "c", "fd", "ze"]
Test2:
bigArr.subarray(2, -2);
< ["c", "fd"]
Test3:
bigArr.subarray(2);
< ["c", "fd","ze"]
Might be easier for developers coming from another language (i.e. Groovy).
Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .
$('html').on('keydown' , function(event) {
if(! $(event.target).is('input')) {
console.log(event.which);
//event.preventDefault();
if(event.which == 8) {
// alert('backspace pressed');
return false;
}
}
});
returning false => both event.preventDefault and event.stopPropagation are in effect .
\path-to-your-android-sdk-folder\platforms\android-xx\data\res
if you are already using jQuery in your build just do this:
$(yourObject).length
It works nicely for me on objects, and I already had jQuery as a dependancy.
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
Using Hamcrest:
assertThat( set1, both(everyItem(isIn(set2))).and(containsInAnyOrder(set1)));
This works also when the sets have different datatypes, and reports on the difference instead of just failing.
I was stuck trying to implement this in typescript, all of the above would not work. I had to first cast the element in order for typescript to have access to the contentWindow.
let iframe = document.getElementById('frameId') as HTMLIFrameElement;
iframe.contentWindow.print();
If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag
<body oncontextmenu="return false;">
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well)
However, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.
This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.
When already given posts answer the question, I made a small change by adding the column name on which the max() function is applied for better code readability.
df.groupby('A', as_index=False)['B'].max()
//Disable a search on particular selector
$(".my_selector").select2({
placeholder: "ÁREAS(todas)",
tags: true,
width:'100%',
containerCssClass: "area_disable_search_input" // I add new class
});
//readonly prop to selector class
$(".area_disable_search_input input").prop("readonly", true);
In this case no conditionals are needed to set the variable.
This one-liner XPath expression:
boolean(joined-subclass)
is true()
only when the child of the current node, named joined-subclass
exists and it is false()
otherwise.
The complete stylesheet is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="class">
<xsl:variable name="subexists"
select="boolean(joined-subclass)"
/>
subexists: <xsl:text/>
<xsl:value-of select="$subexists" />
</xsl:template>
</xsl:stylesheet>
Do note, that the use of the XPath function boolean()
in this expression is to convert a node (or its absense) to one of the boolean values true()
or false()
.
Here are the commands I use to get the contents of the queue:
RabbitMQ version 3.1.5 on Fedora linux using https://www.rabbitmq.com/management-cli.html
Here are my exchanges:
eric@dev ~ $ sudo python rabbitmqadmin list exchanges
+-------+--------------------+---------+-------------+---------+----------+
| vhost | name | type | auto_delete | durable | internal |
+-------+--------------------+---------+-------------+---------+----------+
| / | | direct | False | True | False |
| / | kowalski | topic | False | True | False |
+-------+--------------------+---------+-------------+---------+----------+
Here is my queue:
eric@dev ~ $ sudo python rabbitmqadmin list queues
+-------+----------+-------------+-----------+---------+------------------------+---------------------+--------+----------+----------------+-------------------------+---------------------+--------+---------+
| vhost | name | auto_delete | consumers | durable | exclusive_consumer_tag | idle_since | memory | messages | messages_ready | messages_unacknowledged | node | policy | status |
+-------+----------+-------------+-----------+---------+------------------------+---------------------+--------+----------+----------------+-------------------------+---------------------+--------+---------+
| / | myqueue | False | 0 | True | | 2014-09-10 13:32:18 | 13760 | 0 | 0 | 0 |rabbit@ip-11-1-52-125| | running |
+-------+----------+-------------+-----------+---------+------------------------+---------------------+--------+----------+----------------+-------------------------+---------------------+--------+---------+
Cram some items into myqueue:
curl -i -u guest:guest http://localhost:15672/api/exchanges/%2f/kowalski/publish -d '{"properties":{},"routing_key":"abcxyz","payload":"foobar","payload_encoding":"string"}'
HTTP/1.1 200 OK
Server: MochiWeb/1.1 WebMachine/1.10.0 (never breaks eye contact)
Date: Wed, 10 Sep 2014 17:46:59 GMT
content-type: application/json
Content-Length: 15
Cache-Control: no-cache
{"routed":true}
RabbitMQ see messages in queue:
eric@dev ~ $ sudo python rabbitmqadmin get queue=myqueue requeue=true count=10
+-------------+----------+---------------+---------------------------------------+---------------+------------------+------------+-------------+
| routing_key | exchange | message_count | payload | payload_bytes | payload_encoding | properties | redelivered |
+-------------+----------+---------------+---------------------------------------+---------------+------------------+------------+-------------+
| abcxyz | kowalski | 10 | foobar | 6 | string | | True |
| abcxyz | kowalski | 9 | {'testdata':'test'} | 19 | string | | True |
| abcxyz | kowalski | 8 | {'mykey':'myvalue'} | 19 | string | | True |
| abcxyz | kowalski | 7 | {'mykey':'myvalue'} | 19 | string | | True |
+-------------+----------+---------------+---------------------------------------+---------------+------------------+------------+-------------+
There are multiple ways to do this and from your question it's nor clear what you need.
1. If you need environment variable to be defined PER TASK ONLY, you do this:
- hosts: dev tasks: - name: Echo my_env_var shell: "echo $MY_ENV_VARIABLE" environment: MY_ENV_VARIABLE: whatever_value - name: Echo my_env_var again shell: "echo $MY_ENV_VARIABLE"
Note that MY_ENV_VARIABLE
is available ONLY for the first task, environment
does not set it permanently on your system.
TASK: [Echo my_env_var] *******************************************************
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}
TASK: [Echo my_env_var again] *************************************************
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}
Hopefully soon using environment
will also be possible on play level, not only task level as above.
There's currently a pull request open for this feature on Ansible's GitHub: https://github.com/ansible/ansible/pull/8651
UPDATE: It's now merged as of Jan 2, 2015.
2. If you want permanent environment variable + system wide / only for certain user
You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:
~/.profile
/etc/environment
/etc/profile.d
directoryYou will find Ubuntu docs about it here: https://help.ubuntu.com/community/EnvironmentVariables
After all for setting environment variable in ex. Ubuntu you can just use lineinfile
module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.
I think you are trying to toggle the disabled state, in witch case you should use this (from this question):
$(".inputDisabled").prop('disabled', function (_, val) { return ! val; });
This for sure is an old topic but I want to add up to the voices to crop maybe new ideas. To address the WARNING issue under discussions, all you need to do is to set one of your table columns to a PRIMARY KEY constraint.
When i modify the font size in Tools-> Options->Fonts & Colors->Syntax
to 14, the Editor font change fine, but Netbeans doesn´t take any change in fontsize IDE (icons, menus, ...) until i Add the --fontsize XX
option in the file ...\NetBeans x.x\etc\netbeans.conf at the end of line netbeans_default_options
AND set to true the already added option -J-Dsun.java2d.dpiaware
, But i had to increase the font size Editor to 24. Thats works for me.
Here's something I've come up with while trying to find most simple solution for this problem, perhaps it could be useful to someone. I'm new to javascript, so there might well be some issues with the code.
// pseudo-class definition scope
(function () {
// this is used to identify 'friend' functions defined within this scope,
// while not being able to forge valid parameter for GetContext()
// to gain 'private' access from outside
var _scope = new (function () { })();
// -----------------------------------------------------------------
// pseudo-class definition
this.Something = function (x) {
// 'private' members are wrapped into context object,
// it can be also created with a function
var _ctx = Object.seal({
// actual private members
Name: null,
Number: null,
Somefunc: function () {
console.log('Something(' + this.Name + ').Somefunc(): number = ' + this.Number);
}
});
// -----------------------------------------------------------------
// function below needs to be defined in every class
// to allow limited access from prototype
this.GetContext = function (scope) {
if (scope !== _scope) throw 'access';
return _ctx;
}
// -----------------------------------------------------------------
{
// initialization code, if any
_ctx.Name = (x !== 'undefined') ? x : 'default';
_ctx.Number = 0;
Object.freeze(this);
}
}
// -----------------------------------------------------------------
// prototype is defined only once
this.Something.prototype = Object.freeze({
// public accessors for 'private' field
get Number() { return this.GetContext(_scope).Number; },
set Number(v) { this.GetContext(_scope).Number = v; },
// public function making use of some private fields
Test: function () {
var _ctx = this.GetContext(_scope);
// access 'private' field
console.log('Something(' + _ctx.Name + ').Test(): ' + _ctx.Number);
// call 'private' func
_ctx.Somefunc();
}
});
// -----------------------------------------------------------------
// wrap is used to hide _scope value and group definitions
}).call(this);
function _A(cond) { if (cond !== true) throw new Error('assert failed'); }
// -----------------------------------------------------------------
function test_smth() {
console.clear();
var smth1 = new Something('first'),
smth2 = new Something('second');
//_A(false);
_A(smth1.Test === smth2.Test);
smth1.Number = 3;
smth2.Number = 5;
console.log('smth1.Number: ' + smth1.Number + ', smth2.Number: ' + smth2.Number);
smth1.Number = 2;
smth2.Number = 6;
smth1.Test();
smth2.Test();
try {
var ctx = smth1.GetContext();
} catch (err) {
console.log('error: ' + err);
}
}
test_smth();
Yes it is! Just add them to your database-folder ( depending on the OS ) and run a command such as "MySQL Fix Permissions". This re-stored the database. See too it that the correct permissions are set on the files aswell.
The continue
keyword will do what you are after. break
will exit out of the foreach
loop, so you'll want to avoid that.
If you want your button to call the routine you have written in filename.js you have to edit filename.js so that the code you want to run is the body of a function. For you can call a function, not a source file. (A source file has no entry point)
If the current content of your filename.js is:
alert('Hello world');
_x000D_
you have to change it to:
function functionName(){_x000D_
alert('Hello world');_x000D_
}
_x000D_
Then you have to load filename.js in the header of your html page by the line:
<head>_x000D_
<script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
</head>
_x000D_
so that you can call the function contained in filename.js by your button:
<button onclick="functionName()">Call the function</button>
_x000D_
I have made a little working example. A simple HTML page asks the user to input her name, and when she clicks the button, the function inside Public/Scripts/filename.js is called passing the inserted string as a parameter so that a popup says "Hello, <insertedName>!".
Here is the calling HTML page:
<html>_x000D_
_x000D_
<head>_x000D_
<script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
What's your name? <input id="insertedName" />_x000D_
<button onclick="functionName(insertedName.value)">Say hello</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
And here is Public/Scripts/filename.js
function functionName( s ){_x000D_
alert('Hello, ' + s + '!');_x000D_
}
_x000D_
I had the same problem, and it came from a wrong client_id / Facebook App ID.
Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.
You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.
Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:
Valid OAuth redirect URIs : example.com/
Note that if you have committed a bunch of changes in various submodules, you can (or will be soon able to) push everything in one go (ie one push from the parent repo), with:
git push --recurse-submodules=on-demand
git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
--recurse-submodules=<check|on-demand|no>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
Try this command:
@echo off
cls
:loop
echo RAINBOW
color 0
echo RAINBOW
color 1
echo RAINBOW
color 2
echo RAINBOW
color 3
echo RAINBOW
color 4
echo RAINBOW
color 5
echo RAINBOW
color 6
echo RAINBOW
color 8
echo RAINBOW
color 9
echo RAINBOW
color A
echo RAINBOW
color B
echo RAINBOW
color C
echo RAINBOW
color D
echo RAINBOW
color E
echo RAINBOW
goto loop
This should create color changing text go in a loop.
Edit: You can change the words rainbow to whatever you want.
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding
(or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:
sys.stdout.buffer.write(some_bytes_object)
This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.
You can also use an object-oriented path with pathlib
(available as a standard library as of Python 3.4):
from pathlib import Path
start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'
Try this:
String str = "5 * x^3 - 6 * x^1 + 1";
String replacedStr = str.replaceAll("\\^(\\d+)", "<sup>\$1</sup>");
Be sure to import java.util.regex.
Check if you mixed tabs and spaces, that is a frequent source of indentation errors.
Yes, c[i]=''
is not a valid code. We parenthesis character constant between '
'
, e.g. c[i] = 'A';
char A
. but you don't write any char in between ''
.
Empty space is nothing but suppose if you wants to assigned space then do:
c[i] = ' ';
// ^ space
if wants to assigned nul char
then do:
c[i] = '\0';
// ^ null symbol
Example: Suppose if c[]
a string (nul \0
terminated char array) if you having a string. for example:
char c[10] = {'a', '2', 'c', '\0'};
And you replace second char with space:
c[1] = ' ';
and if you print it using printf as follows:
printf("\n c: %s", c);
then output would be:
c: a c
// ^ space printed
And you replace second char with '\0':
c[1] = '\0';
then output would be:
c: a
because string terminated with \0
.
Converting to double can be done by casting an int to a double:
You can convert an int to a double by using this mechnism like so:
int i = 3; // i is 3
double d = (double) i; // d = 3.0
Alternative (using Java's automatic type recognition):
double d = 1.0 * i; // d = 3.0
Implementing this in your code would be something like:
double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));
Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:
double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));
Good luck.
.blink_text {_x000D_
_x000D_
animation:1s blinker linear infinite;_x000D_
-webkit-animation:1s blinker linear infinite;_x000D_
-moz-animation:1s blinker linear infinite;_x000D_
_x000D_
color: red;_x000D_
}_x000D_
_x000D_
@-moz-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
@keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}
_x000D_
<span class="blink_text">India's Largest portal</span>
_x000D_
To make sed
catch from stdin , instead of from a file, you should use -e
.
Like this:
curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk 'BEGIN{FS=":"} {print $4}'
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
If you don't mind using an external library, I've used Castor to do this in the past.
!important
, after your CSS declaration.
div {
color: blue !important;
/* This Is Now Working */
}
(Linux/WSL at least) From the browser at bitbucket.org, create an empty repo with the same name as your local repo, follow the instructions proposed by bitbucket for importing a local repo (two commands to type).
Option 1:
You can set CMake variables at command line like this:
cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt
See this to learn how to create a CMake cache entry.
Option 2:
In your shell script build_ios.sh
you can set environment variables CC
and CXX
to point to your C and C++ compiler executable respectively, example:
export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt
Option 3:
Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project()
or enable_language()
command)
set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")
See this to learn how to use set
command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.
Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler
One point I noticed with Primefaces 3.4 and Netbeans 7.2:
Remove the Netbeans auto-filled parameters for function handleFileUpload i.e. (event) otherwise event could be null.
<h:form>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload(event)}"
mode="advanced"
update="messages"
sizeLimit="100000"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
</h:form>
A quick definition of the "permanent generation":
"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]
In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space
if an application loads a large number of classes and/or on redeployment).
Note that PermSize
is additional to the -Xmx
value set by the user on the JVM options. But MaxPermSize
allows for the JVM to be able to grow the PermSize
to the amount specified. Initially when the VM is loaded, the MaxPermSize
will still be the default value (32mb for -client
and 64mb for -server
) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize
and MaxPermSize
to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx
setting.
Old question, but an easy way is to:
Below batch "program" should do what you want. Please note that it outputs the data in centiseconds instead of milliseconds. The precision of the used commands is only centiseconds.
Here is an example output:
STARTTIME: 13:42:52,25
ENDTIME: 13:42:56,51
STARTTIME: 4937225 centiseconds
ENDTIME: 4937651 centiseconds
DURATION: 426 in centiseconds
00:00:04,26
Here is the batch script:
@echo off
setlocal
rem The format of %TIME% is HH:MM:SS,CS for example 23:59:59,99
set STARTTIME=%TIME%
rem here begins the command you want to measure
dir /s > nul
rem here ends the command you want to measure
set ENDTIME=%TIME%
rem output as time
echo STARTTIME: %STARTTIME%
echo ENDTIME: %ENDTIME%
rem convert STARTTIME and ENDTIME to centiseconds
set /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
set /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
rem calculating the duratyion is easy
set /A DURATION=%ENDTIME%-%STARTTIME%
rem we might have measured the time inbetween days
if %ENDTIME% LSS %STARTTIME% set set /A DURATION=%STARTTIME%-%ENDTIME%
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A DURATIONH=%DURATION% / 360000
set /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
set /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
set /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
rem some formatting
if %DURATIONH% LSS 10 set DURATIONH=0%DURATIONH%
if %DURATIONM% LSS 10 set DURATIONM=0%DURATIONM%
if %DURATIONS% LSS 10 set DURATIONS=0%DURATIONS%
if %DURATIONHS% LSS 10 set DURATIONHS=0%DURATIONHS%
rem outputing
echo STARTTIME: %STARTTIME% centiseconds
echo ENDTIME: %ENDTIME% centiseconds
echo DURATION: %DURATION% in centiseconds
echo %DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
endlocal
goto :EOF
Try the following
download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
Unzip the file and Run intelhaxm-android.exe.
Run silent_install.bat.
In my computer Win10 x64 - VS2015 it worked
I see many (all) posts above relying on LBound
/UBound
calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...
Erratic code:
Dim x As Long
Dim arr1() As SomeType
...
x = UBound(arr1) 'crashes
Correct code:
Dim x As Long
Dim arr1() As SomeType
...
ReDim Preserve arr1(0 To 0)
...
x = UBound(arr1)
... i.e. any code where Dim arr1()
is followed immediatelly by LBound(arr1)
/UBound(arr1)
calls without ReDim arr1(...)
in between, crashes. The roundabout is to employ an On Error Resume Next
and check the Err.Number
right after the LBound(arr1)
/UBound(arr1)
call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)
Heh, that's my first post, believe it is legible.
For the most accurate rounding, create this function:
function round(value, decimals) {
return Number(Math.round(value +'e'+ decimals) +'e-'+ decimals).toFixed(decimals);
}
and use it to round to 2 decimal places:
console.log("seeked to " + round(1.005, 2));
> 1.01
Thanks to Razu, this article, and MDN's Math.round reference.
Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.
Your best bet is to use a framework that already has this functionality ready and tested for you.
Some suggestions are:
Phalcon - REST API building - Easy to use all in one framework with huge performance
Apigility - A one size fits all API handling framework by Zend Technologies
Laravel API Building Tutorial
and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.
This is how I solved by creating an ic_launcher from a PNG image.
I converted a PNG image into SVG image by using this website https://image.online-convert.com/convert-to-svg.
I used the converted SVG image and converted it into a Vector Asset in Android Studio by, File > New > Vector Asset
. This converted the SVG image into an XML file.
I created the ic_launcher image by creating a new Image Asset in Android Studio by, File > New > Image Asset
. This created an ic_launcher in a square, round and an Adaptive icon from the XML file.
Note: At the time of writing I faced issues with the SVG image exported from Adobe XD. So I had to use the online converter. Adobe XD does not have xml export feature.
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
EDITED: I noticed that in another user's reply %idle was field 12 instead of field 11. The awk has been updated to account for the %idle field being variable.
This should get you the desired output:
mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { print 100 - $field }'
If you want a simple integer rounding, you can use printf:
mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d%%",100 - $field) }'
If you don't want to include a whole library, you can use this one off to add a method that any array can use:
Array.prototype.uniq = function uniq() {
return this.reduce(function(accum, cur) {
if (accum.indexOf(cur) === -1) accum.push(cur);
return accum;
}, [] );
}
["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"].uniq()
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
We facing this issue today and we solved it. what we do ?
leaflet map load div is below.
<div id="map_container">
<div id="listing_map" class="right_listing"></div>
</div>
When form input change or submit we follow this step below. after leaflet map container removed in my page and create new again.
$( '#map_container' ).html( ' ' ).append( '<div id="listing_map" class="right_listing"></div>' );
After this code my leaflet map is working fine with form filter to reload again.
Thank you.
Simply use CAST,
CAST(column_name AS UNSIGNED)
The type for the cast result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Is sku
just a property of the Product
model? If so:
$products = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
foreach ($products as $product ) {
// Access $product->sku here...
}
Or is sku
a relationship to another model? If that is the case, then, as long as your relationship is setup properly, you code should work.
A simple way is to put tabindex="-1" in the field(s) you don't want to be tabbed to. Eg
<input type="text" tabindex="-1" name="f1">
Additional musings. You said insmod crashes. Insmod loads modules. The modules are built in another compile operation from building the kernel. Kernel and modules have to be built from the same headers and so forth. Are all the modules built during the kernel build, or are they "existing"?
The other idea, and something I know little about, is svn externals, which (if used) can affect what is checked out to your project. Look and see if this is any different when exporting.
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
Better to use arc4random_uniform
. However, this isn't available below iOS 4.3. Luckily iOS will bind this symbol at runtime, not at compile time (so don't use the #if preprocessor directive to check if it's available).
The best way to determine if arc4random_uniform
is available is to do something like this:
#include <stdlib.h>
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (74);
else
r = (arc4random() % 74);
Google Finance has an API - you probably have to apply for a developers key, but at least you'd save yourself the hassle of screen-scraping: http://code.google.com/apis/finance/reference.html
Update: For an all configuration based approach using Groovy see Dean Hiller's answer.
--
You can do some interesting things with Logback filters. The below configuration will only print warn and error messages to stderr, and everything else to stdout.
logback.xml
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<target>System.out</target>
<filter class="com.foo.StdOutFilter" />
...
</appender>
<appender name="stderr" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<filter class="com.foo.ErrOutFilter" />
...
</appender>
<logger name="mylogger" level="debug">
<appender-ref ref="stdout" />
<appender-ref ref="stderr" />
</logger>
com.foo.StdOutFilter
public class StdOutFilter extends ch.qos.logback.core.filter.AbstractMatcherFilter
{
@Override
public FilterReply decide(Object event)
{
if (!isStarted())
{
return FilterReply.NEUTRAL;
}
LoggingEvent loggingEvent = (LoggingEvent) event;
List<Level> eventsToKeep = Arrays.asList(Level.TRACE, Level.DEBUG, Level.INFO);
if (eventsToKeep.contains(loggingEvent.getLevel()))
{
return FilterReply.NEUTRAL;
}
else
{
return FilterReply.DENY;
}
}
}
com.foo.ErrOutFilter
public class ErrOutFilter extends ch.qos.logback.core.filter.AbstractMatcherFilter
{
@Override
public FilterReply decide(Object event)
{
if (!isStarted())
{
return FilterReply.NEUTRAL;
}
LoggingEvent loggingEvent = (LoggingEvent) event;
List<Level> eventsToKeep = Arrays.asList(Level.WARN, Level.ERROR);
if (eventsToKeep.contains(loggingEvent.getLevel()))
{
return FilterReply.NEUTRAL;
}
else
{
return FilterReply.DENY;
}
}
}
Two years after my first go, I'm recidivating...
Why do we prefer parameters? SQL injection is obviously a big reason, but could it be that we're secretly longing to get back to SQL as a language. SQL in string literals is already a weird cultural practice, but at least you can copy and paste your request into management studio. SQL dynamically constructed with host language conditionals and control structures, when SQL has conditionals and control structures, is just level 0 barbarism. You have to run your app in debug, or with a trace, to see what SQL it generates.
Don't stop with just parameters. Go all the way and use QueryFirst (disclaimer: which I wrote). Your SQL lives in a .sql file. You edit it in the fabulous TSQL editor window, with syntax validation and Intellisense for your tables and columns. You can assign test data in the special comments section and click "play" to run your query right there in the window. Creating a parameter is as easy as putting "@myParam" in your SQL. Then, each time you save, QueryFirst generates the C# wrapper for your query. Your parameters pop up, strongly typed, as arguments to the Execute() methods. Your results are returned in an IEnumerable or List of strongly typed POCOs, the types generated from the actual schema returned by your query. If your query doesn't run, your app won't compile. If your db schema changes and your query runs but some columns disappear, the compile error points to the line in your code that tries to access the missing data. And there are numerous other advantages. Why would you want to access data any other way?
I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.
However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.
Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
Here's the third answer I've submitted here. This one handles signal interrupts and cleans up background processes when SIGINT
is received. It uses the $BASHPID
and exec
trick used in the top answer to get the PID of a process (in this case $$
in a sh
invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup. (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)
run_with_timeout ()
{
t=$1 ; shift
trap cleanup 2
F=$$.fifo ; rm -f $F ; mkfifo $F
# first, run main process in background
"$@" & pid=$!
# sleeper process to time out
( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
read sleeper <$F
# control shell. read from fifo.
# final input is "finished". after that
# we clean up. we can get a timeout or a
# signal first.
( exec 0<$F
while : ; do
read input
case $input in
finished)
test $sleeper != 0 && kill $sleeper
rm -f $F
exit 0
;;
timeout)
test $pid != 0 && kill $pid
sleeper=0
;;
signal)
test $pid != 0 && kill $pid
;;
esac
done
) &
# wait for process to end
wait $pid
status=$?
echo finished >$F
return $status
}
cleanup ()
{
echo signal >$$.fifo
}
I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2
or run_with_timeout 0 sleep 0
. For me, the latter gives an error:
timeout.sh: line 250: kill: (23248) - No such process
as it is trying to kill a process that has already exited by itself.
I'm only familiar with Mongo and Couch, but there's also one named Persistence.
Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.
/**
* HTTP request types
*/
public static final int POST_TYPE = 1;
public static final int GET_TYPE = 2;
public static final int PUT_TYPE = 3;
public static final int DELETE_TYPE = 4;
/**
* HTTP request header constants
*/
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ENCODING_GZIP = "gzip";
public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN = "text/plain";
private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
final Map<String, String> headers, final Map<String, String> params, final int requestType)
throws IOException {
DefaultHttpClient client = HTTPClientFactory.newClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);
// add user and pass to client credentials if present
if ((user != null) && (pass != null)) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
}
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
if ((headers != null) && (headers.size() > 0)) {
sendHeaders.putAll(headers);
}
if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
}
// request gzip encoding for response
sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException,
IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
}
});
}
//.... code omitted ....//
}
Use \overset{above}{main}
in math mode. In your case, \overset{a}{\#}
.
Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.
There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.
Let me know if there additional problems you are missing.
This answer does not address the Debug button (you'd have to design a form and use the buttons on that to do something like the method in your next question). But it does address this part:
now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured.
First, I'll assume you don't want this in production code - you want it either for debugging or for code you personally will be using. I use a compiler flag to indicate debugging; then if I'm troubleshooting a program, I can easily find the line that's causing the problem.
# Const IsDebug = True
Sub ProcA()
On Error Goto ErrorHandler
' Main code of proc
ExitHere:
On Error Resume Next
' Close objects and stuff here
Exit Sub
ErrorHandler:
MsgBox Err.Number & ": " & Err.Description, , ThisWorkbook.Name & ": ProcA"
#If IsDebug Then
Stop ' Used for troubleshooting - Then press F8 to step thru code
Resume ' Resume will take you to the line that errored out
#Else
Resume ExitHere ' Exit procedure during normal running
#End If
End Sub
Note: the exception to Resume
is if the error occurs in a sub-procedure without an error handling routine, then Resume
will take you to the line in this proc that called the sub-procedure with the error. But you can still step into and through the sub-procedure, using F8 until it errors out again. If the sub-procedure's too long to make even that tedious, then your sub-procedure should probably have its own error handling routine.
There are multiple ways to do this. Sometimes for smaller programs where I know I'm gonna be stepping through it anyway when troubleshooting, I just put these lines right after the MsgBox statement:
Resume ExitHere ' Normally exits during production
Resume ' Never will get here
Exit Sub
It will never get to the Resume statement, unless you're stepping through and set it as the next line to be executed, either by dragging the next statement pointer to that line, or by pressing CtrlF9 with the cursor on that line.
Here's an article that expands on these concepts: Five tips for handling errors in VBA. Finally, if you're using VBA and haven't discovered Chip Pearson's awesome site yet, he has a page explaining Error Handling In VBA.
It is a problem with Java InputStream. When the stream is read once the file offset position counter is moved to the end of file. On the subsequent read by using the same stream you'll get this error. So you have to close and reopen the stream again or call inputStream.reset()
to reset the offset counter to its initial position.
(a)Simply click on your database, select your table. Click on 'Operations'. Under the 'table options' section change the AUTO_INCREMENT value to your desired value, in this case: 10000 the click 'Go'. (See the image attached)
(b)Alternatively, you can run a SQL command under the SQL tab after selecting your table. Simply type 'ALTER TABLE table_name AUTO_INCREMENT = 10000;' then click 'Go'. That's it!! SETTING AUTO INCREMENT VALUE image(a)
You could use ng-init in an outer div:
<div ng-init="param='value';">
<div ng-controller="BasketController" >
<label>param: {{value}}</label>
</div>
</div>
The parameter will then be available in your controller's scope:
function BasketController($scope) {
console.log($scope.param);
}
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference
package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml
like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
In my case it was changes in object value which the ngOnChange
was not capturing. A few object values are modified in response of api call. Reinitializing the object fixed the issue and caused the ngOnChange
to trigger in the child component.
Something like
this.pagingObj = new Paging(); //This line did the magic
this.pagingObj.pageNumber = response.PageNumber;
You must instruct your logger not to send its messages on up to its parent logger:
...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...
However, this should be done before adding any more handlers to logger.
try the following query:
SELECT ID,
Name
INTO #tempTable
FROM Table
SELECT *
FROM #tempTable
WHERE ID = 1
It doesn't need to declare table.
always year for bootstrap 3 datetimepicker https://eonasdan.github.io/bootstrap-datetimepicker/
$('#year').datetimepicker({
format: 'YYYY',
viewMode: "years",
});
$("#year").on("dp.hide", function (e) {
$('#year').datetimepicker('destroy');
$('#year').datetimepicker({
format: 'YYYY',
viewMode: "years",
});
});
If you are using jackson you can easily achieve this with configuring a SerializationFeature
in your ObjectMapper
:
com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeValueAsString(<yourObject>);
Thats it.
Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.
It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.
Here is a very pedagogic example in C# :-)
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TheNightclub
{
public class Program
{
public static Semaphore Bouncer { get; set; }
public static void Main(string[] args)
{
// Create the semaphore with 3 slots, where 3 are available.
Bouncer = new Semaphore(3, 3);
// Open the nightclub.
OpenNightclub();
}
public static void OpenNightclub()
{
for (int i = 1; i <= 50; i++)
{
// Let each guest enter on an own thread.
Thread thread = new Thread(new ParameterizedThreadStart(Guest));
thread.Start(i);
}
}
public static void Guest(object args)
{
// Wait to enter the nightclub (a semaphore to be released).
Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
Bouncer.WaitOne();
// Do some dancing.
Console.WriteLine("Guest {0} is doing some dancing.", args);
Thread.Sleep(500);
// Let one guest out (release one semaphore).
Console.WriteLine("Guest {0} is leaving the nightclub.", args);
Bouncer.Release(1);
}
}
}
As per the official docs the sp_lock is mark as deprecated:
This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.
and it is recommended to use sys.dm_tran_locks instead. This dynamic management object returns information about currently active lock manager resources. Each row represents a currently active request to the lock manager for a lock that has been granted or is waiting to be granted.
It generally returns more details in more user friendly syntax then sp_lock
does.
The whoisactive routine written by Adam Machanic is very good to check the current activity in your environment and see what types of waits/locks are slowing your queries. You can very easily find what is blocking your queries and tons of other handy information.
For example, let's say we have the following queries running in the default SQL Server Isolation Level - Read Committed. Each query is executing in separate query window:
-- creating sample data
CREATE TABLE [dbo].[DataSource]
(
[RowID] INT PRIMARY KEY
,[RowValue] VARCHAR(12)
);
INSERT INTO [dbo].[DataSource]([RowID], [RowValue])
VALUES (1, 'samle data');
-- query window 1
BEGIN TRANSACTION;
UPDATE [dbo].[DataSource]
SET [RowValue] = 'new data'
WHERE [RowID] = 1;
--COMMIT TRANSACTION;
-- query window 2
SELECT *
FROM [dbo].[DataSource];
Then execute the sp_whoisactive
(only part of the columns are displayed):
You can easily seen the session which is blocking the SELECT
statement and even its T-SQL code. The routine has a lot of parameters, so you can check the docs for more details.
If we query the sys.dm_tran_locks
view we can see that one of the session is waiting for a share lock of a resource, that has exclusive lock by other session:
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
Ultimately figured out the root of the problem.
When I create the security context manually no session object is created. Only when the request finishes processing does the Spring Security mechanism realize that the session object is null (when it tries to store the security context to the session after the request has been processed).
At the end of the request Spring Security creates a new session object and session ID. However this new session ID never makes it to the browser because it occurs at the end of the request, after the response to the browser has been made. This causes the new session ID (and hence the Security context containing my manually logged on user) to be lost when the next request contains the previous session ID.
As far as I can tell, there are three main contenders: Table-Valued Parameters, delimited list string, and JSON string.
Since 2016, you can use the built-in STRING_SPLIT if you want the delimited route: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
That would probably be the easiest/most straightforward/simple approach.
Also since 2016, JSON can be passed as a nvarchar and used with OPENJSON: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql
That's probably best if you have a more structured data set to pass that may be significantly variable in its schema.
TVPs, it seems, used to be the canonical way to pass more structured parameters, and they are still good if you need that structure, explicitness, and basic value/type checking. They can be a little more cumbersome on the consumer side, though. If you don't have 2016+, this is probably the default/best option.
I think it's a trade off between any of these concrete considerations as well as your preference for being explicit about the structure of your params, meaning even if you have 2016+, you may prefer to explicitly state the type/schema of the parameter rather than pass a string and parse it somehow.
You can use git archive to download a tar ball for a given tag or commit id:
git archive --format=tar --remote=[hostname]:[path to repo] [tag name] > tagged_version.tar
You can also export a zip archive of a tag.
List tags:
git tag
0.0.1
0.1.0
Export a tag:
git archive -o /tmp/my-repo-0.1.0.zip --prefix=my-repo-0.1.0/ 0.1.0
Notes:
Find control into Repeater (Header, Item, Footer)
public static class FindControlInRepeater
{
public static Control FindControl(this Repeater repeater, string controlName)
{
for (int i = 0; i < repeater.Controls.Count; i++)
if (repeater.Controls[i].Controls[0].FindControl(controlName) != null)
return repeater.Controls[i].Controls[0].FindControl(controlName);
return null;
}
}
Try this
`var url = "http://stackoverflow.com";
$(location).attr('href',url);`
Or you can do something like this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
and add a return false at the end of your function call
Another option is to use
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
I like this one most.
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
I use WinMerge. It is free and works pretty well (works for files and directories).
how to retrieve keystore password
You cannot retrieve the password. If you forgot it, you are doomed.
how to retrieve key alias
$ keytool -list -v -keystore <store>
But you need keystore password for this first.
EDIT
What I don't remember is the 'Key Password'
No password can be restored. If you forgot key password for good then you are doomed too and there's no other way than trying harder to recall it. There's no password reset thing nor anything like that.
Be aware that if you forgot your password for good then you will issue no further updates to your app (docs):
Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.
Don't reinvent the wheel. Take advantage of what's already in .NET BCL.
Microsoft.VisualBasic
(yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV fileHere is the sample code:
using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
//TODO: Process field
}
}
}
It works great for me in my C# projects.
Here are some more links/informations:
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.
Here are some that do not resize their contents (I'm guessing that you are using one or more of these):
StackPanel
WrapPanel
Canvas
TabControl
Here are some that do resize their contents:
Grid
UniformGrid
DockPanel
Therefore, it is almost always preferable to use a Grid
instead of a StackPanel
unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid
to not size its inner controls... it all depends on your Grid.RowDefinition
and Grid.ColumnDefinition
settings:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
<RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
<RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
</Grid.RowDefinitions>
</Grid>
You can find out more about the Grid
control from the Grid
Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.
Further resizing can be achieved using the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties. The default value of these properties is Stretch
which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.
UPDATE >>>
In response to the questions in your comment:
Use the Grid.RowDefinition
and Grid.ColumnDefinition
settings to organise a basic structure first... it is common to add Grid
controls into the cells of outer Grid
controls if need be. You can also use the Grid.ColumnSpan
and Grid.RowSpan
properties to enable controls to span multiple columns and/or rows of a Grid
.
It is most common to have at least one row/column with a Height
/Width
of "*"
which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.
There is no Auto
setting that you can use on the controls in the cells, but this is just as well, because we want the Grid
to size the controls for us... therefore, we don't want to set the Height
or Width
of these controls at all.
The point that I made about the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties was just to let you know of their existence... as their default value is already Stretch
, you don't generally need to set them explicitly.
The Margin
property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin
property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin
property to suit your needs.
I had to delete Tomcat's work directory as it had cached previously generated files. To do this:
This will cause the work directory to be newly generated.
Your query would always return an empty recordset since cut_name= '?????' and cut_name='??'
will never evaluate to true
.
In general, INTERSECT
in MySQL
should be emulated like this:
SELECT *
FROM mytable m
WHERE EXISTS
(
SELECT NULL
FROM othertable o
WHERE (o.col1 = m.col1 OR (m.col1 IS NULL AND o.col1 IS NULL))
AND (o.col2 = m.col2 OR (m.col2 IS NULL AND o.col2 IS NULL))
AND (o.col3 = m.col3 OR (m.col3 IS NULL AND o.col3 IS NULL))
)
If both your tables have columns marked as NOT NULL
, you can omit the IS NULL
parts and rewrite the query with a slightly more efficient IN
:
SELECT *
FROM mytable m
WHERE (col1, col2, col3) IN
(
SELECT col1, col2, col3
FROM othertable o
)
THIS WORK ALSO WITH Arraylist
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
ArrayList<String> firstList = new ArrayList<String>() {/**
*
*/
private static final long serialVersionUID = 1L;
{
add("apple");
add("orange");
add("pea");
}};
ArrayList<String> secondList = new ArrayList<String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
add("apple");
add("orange");
add("banana");
add("strawberry");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)
I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Dim SQL As String
SQL = _
"SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
"c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
"FROM tblClient AS c " & _
"WHERE c.ClientID = @ClientID"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
.Parameters.Append prm
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
mstrLastName = Nz(!LastName, "")
mstrFirstName = Nz(!FirstName, "")
mstrMI = Nz(!MI, "")
mdDOB = !DOB
mstrSSN = Nz(!SSN, "")
mlngRaceID = Nz(!RaceID, -1)
mlngEthnicityID = Nz(!EthnicityID, -1)
mlngGenderID = Nz(!GenderID, -1)
mbooDeleted = Deleted
mdRecordDate = Nz(!RecordDate, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Using PHP close/open tags is not very good solution because of 2 reasons: you can't print PHP variables in plain HTML and it make your code very hard to read (the next code block starts with an end bracket }
, but the reader has no idea what was before).
Better is to use heredoc syntax. It is the same concept as in other languages (like bash).
<?php
if ($condition) {
echo <<< END_OF_TEXT
<b>lots of html</b> <i>$variable</i>
lots of text...
many lines possible, with any indentation, until the closing delimiter...
END_OF_TEXT;
}
?>
END_OF_TEXT
is your delimiter (it can be basically any text like EOF, EOT). Everything between is considered string by PHP as if it were in double quotes, so you can print variables, but you don't have to escape any quotes, so it very convenient for printing html attributes.
Note that the closing delimiter must begin on the start of the line and semicolon must be placed right after it with no other chars (END_OF_TEXT;
).
Heredoc with behaviour of string in single quotes ('
) is called nowdoc. No parsing is done inside of nowdoc. You use it in the same way as heredoc, just you put the opening delimiter in single quotes - echo <<< 'END_OF_TEXT'
.
Either Collections.emptyMap()
, or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()
On Windows, I got this error when running under a non-administrator command prompt. When I ran this as administrator, the error went away.
const button = document.getElementById(btnId);
button.addEventListener("click", function() {
// Submit form
}, {once : true});
// Disabling works too, but this is a more standard approach for general one-time events
SO in fact that you are using excel means that you can use the SpreadSheet Compare from Microsoft. It is available from Office 2013. Yes i know this question is older then 6 years. But who knows maybe someone need this information today.
from this tutorial: https://www.tutorialkart.com/opencv/python/opencv-python-get-image-size/
import cv2
# read image
img = cv2.imread('/home/ubuntu/Walnut.jpg', cv2.IMREAD_UNCHANGED)
# get dimensions of image
dimensions = img.shape
# height, width, number of channels in image
height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]
from this other tutorial: https://www.pyimagesearch.com/2018/07/19/opencv-tutorial-a-guide-to-learn-opencv/
image = cv2.imread("jp.png")
(h, w, d) = image.shape
Please double check things before posting answers.
If you want to make sure that no tasks will run at the same time then use a SingleThreadedExecutor. The tasks will be processed in the order the are submitted. You don't even need to hold the tasks, just submit them to the exec.
Here is yet another way without Invoke-Expression
but with two variables
(command:string and parameters:array). It works fine for me. Assume
7z.exe
is in the system path.
$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& $cmd $prm
If the command is known (7z.exe) and only parameters are variable then this will do
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& 7z.exe $prm
BTW, Invoke-Expression
with one parameter works for me, too, e.g. this works
$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'
Invoke-Expression $cmd
P.S. I usually prefer the way with a parameter array because it is easier to
compose programmatically than to build an expression for Invoke-Expression
.
If you don't want to install MySQL workbench, and are looking for an online tool, this might help: http://ondras.zarovi.cz/sql/demo/
I use it quite often to create simple DB schemas for various apps I build.
My observation on initial accepted solution.
Under RR (default mysql) - If a tx is open and a SELECT has been fired, another tx can NOT delete any row belonging to previous READ result set until previous tx is committed (in fact delete statement in the new tx will just hang), however the next tx can delete all rows from the table without any trouble. Btw, a next READ in previous tx will still see the old data until it is committed.
Also to maintain accessibility, you should use this to determine your keycode:
c = e.which ? e.which : e.keyCode;
if (c == 13) ...
I figured out below would work:
my_df.dropna().quantile([0.0, .9])
Select mymethod()
and press ctrl+alt+h.
To see some detailed Information about any method you can use this by selecting that particular Object or method and right click. you can see the "OpenCallHierarchy" (Ctrl+Alt+H). Like that many tools are there to make your work Easier like "Quick Outline" (Ctrl+O) to view the Datatypes and methods declared in a particular .java file.
To know more about this, refer this eclipse Reference
If you're installing using --user
(e.g. pip3.6 install --user tmuxp
), it is possible to get the platform-specific user install directory from Python itself using the site
module. For example, on macOS:
$ python2.7 -m site --user-base
/Users/alexp/Library/Python/2.7
By appending /bin
to this, we now have the path where package executables will be installed. We can dynamically populate the PATH in your shell's rc file based on the output; I'm using bash, but with any luck this is portable:
# Add Python bin directories to path
python3.6 -m site &> /dev/null && PATH="$PATH:`python3.6 -m site --user-base`/bin"
python2.7 -m site &> /dev/null && PATH="$PATH:`python2.7 -m site --user-base`/bin"
I use the precise Python versions to reduce the chance of the executables just "disappearing" when Python upgrades a minor version, e.g. from 3.5 to 3.6. They'll disappear because, as can be seen above, the user installation path may include the Python version. So while python3
could point to 3.5 or 3.6, python3.6
will always point to 3.6. This needs to be kept in mind when installing further packages, e.g. use pip3.6
over pip3
.
If you don't mind the idea of packages disappearing, you can use python2
and python3
instead:
# Add Python bin directories to path
# Note: When Python is upgraded, packages may need to be re-installed
# or Python versions managed.
python3 -m site &> /dev/null && PATH="$PATH:`python3 -m site --user-base`/bin"
python2 -m site &> /dev/null && PATH="$PATH:`python2 -m site --user-base`/bin"
A simple way can be to split the string on each character and join the parts using space as the delimiter.
Demo:
public class Main {
public static void main(String[] args) {
String s = "JAYARAM";
s = String.join(" ", s.split(""));
System.out.println(s);
}
}
Output:
J A Y A R A M
This question seems to be the most popular one for disabling textarea
wrap. However, as of April 2017 I find that IE 11 (11.0.9600) will not disable word wrap with any of the above solutions.
The only solution which does work for IE 11 is wrap="off"
. wrap="soft"
and/or the various CSS attributes like white-space: pre
alter where IE 11 chooses to wrap but it still wraps somewhere. Note that I have tested this with or without Compatibility View. IE 11 is pretty HTML 5 compatible, but not in this case.
Thus, to achieve lines which retain their whitespace and go off the right-hand side I am using:
<textarea style="white-space: pre; overflow: scroll;" wrap="off">
Fortuitously this does seem to work in Chrome & Firefox too. I am not defending the use of pre-HTML 5 wrap="off"
, just saying that it seems to be required for IE 11.
This is a great chance to introduce you to the File Exchange. Though the organization of late has suffered from some very unfortunately interface design choices, it is still a great resource for pre-packaged solutions to common problems. Though many here have given you the gory details of how to achieve this (@prm!), I had a similar need a few years ago and found that addaxis worked very well. (It was a File Exchange pick of the week at one point!) It has inspired later, probably better mods. Here is some example output:
addaxis example http://www.mathworks.com/matlabcentral/fx_files/9016/1/addaxis_screenshot.jpg
I just searched for "plotyy" at File Exchange.
Though understanding what's going on in important, sometimes you just need to get things done, not do them yourself. Matlab Central is great for that.
if its date in 24 hours and start in morning and end in the night should add something like :
declare @Approval_date datetime
set @Approval_date =getdate()
Approval_date between @Approval_date +' 00:00:00.000' and @Approval_date +' 23:59:59.999'
string.Join(" ,", myArrayList.ToArray());
This will work with .net framework 4.5
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
There is a clean, one-line way of doing this in Pandas:
df['col_3'] = df.apply(lambda x: f(x.col_1, x.col_2), axis=1)
This allows f
to be a user-defined function with multiple input values, and uses (safe) column names rather than (unsafe) numeric indices to access the columns.
Example with data (based on original question):
import pandas as pd
df = pd.DataFrame({'ID':['1', '2', '3'], 'col_1': [0, 2, 3], 'col_2':[1, 4, 5]})
mylist = ['a', 'b', 'c', 'd', 'e', 'f']
def get_sublist(sta,end):
return mylist[sta:end+1]
df['col_3'] = df.apply(lambda x: get_sublist(x.col_1, x.col_2), axis=1)
Output of print(df)
:
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
If your column names contain spaces or share a name with an existing dataframe attribute, you can index with square brackets:
df['col_3'] = df.apply(lambda x: f(x['col 1'], x['col 2']), axis=1)