For large datasets, how about JQuery UI Autocomplete, which is basically the "official" version of Jorn Zaeferrer's Autocomplete plugin?
I also wrote a straight JQuery combobox plugin that's gotten pretty good feedback from its users. It's explicitly not meant for large datasets though; I figure that if you want something that prunes the list based on what the user types, you're better off with Jorn's autocompletion plugin.
You should specify
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
as array.
Add []
to all names Days
and work at php with this like an array.
After it, you can INSERT
values at different columns at db, or use implode
and save values into one column.
Didn't tested it, but you can try like this. Don't forget to replace mysql
with mysqli
.
<html>
<body>
<form method="post" action="chk123.php">
Flights on: <br/>
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
<input type="checkbox" name="Days[]" value="Monday">Monday<br>
<input type="checkbox" name="Days[]" value="Tuesday">Tuesday <br>
<input type="checkbox" name="Days[]" value="Wednesday">Wednesday<br>
<input type="checkbox" name="Days[]" value="Thursday">Thursday <br>
<input type="checkbox" name="Days[]" value="Friday">Friday<br>
<input type="checkbox" name="Days[]" value="Saturday">Saturday <br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$checkBox = implode(',', $_POST['Days']);
if(isset($_POST['submit']))
{
$query="INSERT INTO example (orange) VALUES ('" . $checkBox . "')";
mysql_query($query) or die (mysql_error() );
echo "Complete";
}
?>
Worked for me Try this code
uri = Uri.fromFile(new File("//assets/testdemo.txt"));
String testfilepath = uri.getPath();
File f = new File(testfilepath);
if (f.exists() == true) {
Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
} else {
Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
}
Try this -->
new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko).ToList()
Another option is setting the log levels for specific tags:
adb logcat SensorService:S PowerManagerService:S NfcService:S power:I Sensors:E
If you just want to set the log levels for some tags you can do it on a tag by tag basis.
If anyone runs across this and is looking for a bit more up-to-date answer or copy-paste answer or answer targeting multiple versions than JC Raja's post, here's what I've found:
Google's got a pretty solid, easy-to-understand introduction to how this works and what is advantageous and not. https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer They recommend the HTML5 Boilerplate project, which has solutions for different versions of IIS:
Available here: https://github.com/h5bp/server-configs-iis They have web.configs that you can copy and paste changes from theirs to yours and see the changes, much easier than digging through a bunch of blog posts.
Here's the web.config settings for .NET version 4.5: https://github.com/h5bp/server-configs-iis/blob/master/dotnet%204.5/MVC5/Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" targetFramework="4.5" />
<!-- Security through obscurity, removes X-AspNet-Version HTTP header from the response -->
<!-- Allow zombie DOS names to be captured by ASP.NET (/con, /com1, /lpt1, /aux, /prt, /nul, etc) -->
<httpRuntime targetFramework="4.5" requestValidationMode="2.0" requestPathInvalidCharacters="" enableVersionHeader="false" relaxedUrlToFileSystemMapping="true" />
<!-- httpCookies httpOnlyCookies setting defines whether cookies
should be exposed to client side scripts
false (Default): client side code can access cookies
true: client side code cannot access cookies
Require SSL is situational, you can also define the
domain of cookies with optional "domain" property -->
<httpCookies httpOnlyCookies="true" requireSSL="false" />
<trace writeToDiagnosticsTrace="false" enabled="false" pageOutput="false" localOnly="true" />
</system.web>
<system.webServer>
<!-- GZip static file content. Overrides the server default which only compresses static files over 2700 bytes -->
<httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
<httpErrors existingResponse="PassThrough" errorMode="Custom">
<!-- Catch IIS 404 error due to paths that exist but shouldn't be served (e.g. /controllers, /global.asax) or IIS request filtering (e.g. bin, web.config, app_code, app_globalresources, app_localresources, app_webreferences, app_data, app_browsers) -->
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" subStatusCode="-1" path="/notfound" responseMode="ExecuteURL" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" subStatusCode="-1" path="/error" responseMode="ExecuteURL" />
</httpErrors>
<directoryBrowse enabled="false" />
<validation validateIntegratedModeConfiguration="false" />
<!-- Microsoft sets runAllManagedModulesForAllRequests to true by default
You should handle this according to need but consider the performance hit.
Good source of reference on this matter: http://www.west-wind.com/weblog/posts/2012/Oct/25/Caveats-with-the-runAllManagedModulesForAllRequests-in-IIS-78
-->
<modules runAllManagedModulesForAllRequests="false" />
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<staticContent>
<!-- Set expire headers to 30 days for static content-->
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
<!-- use utf-8 encoding for anything served text/plain or text/html -->
<remove fileExtension=".css" />
<mimeMap fileExtension=".css" mimeType="text/css" />
<remove fileExtension=".js" />
<mimeMap fileExtension=".js" mimeType="text/javascript" />
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<remove fileExtension=".rss" />
<mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
<remove fileExtension=".html" />
<mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
<remove fileExtension=".xml" />
<mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />
<!-- HTML5 Audio/Video mime types-->
<remove fileExtension=".mp3" />
<mimeMap fileExtension=".mp3" mimeType="audio/mpeg" />
<remove fileExtension=".mp4" />
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />
<remove fileExtension=".ogg" />
<mimeMap fileExtension=".ogg" mimeType="audio/ogg" />
<remove fileExtension=".ogv" />
<mimeMap fileExtension=".ogv" mimeType="video/ogg" />
<remove fileExtension=".webm" />
<mimeMap fileExtension=".webm" mimeType="video/webm" />
<!-- Proper svg serving. Required for svg webfonts on iPad -->
<remove fileExtension=".svg" />
<mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
<remove fileExtension=".svgz" />
<mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />
<!-- HTML4 Web font mime types -->
<!-- Remove default IIS mime type for .eot which is application/octet-stream -->
<remove fileExtension=".eot" />
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<remove fileExtension=".ttf" />
<mimeMap fileExtension=".ttf" mimeType="application/x-font-ttf" />
<remove fileExtension=".ttc" />
<mimeMap fileExtension=".ttc" mimeType="application/x-font-ttf" />
<remove fileExtension=".otf" />
<mimeMap fileExtension=".otf" mimeType="font/opentype" />
<remove fileExtension=".woff" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<remove fileExtension=".crx" />
<mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension" />
<remove fileExtension=".xpi" />
<mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall" />
<remove fileExtension=".safariextz" />
<mimeMap fileExtension=".safariextz" mimeType="application/octet-stream" />
<!-- Flash Video mime types-->
<remove fileExtension=".flv" />
<mimeMap fileExtension=".flv" mimeType="video/x-flv" />
<remove fileExtension=".f4v" />
<mimeMap fileExtension=".f4v" mimeType="video/mp4" />
<!-- Assorted types -->
<remove fileExtension=".ico" />
<mimeMap fileExtension=".ico" mimeType="image/x-icon" />
<remove fileExtension=".webp" />
<mimeMap fileExtension=".webp" mimeType="image/webp" />
<remove fileExtension=".htc" />
<mimeMap fileExtension=".htc" mimeType="text/x-component" />
<remove fileExtension=".vcf" />
<mimeMap fileExtension=".vcf" mimeType="text/x-vcard" />
<remove fileExtension=".torrent" />
<mimeMap fileExtension=".torrent" mimeType="application/x-bittorrent" />
<remove fileExtension=".cur" />
<mimeMap fileExtension=".cur" mimeType="image/x-icon" />
<remove fileExtension=".webapp" />
<mimeMap fileExtension=".webapp" mimeType="application/x-web-app-manifest+json; charset=UTF-8" />
</staticContent>
<httpProtocol>
<customHeaders>
<!--#### SECURITY Related Headers ###
More information: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
-->
<!--
# Access-Control-Allow-Origin
The 'Access Control Allow Origin' HTTP header is used to control which
sites are allowed to bypass same-origin policies and send cross-origin requests.
Secure configuration: Either do not set this header or return the 'Access-Control-Allow-Origin'
header restricting it to only a trusted set of sites.
http://enable-cors.org/
<add name="Access-Control-Allow-Origin" value="*" />
-->
<!--
# Cache-Control
The 'Cache-Control' response header controls how pages can be cached
either by proxies or the user's browser.
This response header can provide enhanced privacy by not caching
sensitive pages in the user's browser cache.
<add name="Cache-Control" value="no-store, no-cache"/>
-->
<!--
# Strict-Transport-Security
The HTTP Strict Transport Security header is used to control
if the browser is allowed to only access a site over a secure connection
and how long to remember the server response for, forcing continued usage.
Note* Currently a draft standard which only Firefox and Chrome support. But is supported by sites like PayPal.
<add name="Strict-Transport-Security" value="max-age=15768000"/>
-->
<!--
# X-Frame-Options
The X-Frame-Options header indicates whether a browser should be allowed
to render a page within a frame or iframe.
The valid options are DENY (deny allowing the page to exist in a frame)
or SAMEORIGIN (allow framing but only from the originating host)
Without this option set, the site is at a higher risk of click-jacking.
<add name="X-Frame-Options" value="SAMEORIGIN" />
-->
<!--
# X-XSS-Protection
The X-XSS-Protection header is used by Internet Explorer version 8+
The header instructs IE to enable its inbuilt anti-cross-site scripting filter.
If enabled, without 'mode=block', there is an increased risk that
otherwise, non-exploitable cross-site scripting vulnerabilities may potentially become exploitable
<add name="X-XSS-Protection" value="1; mode=block"/>
-->
<!--
# MIME type sniffing security protection
Enabled by default as there are very few edge cases where you wouldn't want this enabled.
Theres additional reading below; but the tldr, it reduces the ability of the browser (mostly IE)
being tricked into facilitating driveby attacks.
http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
-->
<add name="X-Content-Type-Options" value="nosniff" />
<!-- A little extra security (by obscurity), removings fun but adding your own is better -->
<remove name="X-Powered-By" />
<add name="X-Powered-By" value="My Little Pony" />
<!--
With Content Security Policy (CSP) enabled (and a browser that supports it (http://caniuse.com/#feat=contentsecuritypolicy),
you can tell the browser that it can only download content from the domains you explicitly allow
CSP can be quite difficult to configure, and cause real issues if you get it wrong
There is website that helps you generate a policy here http://cspisawesome.com/
<add name="Content-Security-Policy" "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://www.google-analytics.com;" />
-->
<!--//#### SECURITY Related Headers ###-->
<!--
Force the latest IE version, in various cases when it may fall back to IE7 mode
github.com/rails/rails/commit/123eb25#commitcomment-118920
Use ChromeFrame if it's installed for a better experience for the poor IE folk
-->
<add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
<!--
Allow cookies to be set from iframes (for IE only)
If needed, uncomment and specify a path or regex in the Location directive
<add name="P3P" value="policyref="/w3c/p3p.xml", CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"" />
-->
</customHeaders>
</httpProtocol>
<!--
<rewrite>
<rules>
Remove/force the WWW from the URL.
Requires IIS Rewrite module http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/
Configuration lifted from http://nayyeri.net/remove-www-prefix-from-urls-with-url-rewrite-module-for-iis-7-0
NOTE* You need to install the IIS URL Rewriting extension (Install via the Web Platform Installer)
http://www.microsoft.com/web/downloads/platform.aspx
** Important Note
using a non-www version of a webpage will set cookies for the whole domain making cookieless domains
(eg. fast CD-like access to static resources like CSS, js, and images) impossible.
# IMPORTANT: THERE ARE TWO RULES LISTED. NEVER USE BOTH RULES AT THE SAME TIME!
<rule name="Remove WWW" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
</conditions>
<action type="Redirect" url="http://example.com{PATH_INFO}" redirectType="Permanent" />
</rule>
<rule name="Force WWW" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^example.com$" />
</conditions>
<action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" />
</rule>
# E-TAGS
E-Tags are actually quite useful in cache management especially if you have a front-end caching server such as Varnish. http://en.wikipedia.org/wiki/HTTP_ETag / http://developer.yahoo.com/performance/rules.html#etags
But in load balancing and simply most cases ETags are mishandled in IIS, and it can be advantageous to remove them.
# removed as in https://stackoverflow.com/questions/7947420/iis-7-5-remove-etag-headers-from-response
<rewrite>
<outboundRules>
<rule name="Remove ETag">
<match serverVariable="RESPONSE_ETag" pattern=".+" />
<action type="Rewrite" value="" />
</rule>
</outboundRules>
</rewrite>
-->
<!--
### Built-in filename-based cache busting
In a managed language such as .net, you should really be using the internal bundler for CSS + js
or get cassette or similar.
If you're not using the build script to manage your filename version revving,
you might want to consider enabling this, which will route requests for
/css/style.20110203.css to /css/style.css
To understand why this is important and a better idea than all.css?v1231,
read: github.com/h5bp/html5-boilerplate/wiki/Version-Control-with-Cachebusting
<rule name="Cachebusting">
<match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" />
<action type="Rewrite" url="{R:1}{R:2}" />
</rule>
</rules>
</rewrite>-->
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Edit: One update if you need Gzip compression on WebAPI responses. I wasn't aware our WebAPI wasn't returning Gzipped responses until recently and scratched my head for a while because we had dynamic and static compression turned on in web.config. We looked at writing our own compression services and response handlers (still on WebAPI 2 not on .NET Core where it's easier now), but that was too cumbersome for what seemed like something we should just be able to turn on.
(If you're interested here's what we were looking at for our own compression service https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/
EDIT: Link is now offline, but you can view the code/content here: https://web.archive.org/web/20190608161201/https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ )
Instead, we found this great post by Ben Foster (http://benfoster.io/blog/aspnet-web-api-compression) If you can modify applicationHost.config (running your own servers), you can pop that config file open and add the mimeTypes you want to compress (I pulled the relevant ones based on what our API was returning to clients from our Web.Config). Save that file, IIS will pickup your changes, recycle app pools, and your WebAPI will start returning gzip compressed responses to clients who request it.
If you don't see gzipped responses, check the response content type with Fiddler or Chrome/Firefox Dev Tools, and ensure it matches what you added. I had to change the view mode (use large request rows) in Chrome Dev Tools to ensure it showed the total size vs transferred size. If everything validates, try rebooting the server once to just ensure it was properly applied. I did have one syntax error where when I opened up the site in IIS, IIS poppped open a message about a parsing error that I had to fix in the config file.
<httpCompression directory="%TEMP%\iisexpress\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%IIS_BIN%\gzip.dll" />
<dynamicTypes>
...
<!-- compress JSON responses from Web API -->
<add mimeType="application/json" enabled="true" />
...
</dynamicTypes>
<staticTypes>
...
</staticTypes>
</httpCompression>
Also from Java 8 you can write Dan Cruz answer as:
Thread t = new Thread(()->{
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException(); });
t.setUncaughtExceptionHandler((th, ex)-> log(String.format("Exception in thread %d id: %s", th.getId(), ex)));
t.start();
Simply install this jQuery Plugin: jQuery Cross-Domain AJAX for IE8
This 1.4kb plugin works right away in Internet Explorer 8 and 9.
Include the plugin after jQuery, and call your ajax request as normal. Nothing else required.
I've made another sample extension on UIDevice to include simulator model identifier base on @HAS's answer . It's working fine with Swift3.2 above(include Swift 4.x, Swift 5):
let modelName = UIDevice.current.modelName
New add Models: iPod touch (7th generation), iPhone SE (2nd generation), iPhone 12 mini, iPhone 12, iPhone 12 Pro, iPhone 12 Pro Max, iPad Pro (12.9-inch) (4th generation)
import UIKit
public extension UIDevice {
/// pares the deveice name as the standard name
var modelName: String {
#if targetEnvironment(simulator)
let identifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"]!
#else
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
#endif
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPod9,1": return "iPod touch (7th generation)"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4", "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE (2nd generation)"
case "iPhone13,1": return "iPhone 12 mini"
case "iPhone13,2": return "iPhone 12"
case "iPhone13,3": return "iPhone 12 Pro"
case "iPhone13,4": return "iPhone 12 Pro Max"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad6,11", "iPad6,12": return "iPad 5"
case "iPad7,5", "iPad7,6": return "iPad 6"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)"
case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)"
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch)"
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)"
case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
default: return identifier
}
}
}
Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
As CharlesA notes in his answer, .values()
is technically deprecated, though this fact isn't explicitly noted in the docs. If you don't want to use { raw: true }
in the query, the preferred approach is to call .get()
on the results.
.get()
, however, is a method of an instance, not of an array. As noted in the linked issue above, Sequelize returns native arrays of instance objects (and the maintainers don't plan on changing that), so you have to iterate through the array yourself:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
}
}).success((sensors) => {
const nodeData = sensors.map((node) => node.get({ plain: true }));
});
Use type="application/javascript"
In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.
http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
Use "application/javascript", because "text/javascript" is obsolete:
RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt
Deployed Scripting Media Types and Compatibility
Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:
+-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+
Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.
x-javascript is experimental, don't use it.
If using Python 2.7 or higher (especially prior to Python 3.5) you can use the following:
import subprocess
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Runs the command described by args. Waits for command to complete, then returns the returncode attribute.subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Runs command with arguments. Waits for command to complete. If the return code was zero then returns, otherwise raises CalledProcessError. The CalledProcessError object will have the return code in the returncode attributeExample: subprocess.check_call([r"C:\pathToYourProgram\yourProgram.exe", "your", "arguments", "comma", "separated"])
In regular Python strings, the \U character combination signals a extended Unicode code point escape.
Here is the link to the documentation: http://docs.python.org/3.2/library/subprocess.html
For Python 3.5+ you can now use run() in many cases: https://docs.python.org/3.5/library/subprocess.html#subprocess.run
You generally should not add an app.config
file to a class library project; it won't be used without some painful bending and twisting on your part. It doesn't hurt the library project at all - it just won't do anything at all.
Instead, you configure the application which is using your library; so the configuration information required would go there. Each application that might use your library likely will have different requirements, so this actually makes logical sense, too.
First of all, every variable must be initialized. Always.
Casting is not an option.
if get_values(); can return different type variable, this value must be checked, of course.
No. Not necessarily.
If you need to place a DIV within a TD, be sure you're using the TD properly. If you don't care about tabular-data, and semantics, then you ultimately won't care about DIVs in TDs. I don't think there's a problem though - if you have to do it, you're fine.
According to the HTML Specification
A <div>
can be placed where flow content is expected1, which is the <td>
content model2.
According to Android Developer site
I think you cant(as far as i know) hide navigation bar permanently..
However you can do one trick. Its a trick mind you.
Just when the navigation bar
shows up when user touches the screen. Immediately hide it again.
Its fun.
Check this.
void setNavVisibility(boolean visible) {
int newVis = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| SYSTEM_UI_FLAG_LAYOUT_STABLE;
if (!visible) {
newVis |= SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_FULLSCREEN
| SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// If we are now visible, schedule a timer for us to go invisible.
if (visible) {
Handler h = getHandler();
if (h != null) {
h.removeCallbacks(mNavHider);
if (!mMenusOpen && !mPaused) {
// If the menus are open or play is paused, we will not auto-hide.
h.postDelayed(mNavHider, 1500);
}
}
}
// Set the new desired visibility.
setSystemUiVisibility(newVis);
mTitleView.setVisibility(visible ? VISIBLE : INVISIBLE);
mPlayButton.setVisibility(visible ? VISIBLE : INVISIBLE);
mSeekView.setVisibility(visible ? VISIBLE : INVISIBLE);
}
See this for more information on this ..
You are right that CSS positioning is the way to go. Here's a quick run down:
position: relative
will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).
However, you're most likely interested in position: absolute
which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative
or position: absolute
set on it, then it will act as the parent for positioning coordinates for its children.
To demonstrate:
#container {_x000D_
position: relative;_x000D_
border: 1px solid red;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="box">absolute</div>_x000D_
</div>
_x000D_
In that example, the top left corner of #box
would be 100px down and 50px left of the top left corner of #container
. If #container
did not have position: relative
set, the coordinates of #box
would be relative to the top left corner of the browser view port.
You can have a pair of extension methods to make this task easier:
public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
return lst.ToDelimitedString(p => p, separator);
}
public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector,
string separator = ", ")
{
return string.Join(separator, lst.Select(selector));
}
So now just:
new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
As in any unix-based environment, you can use the sudo
command:
$ sudo script-name
It will ask for your password (your own, not a separate root
password).
All other answers are useful but they may not help you in case nginx
is not on PATH
so you're getting command not found
when trying to run nginx
:
I have nginx 1.2.1 on Debian 7 Wheezy, the nginx
executable is not on PATH
, so I needed to locate it first. It was already running, so using ps aux | grep nginx
I have found out that it's located on /usr/sbin/nginx
, therefore I needed to run /usr/sbin/nginx -t
.
If you want to use a non-default configuration file (i.e. not /etc/nginx/nginx.conf
), run it with the -c
parameter: /usr/sbin/nginx -c <path-to-configuration> -t
.
You may also need to run it as root
, otherwise nginx may not have permissions to open for example logs, so the command would fail.
Systemd which now runs in the majority of distros
Find your user defined services mine was at /usr/lib/systemd/system/
Create a text file with your favorite text editor name it whatever_you_want.service
Put following
Template to the file whatever_you_want.service
[Unit]
Description=webserver Daemon
[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user
[Install]
WantedBy=multi-user.target
Run your service
as super user
$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service
go to cmd get into file directory and type jupyter notebook filename.ipynb in my case it open code editor and provide local host connection string copy that string and paste in any browser!done
Flexbox was created for exactly these kind of problems:
#container {_x000D_
height: 150px;/*Only for the demo.*/_x000D_
background-color:green;/*Only for the demo.*/_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: flex-end;_x000D_
}
_x000D_
<div id="container">_x000D_
<span>Text align to center bottom.</span>_x000D_
</div>
_x000D_
If you don't want to mess with table displays, then you can create a <div>
inside a relatively positioned parent container, place it to the bottom with absolute positioning, then make it 100% wide, so you can text-align
it to the center:
#container {_x000D_
height: 150px;/*Only for the demo.*/_x000D_
background-color:green;/*Only for the demo.*/_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#text {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
<span id="text">Text align to center bottom.</span>_x000D_
</div>
_x000D_
Using PowerShell, you can use the following
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name
This will show a list off all services which displayname starts with "NATION-".
You can also directly stop or start the services;
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service
or simply
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service
SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)
Never returns any records unless eotm_dyn
is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn
like
SELECT * from employees
WHERE NOT EXISTS (
SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)
assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.
In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE
function.
SET SERVEROUTPUT ON
DECLARE
x VARCHAR2(10);
BEGIN
x := owa_util.ite('a' = 'b','T','F');
dbms_output.put_line(x);
END;
/
F
PL/SQL procedure successfully completed.
Personally I would use the Maven surefire JUnit runner to do that.
This is how I do it:
std::string removeAll(std::string str, char c) {
size_t offset = 0;
size_t size = str.size();
size_t i = 0;
while (i < size - offset) {
if (str[i + offset] == c) {
offset++;
}
if (offset != 0) {
str[i] = str[i + offset];
}
i++;
}
str.resize(size - offset);
return str;
}
Basically whenever I find a given char, I advance the offset and relocate the char to the correct index. I don't know if this is correct or efficient, I'm starting (yet again) at C++ and i'd appreciate any input on that.
You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session
(cookie) variable before redirecting and then get the variable before rendering the template. For example:
from flask import session, url_for
def do_baz():
messages = json.dumps({"main":"Condition failed on page baz"})
session['messages'] = messages
return redirect(url_for('.do_foo', messages=messages))
@app.route('/foo')
def do_foo():
messages = request.args['messages'] # counterpart for url_for()
messages = session['messages'] # counterpart for session
return render_template("foo.html", messages=json.loads(messages))
(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)
Or you could probably just use Flask Message Flashing if you just need to show simple messages.
JUnit 5 update (and my opinion)
I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?
By default, unit testing libraries don't try to execute tests in the order that occurs in the source file.
JUnit 5 as JUnit 4 work in that way. Why ? Because if the order matters it means that some tests are coupled between them and that is undesirable for unit tests.
So the @Nested
feature introduced by JUnit 5 follows the same default approach.
But for integration tests, the order of the test method may matter since a test method may change the state of the application in a way expected by another test method.
For example when you write an integration test for a e-shop checkout processing, the first test method to be executed is registering a client, the second is adding items in the basket and the last one is doing the checkout. If the test runner doesn't respect that order, the test scenario is flawed and will fail.
So in JUnit 5 (from the 5.4 version) you have all the same the possibility to set the execution order by annotating the test class with @TestMethodOrder(OrderAnnotation.class)
and by specifying the order with @Order(numericOrderValue)
for the methods which the order matters.
For example :
@TestMethodOrder(OrderAnnotation.class)
class FooTest {
@Order(3)
@Test
void checkoutOrder() {
System.out.println("checkoutOrder");
}
@Order(2)
@Test
void addItemsInBasket() {
System.out.println("addItemsInBasket");
}
@Order(1)
@Test
void createUserAndLogin() {
System.out.println("createUserAndLogin");
}
}
Output :
createUserAndLogin
addItemsInBasket
checkoutOrder
By the way, specifying @TestMethodOrder(OrderAnnotation.class)
looks like not needed (at least in the 5.4.0 version I tested).
Side note
About the question : is JUnit 5 the best choice to write integration tests ? I don't think that it should be the first tool to consider (Cucumber and co may often bring more specific value and features for integration tests) but in some integration test cases, the JUnit framework is enough. So that is a good news that the feature exists.
I had this same issue, but the way I fixed it was by going to the applicationhost.config and remove a port which was not added by me (IIS Express I would guess) which placed my specific port site on another port.
Here is what the config file had for my bindings:
<bindings>
<binding protocol="http" bindingInformation="*:54764:localhost" />
<binding protocol="https" bindingInformation="*:44360:localhost" />
</bindings>
I removed the first bindings item as the only port I wanted was 44360. My config file now looks like this:
<bindings>
<binding protocol="https" bindingInformation="*:44360:localhost" />
</bindings>
Now I don't see the error when I debug.
I also noticed my second API in my project had port 80 also assigned to it, I removed that as well.
First, Eloquent automatically converts it's timestamps (created_at
, updated_at
) into carbon objects. You could just use updated_at
to get that nice feature, or specify edited_at
in your model in the $dates
property:
protected $dates = ['edited_at'];
Now back to your actual question. Carbon has a bunch of comparison functions:
eq()
equalsne()
not equalsgt()
greater thangte()
greater than or equalslt()
less thanlte()
less than or equalsUsage:
if($model->edited_at->gt($model->created_at)){
// edited at is newer than created at
}
Just for others (like me) who might have faced the above error. The solution in simple terms.
You might have missed to register your Interface and class (which implements that inteface) registration in your code.
e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"
Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below
container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();
Both
find()
andchildren()
methods are used to filter the child of the matched elements, except the former is travels any level down, the latter is travels a single level down.
To simplify:
find()
– search through the matched elements’ child, grandchild, great-grandchild... all levels down.children()
– search through the matched elements’ child only (single level down).<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<!-- get all project dependencies -->
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<!-- bind to the packaging phase -->
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
If it's a DNS problem, you could try:
If this doesn't fix it, you could try editing the hosts file located here:
C:\Windows\System32\drivers\etc\hosts
And ensure that this line (and no other line referencing localhost) is in there:
127.0.0.1 localhost
From other post:
find /c "string" file >NUL
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
Use the /i switch when you want case insensitive checking:
find /i /c "string" file >NUL
Or something like: if not found write to file.
find /c "%%P" file.txt || ( echo %%P >> newfile.txt )
Or something like: if found write to file.
find /c "%%P" file.txt && ( echo %%P >> newfile.txt )
Or something like:
find /c "%%P" file.txt && ( echo found ) || ( echo not found )
What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full
svn resolve --accept base
Short answer: You can't.
Long answer:
Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:
public class Foo<T>
{
private Class<T> type;
public Foo(Class<T> type) { this.type = type; }
}
Usage example:
Foo<Integer> test = new Foo<Integer>(Integer.class);
That really works.
Simple,
Easy to understand,
Single method to set and update plugin which worked for me.
$(".datepicker").datepicker("update", new Date());
Other ways to update
$('.datepicker').data({date: '2015-01-01'});
$('.datepicker').datepicker('update');
Dont forget to call update
manually.
In my case, if I remove the the contentType
, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify()
to the data as mentioned in the update of this answer.
It's important to point out that install
and install:install
are different things, install
is a phase, in which maven do more than just install current project modules artifacs to local repository, it check remote repository first. On the other hand, install:install
is a goal, it just build your current project and install all it's artifacts to local repository (e.g. into the .m2
directory).
Update for tslint v5.8.0
As mentioned by Saugat Acharya, you can now update tslint.json CLI Options:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"lib/*generated.js"
]
}
}
More information in this pull request.
This feature has been introduced with tslint 3.6
tslint \"src/**/*.ts\" -e \"**/__test__/**\"
You can now add --exclude (or -e) see PR here.
CLI
usage: tslint [options] file ...
Options:
-c, --config configuration file
--force return status code 0 even if there are lint errors
-h, --help display detailed help
-i, --init generate a tslint.json config file in the current working directory
-o, --out output file
-r, --rules-dir rules directory
-s, --formatters-dir formatters directory
-e, --exclude exclude globs from path expansion
-t, --format output format (prose, json, verbose, pmd, msbuild, checkstyle) [default: "prose"]
--test test that tslint produces the correct output for the specified directory
-v, --version current version
you are looking at using
-e, --exclude exclude globs from path expansion
To check the emptiness of a queryset:
if orgs.exists():
# Do something
or you can check for a the first item in a queryset, if it doesn't exist it will return None
:
if orgs.first():
# Do something
The accepted answer previously contained new Buffer()
, which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).
The Buffer
constructor is deprecated according to the documentation.
Here is an example of a vulnerability that can result from using it in the ws library.
The code snippets should read:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
After this answer was written, it has been updated and now matches this.
Output of git push
when pushing a new branch
> git checkout -b new_branch
Switched to a new branch 'new_branch'
> git push
fatal: The current branch new_branch has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin new_branch
A simple git push
assumes that there already exists a remote branch that the current local branch is tracking. If no such remote branch exists, and you want to create it, you must specify that using the -u
(short form of --set-upstream
) flag.
Why this is so? I guess the implementers felt that creating a branch on the remote is such a major action that it should be hard to do it by mistake. git push
is something you do all the time.
"Isn't a branch a new change to be pushed by default?" I would say that "a change" in Git is a commit. A branch is a pointer to a commit. To me it makes more sense to think of a push as something that pushes commits over to the other repositories. Which commits are pushed is determined by what branch you are on and the tracking relationship of that branch to branches on the remote.
You can read more about tracking branches in the Remote Branches chapter of the Pro Git book.
You can also use flexbox, but you'd have to add a parent div that covers div#top
and div#term-defs
. So the HTML looks like this:
#content {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
#term-defs {_x000D_
flex-grow: 1;_x000D_
overflow: auto;_x000D_
}
_x000D_
<body>_x000D_
<div id="content">_x000D_
<div id="top">_x000D_
<a href="#A">A</a> |_x000D_
<a href="#B">B</a> |_x000D_
<a href="#Z">Z</a>_x000D_
</div>_x000D_
_x000D_
<div id="term-defs">_x000D_
<dl>_x000D_
<span id="A"></span>_x000D_
<dt>foo</dt>_x000D_
<dd>This is the sound made by a fool</dd>_x000D_
<!-- and so on ... -->_x000D_
</dl>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
flex-grow
ensures that the div's size is equal to the remaining size.
You could do the same without flexbox, but it would be more complicated to work out the height of #term-defs
(you'd have to know the height of #top
and use calc(100% - 999px)
or set the height of #term-defs
directly).
With flexbox dynamic sizes of the divs are possible.
One difference is that the scrollbar only appears on the term-defs div
.
One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:
SELECT a.ID,
a.AText,
(SELECT Count(ID)
FROM table1 b WHERE b.ID <= a.ID
AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;
I find it's easier to use the form echo $LIST | xargs -n1 echo | grep $VALUE
as illustrated below:
LIST="ITEM1 ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | xargs -n1 echo | grep -e \"^$VALUE`$\" ]; then
...
fi
This works for a space-separated list, but you could adapt it to any other delimiter (like :
) by doing the following:
LIST="ITEM1:ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | sed 's|:|\\n|g' | grep -e \"^$VALUE`$\"`" ]; then
...
fi
Note that the "
are required for the test to work.
What you are possibly looking for is map()
. You can "convert" the objects in a stream to another by mapping this way:
...
.map(userMeal -> new UserMealExceed(...))
...
DateTime values should be inserted as if they are strings surrounded by single quotes
'20201231'
but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME)
to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:
CREATE TABLE dbo.T(D DATETIME)
--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')
--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))
public class CloneableList<T> : List<T>, ICloneable where T : ICloneable
{
public object Clone()
{
var clone = new List<T>();
ForEach(item => clone.Add((T)item.Clone()));
return clone;
}
}
We do it that way: First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter. We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.
The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.
A little reminder, when elements are added dynamically, functions like append()
, appendTo()
, prepend()
or prependTo()
return a jQuery object, not the HTML DOM element.
var container=$("div.container").get(0),
htmlA="<div class=children>A</div>",
htmlB="<div class=children>B</div>";
// jQuery object
alert( $(container).append(htmlA) ); // outputs "[object Object]"
// HTML DOM element
alert( $(container).append(htmlB).get(0) ); // outputs "[object HTMLDivElement]"
Tip: It's always good to use the -Script
switch for migration commands if you're not sure. It also really helps understand what Update-Database
actually does.
I run the following to update the database, then I get a script I can apply manually (or just run it again without the -Script tag).
For Update-Database
I would run the following :
Update-Database -Script -ConfigurationTypeName Configuration_ASPNETIdentity -ConnectionStringName SQL_AzureLive
Where SQL_AzureLive
is the named connection string in my config.
Then I can verify the SQL looks right, apply it and be done. As many others have said if the connection string is wrong or invalid you'll get this error.
What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:
var newUL = $('<ul><li>test</li></ul>');
$(this).append(newUL);
// Later ...
newUL.remove();
Usually with printf
(or one of its cousins) using the %x
format specifier.
If replacement is of different length:
If replacement is of same length:
This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.
Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.
This is very confusing, and if you are using IDE like pycharm, it's little more confusing. What worked for me: 1. Make pycharm project settings (if you are running python from a VE or from python directory) 2. There is no wrong the way you defined. sometime it works with from folder1.file1 import class
if it does not work, use import folder1.file1 3. Your environment variable should be correctly mentioned in system or provide it in your command line argument.
Try this
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
I did it with jQuery:
page.execute_script %Q{ $('#some_id').prop('checked', true) }
You can easily pass it as an environment variable
docker run .. -e HOST_HOSTNAME=`hostname` ..
using
-e HOST_HOSTNAME=`hostname`
will call the hostname and use it's return as an environment variable called HOST_HOSTNAME
, of course you can customize the key as you like.
note that this works on bash shell, if you using a different shell you might need to see the alternative for "backtick", for example a fish
shell alternative would be
docker run .. -e HOST_HOSTNAME=(hostname) ..
[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.
[Original answer]:
It is pretty clear in the documentation. depends_on
decides the dependency and the order of container creation and links
not only does these, but also
Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.
For example, assuming the following docker-compose.yml
file:
web:
image: example/my_web_app:latest
links:
- db
- cache
db:
image: postgres:latest
cache:
image: redis:latest
With links
, code inside web
will be able to access the database using db:5432
, assuming port 5432 is exposed in the db
image. If depends_on
were used, this wouldn't be possible, but the startup order of the containers would be correct.
Selecting is often unnecessary. Try this
Sub OneCell()
Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
End Sub
I had this error when I had specified fromGroupName instead of formArrayName.
Make sure you correctly specify if it is a form array or form group.
<div formGroupName="formInfo"/>
<div formArrayName="formInfo"/>
I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
From the article:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
Edit:
But my trusty compiler says, XslTransform
is obsolete: Use XslCompiledTransform
instead:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
If you are unsure of the size of the array or if it can change you can do this to have a static array.
ArrayList<Player> thePlayersList = new ArrayList<Player>();
thePlayersList.add(new Player(1));
thePlayersList.add(new Player(2));
.
.
//Some code here that changes the number of players e.g
Players[] thePlayers = thePlayersList.toArray();
Pointy's answer suggests the use of an object literal as an alternative to switch
or if
/else
. I like this approach too, but the code in the answer creates a new map
object every time the dispatch
function is called:
function dispatch(funCode) {
var map = {
'explode': function() {
prepExplosive();
if (flammable()) issueWarning();
doExplode();
},
'hibernate': function() {
if (status() == 'sleeping') return;
// ... I can't keep making this stuff up
},
// ...
};
var thisFun = map[funCode];
if (thisFun) thisFun();
}
If map
contains a large number of entries, this can create significant overhead. It's better to set up the action map only once and then use the already-created map each time, for example:
var actions = {
'explode': function() {
prepExplosive();
if( flammable() ) issueWarning();
doExplode();
},
'hibernate': function() {
if( status() == 'sleeping' ) return;
// ... I can't keep making this stuff up
},
// ...
};
function dispatch( name ) {
var action = actions[name];
if( action ) action();
}
In Python 2.6 or greater it's a bit cleaner:
except Exception as e: print(e)
In older versions it's still quite readable:
except Exception, e: print e
asynchronous call ping
command to block current code to execution in specified milliseconds.
ping
command is Cross-platformstart /b
means: start program but
not show window.code as below:
const { execSync } = require('child_process')
// delay(blocking) specified milliseconds
function sleep(ms) {
// special Reserved IPv4 Address(RFC 5736): 192.0.0.0
// refer: https://en.wikipedia.org/wiki/Reserved_IP_addresses
execSync(`start /b ping 192.0.0.0 -n 1 -w ${ms} > nul`)
}
// usage
console.log("delay 2500ms start\t:" + (new Date().getTime() / 1000).toFixed(3))
sleep(2500)
console.log("delay 2500ms end\t:" + (new Date().getTime() / 1000).toFixed(3))
notice important: Above is not a precision solution, it just approach the blocking time
See How to Make Dialogs.
You can use:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.
This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:
CREATE EVENT event_name
ON SCHEDULE
EVERY 1 DAY
STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
DO
# Your awesome query
If you are absolutely sure that your Python library path is in your system variables (and you can find that path when you pip install Jupyter, you just have to read a bit) and you still experience "command not found or recognized" errors in Windows, you can try:
python -m notebook
For my Windows at least (Windows 10 Pro), having the python -m
is the only way I can run my Python packages from command line without running into some sort of error
Fatal error in launcher: Unable to create process using ' "
or
Errno 'THIS_PROGRAM' not found
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
Just add layout_weight="1" to in your linearLayout which having Buttons.
Edit :- let me make it simple
follow something like below, tags name may not be correct, it is just an Idea
<LL>// Top Parrent LinearLayout
<LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
<LL2 height="wrap_content" weight="1" orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen
<LL/> TOP PARENT CLOSED
Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.
Change the directory of the Project and re-open.
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
then:
pause_menu.pause_button.someProperty //evaluates to "prop1"
etc etc.
I was having the same problem and even though I was styling my button in CSS it would never pick up the border:none
but what worked was adding a style directly on the input button like so:
<div style="text-align:center;">
<input type="submit" class="SubmitButtonClass" style="border:none;" value="" />
</div>
To debug Windows Services I combine GFlags and a .reg file created by regedit.
Or save the following snippets and replace servicename.exe with the desired executable name.
debugon.reg:
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe] "GlobalFlag"="0x00000000" "Debugger"="vsjitdebugger.exe"
debugoff.reg:
Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe] "GlobalFlag"="0x00000000"
If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]"
does the matching, result will be in $Matches[0]
npm login
is required before publish
Easy
if (lblExample.ForeColor != System.Drawing.Color.Red)
{
lblExample.ForeColor = System.Drawing.Color.Red;
}
else
{
lblExample.ForeColor = new System.Drawing.Color();
}
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
I think @Zack properly answered the question but just to cover all the bases:
Update myTable set MyColumn = NULL
This would set the entire column to null as the Question Title asks.
To set a specific row on a specific column to null use:
Update myTable set MyColumn = NULL where Field = Condition.
This would set a specific cell to null as the inner question asks.
A framework provides functionalities/solution to the particular problem area.
Definition from wiki:
A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.
Try it this way in a simple manner it will work
$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";
Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()
if (authUserList != null && _list.Count() > 0)
_list = _list.Where(l => authUserList.Contains(l.CreateUserId));
For me the problem was maven couldn't find the settings.xml file which is located in myMavenFolder\conf.
What I did to fix the issue was to select the right location of the settings.xml file from eclipse:
Window -> Preferences -> Maven -> User Settings
Finally, hit apply and update your project
There's also now this option: http://code.google.com/p/csharp-sqlite/ - a complete port of SQLite to C#.
Try something like grep -r -n -i --include="*.html *.php *.js" searchstrinhere .
the -i
makes it case insensitlve
the .
at the end means you want to start from your current directory, this could be substituted with any directory.
the -r
means do this recursively, right down the directory tree
the -n
prints the line number for matches.
the --include
lets you add file names, extensions. Wildcards accepted
For more info see: http://www.gnu.org/software/grep/
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
This will work for ENUM type as default value
ALTER TABLE engagete_st.holidays add column `STATUS` ENUM('A', 'D') default 'A' AFTER `H_TYPE`;
I'll interpret your question as two questions: 1) why ->
even exists, and 2) why .
does not automatically dereference the pointer. Answers to both questions have historical roots.
Why does ->
even exist?
In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator ->
had very exclusive meaning, not synonymous with *
and .
combination
The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare
struct S {
int a;
int b;
};
and name a
would stand for offset 0, while name b
would stand for offset 2 (assuming int
type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare
struct X {
int a;
int x;
};
and that would be OK, since the name a
would consistently stand for offset 0. But this additional declaration
struct Y {
int b;
int a;
};
would be formally invalid, since it attempted to "redefine" a
as offset 2 and b
as offset 0.
And this is where the ->
operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these
int i = 5;
i->b = 42; /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */
The first assignment was interpreted by the compiler as "take address 5
, add offset 2
to it and assign 42
to the int
value at the resultant address". I.e. the above would assign 42
to int
value at address 7
. Note that this use of ->
did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).
This sort of trickery was not possible with *
and .
combination. You could not do
(*i).b = 42;
since *i
is already an invalid expression. The *
operator, since it is separate from .
, imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the ->
operator, which is independent from the type of the left-hand operand.
As Keith noted in the comments, this difference between ->
and *
+.
combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1
be of pointer type, the expression E1->MOS
is exactly equivalent to (*E1).MOS
Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of ->
operator became fully identical to the functionality of *
and .
combination.
Why can't .
dereference the pointer automatically?
Again, in CRM version of the language the left operand of the .
operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->
, as explained above). Note that CRM did not require the left operand of .
to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this
struct S { int a, b; };
struct T { float x, y, z; };
struct T c;
c.b = 55;
In this case the compiler would write 55
into an int
value positioned at byte-offset 2 in the continuous memory block known as c
, even though type struct T
had no field named b
. The compiler would not care about the actual type of c
at all. All it cared about is that c
was an lvalue: some sort of writable memory block.
Now note that if you did this
S *s;
...
s.b = 42;
the code would be considered valid (since s
is also an lvalue) and the compiler would simply attempt to write data into the pointer s
itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.
I.e. in that version of the language your proposed idea about overloading operator .
for pointer types would not work: operator .
already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.
Of course, this weird functionality is not a very strong reason against introducing overloaded .
operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.
(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)
Inside the component put the input box in the following way.
<input className="class-name"
type= "text"
id="id-123"
value={ this.state.value || "" }
name="field-name"
placeholder="Enter Name"
/>
Re the solution for SqlBulkCopy:
I used the StreamReader to convert and process the text file. The result was a list of my object.
I created a class than takes Datatable
or a List<T>
and a Buffer size (CommitBatchSize
). It will convert the list to a data table using an extension (in the second class).
It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.
Here is the class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class BulkUploadToSql<T>
{
public IList<T> InternalStore { get; set; }
public string TableName { get; set; }
public int CommitBatchSize { get; set; }=1000;
public string ConnectionString { get; set; }
public void Commit()
{
if (InternalStore.Count>0)
{
DataTable dt;
int numberOfPages = (InternalStore.Count / CommitBatchSize) + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
{
dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
BulkInsert(dt);
}
}
}
public void BulkInsert(DataTable dt)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = TableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dt);
connection.Close();
}
// reset
//this.dataTable.Clear();
}
}
public static class BulkUploadToSqlHelper
{
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
}
Here is an example when I want to insert a List of my custom object List<PuckDetection>
(ListDetections
):
var objBulk = new BulkUploadToSql<PuckDetection>()
{
InternalStore = ListDetections,
TableName= "PuckDetections",
CommitBatchSize=1000,
ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();
The BulkInsert
class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)
//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
Another reason> someone changed the password for the default SQL user
this happened to me a couple of minutes ago by switching to a new domain controller ...
Try it:
document.querySelector("input").addEventListener("keyup", function () {
this.value = this.value.replace(/\D/, "")
});
INSERT INTO vendors (
name,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customer_id
)
SELECT
name,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customer_id
FROM
customers;
Java is faster than Python. Easily.
Python is favorable for many things; speed isn't necessarily one of them.
Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.
Untested....but should work.
Dim lastrow as long
lastrow = range("D65000").end(xlup).Row
ActiveCell.FormulaR1C1 = _
"=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
Selection.AutoFill Destination:=Range("E2:E" & lastrow)
'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
Range("E2:E1344").Select
Only exception being are you sure your Autofill code is perfect...
You can try this:
Hope it works for you..
`private void validateUserEntry()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}`
Yes! By passing a stream context in the third parameter:
Here with a timeout of 1s:
file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));
Source in comment section of https://www.php.net/manual/en/function.file-get-contents.php
method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout
Other contexts: https://www.php.net/manual/en/context.php
In addition to the accepted answer, if you are using Android Studio you can
Android Device Monitor
,Devices
tab on the left,File Explorer
tab on the right,Pull a file from the device
button to save it to your local file systemLike for me -> working is:
string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png";
image1.Source = new BitmapImage(new Uri(strUri2));
Try this:
*:focus {
outline: none;
}
This would affect all your pages.
Just a note ..
add:
android:name=".Globals"
or whatever you named your subclass to the existing <application>
tag. I kept trying to add another <application>
tag to the manifest and would get an exception.
You need to modify the config-db.php
and set your password to the password you gave to the user root
, or else if he has no password leave as this ''
.
Holla/Hello, I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.
I just made two changes and I don't which help.
Go to IIS 6 Manager
Select properties of SMTP server
On tab Access, select Relays
Add your public IP address
Close the dialog and on the same tab click to Authentication button.
Add Integrated Windows Authentication
Maybe some step is not needed, but it works.
From your post, I understand that you cannot set the width to your li.
How about this?
ul {
border:2px solid red;
display:inline-block;
}
li {
display:inline;
padding:0 30%; /* try adjusting the side % to give a feel of center aligned.*/
}
_x000D_
<ul>
<li>Hello</li>
<li>Hezkdhkfskdhfkllo</li>
<li>Hello</li>
</ul>
_x000D_
Here's a demo. http://codepen.io/anon/pen/HhBwx
The answer of @abbotto did not work for me, had to do some things differently:
In my case (I'm using VS 2017) works fine the following simple code:
#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
for (int i = 1000; i > 0; i--) //try it thousand times
{
int randnum = (double)rand() / ((double)RAND_MAX + 1);
std::cout << " rnum: " << rand()%2 ;
}
}
If you are 100% sure that you have just one stash or you want to delete all stashes (make a git stash list
to be 107% sure), you can do a:
git stash clear
..and forget about them (it deletes all stashes).
Note: Added this answer for those who ended up here looking for a way to clear them all (like me).
For Windows you can check it using PowerShell
$PathInvalidChars = [System.IO.Path]::GetInvalidPathChars() #36 chars
To display UTF-8 codes you can convert
$enc = [system.Text.Encoding]::UTF8
$PathInvalidChars | foreach { $enc.GetBytes($_) }
$FileNameInvalidChars = [System.IO.Path]::GetInvalidFileNameChars() #41 chars
$FileOnlyInvalidChars = @(':', '*', '?', '\', '/') #5 chars - as a difference
What worked here : on the client
1) ssh-add
2) ssh-copy-id user@server
The keys has been created some time ago with plain "ssh-keygen -t rsa" I sw the error message because I copied across my ssh public key from client to server (with ssh-id-copy) without running ssh-add first, since I erroneously assumed I'd added them some time earlier.
select column1 || ' ' || column2 as whole_name FROM tablename;
Here ||
is the concat operator used for concatenating them to single column and (''
) inside ||
used for space between two columns.
When you want to remove a string, rather than replace it you can use String#delete
(or its mutator equivalent String#delete!
), e.g.:
x = "foo\nfoo"
x.delete!("\n")
x
now equals "foofoo"
In this specific case String#delete
is more readable than gsub
since you are not actually replacing the string with anything.
You can use spring-rest-template-logger to log RestTemplate
HTTP traffic.
Add a dependency to your Maven project:
<dependency>
<groupId>org.hobsoft.spring</groupId>
<artifactId>spring-rest-template-logger</artifactId>
<version>2.0.0</version>
</dependency>
Then customize your RestTemplate
as follows:
RestTemplate restTemplate = new RestTemplateBuilder()
.customizers(new LoggingCustomizer())
.build()
Ensure that debug logging is enabled in application.properties
:
logging.level.org.hobsoft.spring.resttemplatelogger.LoggingCustomizer = DEBUG
Now all RestTemplate HTTP traffic will be logged to org.hobsoft.spring.resttemplatelogger.LoggingCustomizer
at debug level.
DISCLAIMER: I wrote this library.
I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)
Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.
In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.
Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).
Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter Source: http://php.net/manual/en/function.stream-get-line.php
Your first problem was you weren't using your compare symbols correctly.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
To answer your other questions; get the condition to work on every cell in the column and what about blanks?
What about blanks?
Add an extra IF
condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())
Condition on every cell in column
If you mean a python script, just do something like this:
import importlib.util
import sys
# For illustrative purposes.
name = 'itertools'
if name in sys.modules:
print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
# If you choose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
print(f"{name!r} has been imported")
else:
print(f"can't find the {name!r} module")
try:
import mymodule
except ImportError as e:
pass # module doesn't exist, deal with it.
try:
import mymodule
except ImportError, e:
pass # module doesn't exist, deal with it.
if anyone cares i ended up with:
a {
color: inherit;
}
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
If the customer does not exist, you'll get an sql exception which text will be something like:
null value in column "customer_id" violates not-null constraint
(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:
insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);
Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.
Late answer, but you can take advantage of the fact that you can deserialize multiple objects from one JSON string, as long as the objects don't share any common property names,
public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
var jsonString = await request.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<Content >(jsonString);
var config = JsonConvert.DeserializeObject<Config>(jsonString);
}
After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution
- Right click on installer(.exe)
- Select properties option.
- Click on checkbox to check Unblock at the bottom of Properties.
This solution work for Heroku CLI (heroku-x64) installer(.exe)
for me shelling-out does the job because it gives you possibility to run [a|any] command on the shell:
http://www.dba-oracle.com/t_display_current_directory_sqlplus.htm
in short see the current directory:
!pwd
change it
!cd /path/you/want
This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.
Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.
Cheers!
USE [master]
GO
/****** Object: StoredProcedure [SP_Set].[TrasferDataAtColumnLevel] Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
@database varchar(100),
@table varchar(100),
@column varchar(100),
@position int,
@datatype varchar(20)
)
AS
BEGIN
set nocount on
exec ('
declare @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
select column_name, data_type, character_maximum_length, ORDINAL_POSITION from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN
if(@oldCPos = ' + @position + ')
begin
exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end
if(@oldCDataType != ''timestamp'')
begin
set @columns += @oldC + '' , ''
set @columnVars += ''@'' + @oldC + '' , ''
if(@oldCLen is null)
begin
if(@oldCDataType != ''uniqueidentifier'')
begin
set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
else
begin
set @printVars += '' print convert(varchar(50),@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
end
else
begin
if(@oldCLen < 0)
begin
set @oldCLen = 4000
end
set @printVars += '' print @'' + @oldC
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
end
end
if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
alter table Test drop column dummy
end
FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR
set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, '' '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars)))
create table query (id int identity(1,1), string varchar(max))
insert into query values (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')
insert into query values (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')
insert into query values (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')
insert into query values (@printVars )
insert into query values ( '' insert into Test ('')
insert into query values (@columns)
insert into query values ( '') values ( '' + @columnVars + '')'')
insert into query values (''FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')
declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S '' + @@servername + '' -T''
exec master..xp_cmdshell @query
set @query = ''sqlcmd -S '' + @@servername + '' -i '' + @path
EXEC xp_cmdshell @query
set @query = ''del '' + @path
exec xp_cmdshell @query
drop table ' + @database + '._.' + @table + '
select * into ' + @database + '._.' + @table + ' from Test
drop table query
drop table Test ')
END
I think that CONTAINS
took longer and used Merge
because you had a dash("-") in your query adventure-works.com
.
The dash is a break word so the CONTAINS
searched the full-text index for adventure
and than it searched for works.com
and merged the results.
Create a ThreadSafeInvoke.snippet file, and then you can just select the update statements, right click and select 'Surround With...' or Ctrl-K+S:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>ThreadsafeInvoke</Title>
<Shortcut></Shortcut>
<Description>Wraps code in an anonymous method passed to Invoke for Thread safety.</Description>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[
Invoke( (MethodInvoker) delegate
{
$selected$
});
]]>
</Code>
</Snippet>
</CodeSnippet>
Check if the activity isFinishing()
before showing the fragment.
Example:
if(!isFinishing()) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DummyFragment dummyFragment = DummyFragment.newInstance();
ft.add(R.id.dummy_fragment_layout, dummyFragment);
ft.commitAllowingStateLoss();
}
Just in case, for anyone still encountering the issue despite following the above, check that the simulator you are running is also the supported one. I had mine specified to arm7 and arm7s but was trying to run the app on a 64 bit simulator.
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
Another recursive solution
public static String reverse(ArrayList<Float> list) {
if (list.size() == 1) {
return " " +list.get(0);
}
else {
return " "+ list.remove(list.size() - 1) + reverse(list);
}
}
You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with
Dim a = My.Resources.Whatever_you_chose
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
You have said you can only load scripts from your own site (self). You have then tried to load a script from another site (www.google.com) and, because you've restricted this, you can't. That's the whole point of Content Security Policy (CSP).
You can change your first line to:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://www.google.com">
Or, alternatively, it may be worth removing that line completely until you find out more about CSP. Your current CSP is pretty lax anyway (allowing unsafe-inline
, unsafe-eval
and a default-src
of *
), so it is probably not adding too much value, to be honest.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
//Function for inverse of the input square matrix 'J' of dimension 'dim':
vector<vector<double > > inverseVec33(vector<vector<double > > J, int dim)
{
//Matrix of Minors
vector<vector<double > > invJ(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
for(int j=0; j<dim; j++)
{
invJ[i][j] = (J[(i+1)%dim][(j+1)%dim]*J[(i+2)%dim][(j+2)%dim] -
J[(i+2)%dim][(j+1)%dim]*J[(i+1)%dim][(j+2)%dim]);
}
}
//determinant of the matrix:
double detJ = 0.0;
for(int j=0; j<dim; j++)
{ detJ += J[0][j]*invJ[0][j];}
//Inverse of the given matrix.
vector<vector<double > > invJT(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
for(int j=0; j<dim; j++)
{
invJT[i][j] = invJ[j][i]/detJ;
}
}
return invJT;
}
void main()
{
//given matrix:
vector<vector<double > > Jac(3,vector<double > (3));
Jac[0][0] = 1; Jac[0][1] = 2; Jac[0][2] = 6;
Jac[1][0] = -3; Jac[1][1] = 4; Jac[1][2] = 3;
Jac[2][0] = 5; Jac[2][1] = 1; Jac[2][2] = -4;`
//Inverse of the matrix Jac:
vector<vector<double > > JacI(3,vector<double > (3));
//call function and store inverse of J as JacI:
JacI = inverseVec33(Jac,3);
}
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
not really. Server side code is happening on the server--- you can use javascript to display something to the user on the client side, but it obviously will only execute on the client side. This is the nature of a client server web technology. You're basically disconnected from the server when you get your response.
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)
You can use round function. Here some example
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']
The problem you'll face is that there's two types of PEM formatted keys: PKCS8 and SSLeay. It doesn't help that OpenSSL seems to use both depending on the command:
The usual openssl genrsa
command will generate a SSLeay format PEM. An export from an PKCS12 file with openssl pkcs12 -in file.p12
will create a PKCS8 file.
The latter PKCS8 format can be opened natively in Java using PKCS8EncodedKeySpec
. SSLeay formatted keys, on the other hand, can not be opened natively.
To open SSLeay private keys, you can either use BouncyCastle provider as many have done before or Not-Yet-Commons-SSL have borrowed a minimal amount of necessary code from BouncyCastle to support parsing PKCS8 and SSLeay keys in PEM and DER format: http://juliusdavies.ca/commons-ssl/pkcs8.html. (I'm not sure if Not-Yet-Commons-SSL will be FIPS compliant)
By inference from the OpenSSL man pages, key headers for two formats are as follows:
PKCS8 Format
Non-encrypted: -----BEGIN PRIVATE KEY-----
Encrypted: -----BEGIN ENCRYPTED PRIVATE KEY-----
SSLeay Format
-----BEGIN RSA PRIVATE KEY-----
(These seem to be in contradiction to other answers but I've tested OpenSSL's output using PKCS8EncodedKeySpec
. Only PKCS8 keys, showing ----BEGIN PRIVATE KEY-----
work natively)
Could this do for you? Check my JSFiddle
And the code:
HTML
<div class="container">
<div class="div1">Div 1</div>
<div class="div2">Div 2</div>
</div>
CSS
div.container {
background-color: #FF0000;
margin: auto;
width: 304px;
}
div.div1 {
border: 1px solid #000;
float: left;
width: 150px;
}
div.div2 {
border: 1px solid red;
float: left;
width: 150px;
}
As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count()
is deprecated. Instead of using count()
, the alternatives are the following:
Model.countDocuments(filterObject, callback)
Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.
Model.estimatedDocumentCount()
This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments()
, because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.
Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec()
if you want to execute a query at a later time.
For example, count all documents in a collection using .countDocuments()
:
someModel.countDocuments({}, function(err, docCount) {
if (err) { return handleError(err) } //handle possible errors
console.log(docCount)
//and do some other fancy stuff
})
Or, count all documents in a collection having a certain name using .countDocuments()
:
someModel.countDocuments({ name: 'Snow' }, function(err, docCount) {
//see other example
}
.then()
A mongoose query has .then()
so it’s “thenable”. This is for a convenience and query itself is not a promise.
For example, count all documents in a collection using .estimatedDocumentCount()
:
someModel
.estimatedDocumentCount()
.then(docCount => {
console.log(docCount)
//and do one super neat trick
})
.catch(err => {
//handle possible errors
})
When using async/await approach, the recommended way is to use it with .exec()
as it provides better stack traces.
const docCount = await someModel.countDocuments({}).exec();
Learning by stackoverflowing,
I have a library that is doing exactly you need.
Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter
It works with CSV like with 2 dimensions array. Exactly like you need.
As example, in case of you need all of values of 3rd row only you need is to write:
Csv csv = new Csv();
csv.FileOpen("c:\\file1.csv");
var allValuesOf3rdRow = csv.Rows[2];
or to read 2nd cell of
var value = csv.Rows[2][1];
Try This Code :
button.setVisibility(View.INVISIBLE);
Here is what is going on.
First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)
All you have to do to make a module-global variable is just assign to a name.
Imagine a file called foo.py, containing this single line:
X = 1
Now imagine you import it.
import foo
print(foo.X) # prints 1
However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global
declaration in your function, before you try to use the global.
def initDB(name):
global __DBNAME__ # add this line!
if __DBNAME__ is None: # see notes below; explicit test for None
__DBNAME__ = name
else:
raise RuntimeError("Database name has already been set.")
By the way, for this example, the simple if not __DBNAME__
test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename
; in that case, you should explicitly test for None
using the is
operator. I modified the example to add an explicit None
test. The explicit test for None
is never wrong, so I default to using it.
Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an import * from mymodule
, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule
and then say dir(mymodule)
you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__
Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.
It is considered best practice in Python not to do import *
, but to minimize the coupling and maximize explicitness by either using mymodule.something
or by explicitly doing an import like from mymodule import something
.
EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global
keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.
In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.
You can use a list
but your code will be ugly:
__DBNAME__ = [None] # use length-1 list as a mutable
# later, in code:
if __DBNAME__[0] is None:
__DBNAME__[0] = name
A dict
is better. But the most convenient is a class instance, and you can just use a trivial class:
class Box:
pass
__m = Box() # m will contain all module-level values
__m.dbname = None # database name global in module
# later, in code:
if __m.dbname is None:
__m.dbname = name
(You don't really need to capitalize the database name variable.)
I like the syntactic sugar of just using __m.dbname
rather than __m["DBNAME"]
; it seems the most convenient solution in my opinion. But the dict
solution works fine also.
With a dict
you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box
in the above.
Apart from the fact that cloning is from server to your machine and forking is making a copy on the server itself, an important difference is that when we clone, we actually get all the branches, labels, etc.
But when we fork, we actually only get the current files in the master branch, nothing other than that. This means we don't get the other branches, etc.
Hence if you have to merge something back to the original repository, it is a inter-repository merge and will definitely need higher privileges.
Fork is not a command in Git; it is just a concept which GitHub implements. Remember Git was designed to work in peer-to-peer environment without the need to synchronize stuff with any master copy. The server is just another peer, but we look at it as a master copy.
Note: the commit 5e1361c from brian m. carlson (bk2204
) (for git 1.9/2.0 Q1 2014) deals with a special case in term of log decoration with tags:
log: properly handle decorations with chained tags
git log
did not correctly handle decorations when a tag object referenced another tag object that was no longer a ref, such as when the second tag was deleted.
The commit would not be decorated correctly becauseparse_object
had not been called on the second tag and therefore its tagged field had not been filled in, resulting in none of the tags being associated with the relevant commit.Call
parse_object
to fill in this field if it is absent so that the chain of tags can be dereferenced and the commit can be properly decorated.
Include tests as well to prevent future regressions.
Example:
git tag -a tag1 -m tag1 &&
git tag -a tag2 -m tag2 tag1 &&
git tag -d tag1 &&
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=gmailpassword
[email protected]
need authenticate username and password of mail then only once can successfully send mail from localhost
For Mac OSX I had to do
tar -zcv --exclude='folder' -f theOutputTarFile.tar folderToTar
Note the -f
after the --exclude=
I hope you can find the following brief example helpful:
<!DOCTYPE html>
<html>
<head>
<script>
function checkGender(){
if(document.getElementById('male').checked) {
alert("Selected gender: "+document.getElementById('male').value)
}else if(document.getElementById('female').checked) {
alert("Selected gender: "+document.getElementById('female').value)
}
else{
alert("Please choose your gender")
}
}
</script>
</head>
<body>
<h1>Select your gender:</h1>
<form>
<input type="radio" id="male" name="gender" value="male">Male<br>
<input type="radio" id="female" name="gender" value="female">Female<br>
<button onclick="checkGender()">Check gender</button>
</form>
</body>
</html>
In the code, note that both 'name' attributes are the same to define optionality between 'male' or 'female', but the 'id's are not equals to differentiate them.
Assume a dataframe with 19 rows
index=range(0,19)
index
columns=['A']
test = pd.DataFrame(index=index, columns=columns)
Keeping Column A as a constant
test['A']=10
Keeping column b as a variable given by a loop
for x in range(0,19):
test.loc[[x], 'b'] = pd.Series([x], index = [x])
You can replace the first x in pd.Series([x], index = [x])
with any value
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
Only works for Linux but Using the "sh" python module you can simply call any shell command
pip install sh
import sh
sh.file("/root/file")
Output: /root/file: ASCII text
I like the kind of redirection after counting seconds
<?php
header("Refresh: 3;url=https://theweek.com.br/índex.php");
Solution 1 : You can Quit simulator
and try again.
Solution 2 (Recommended) : Go to iOS Simulator
-> Reset Content and Settings...
This will pop-up an alert stating 'Are you sure you want to reset the iOS Simulator content and settings?'
Select Reset
if you wish to or else Don't Reset
button.
Note that once you reset simulator content all app installed on simulator will be deleted and it will reset to initial settings.
Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True
parameter to the app.run()
call, like:
app.run(host="your.host", port=4321, threaded=True)
Another option as per what we can see in the werkzeug docs, is to use the processes
parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:
- threaded – should the process handle each request in a separate thread?
- processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.
Something like:
app.run(host="your.host", port=4321, processes=3) #up to 3 processes
More info on the run()
method here, and the blog post that led me to find the solution and api references.
Note: on the Flask docs on the run()
methods it's indicated that using it in a Production Environment is discouraged because (quote): "While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well."
However, they do point to their Deployment Options page for the recommended ways to do this when going for production.
Run the following commands from git CLI:
# move to the wanted commit
git reset --hard <commit-hash>
# update remote
git push --force origin <branch-name>
The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.
class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}
Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.
// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}
// .cpp file
//...
template <typename T> void Foo::some_method(T t)
{//...}
//...
template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);
An other approach is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the MySql JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".
Let me share my fix in ASP.NET MVC 4. The main idea like in correct answer for PHP. The next code added in main Layout in header near scripts section:
@if (Request.Browser.Browser=="Safari")
{
string pageUrl = Request.Url.GetLeftPart(UriPartial.Path);
if (Request.Params["safarifix"] != null && Request.Params["safarifix"] == "doSafariFix")
{
Session["IsActiveSession"] = true;
Response.Redirect(pageUrl);
Response.End();
}
else if(Session["IsActiveSession"]==null)
{
<script>top.window.location = "?safarifix=doSafariFix";</script>
}
}
<form id="yourFormName" >
<input type="text" value="" id="val1">
<input type="text" value="" id="val2">
<input type="text" value="" id="val3">
<button type="button" onclick="yourFunction()"> Check </button>
</form>
<script type="text/javascript">
function yourFunction()
{
var elements = document.querySelectorAll("#yourFormName input[type=text]")
console.log(elements);
for (var i = 0; i<elements.length; i++ )
{
var check = document.getElementById(elements[i].id).value);
console.log(check);
// write your logic here
}
}
</script>
Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:
function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
range:testRange,
value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}
Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
Little unrelated but I will still put it here, For other practical purposes shell variables can be used as -
value=10
jq '."key" = "'"$value"'"' file.json
Example query below, here are some details on how I solved it.
Using DATEDIFF(WK, ...)
will give us the number of weeks between the 2 dates. SQL Server evaluates this as a difference between week numbers rather than based on the number of days. This is perfect, since we can use this to determine how many weekends passed between the dates.
So we can multiple that value by 2 to get the number of weekend days that occurred and subtract that from the DATEDIFF(dd, ...)
to get the number of weekdays.
This doesn't behave 100% correctly when the start or end date falls on Sunday, though. So I added in some case logic at the end of the calculation to handle those instances.
You may also want to consider whether or not the DATEDIFF
should be fully inclusive. e.g. Is the difference between 9/10 and 9/11 1 day or 2 days? If the latter, you'll want to add 1 to the final product.
declare @d1 datetime, @d2 datetime
select @d1 = '9/9/2011', @d2 = '9/18/2011'
select datediff(dd, @d1, @d2) - (datediff(wk, @d1, @d2) * 2) -
case when datepart(dw, @d1) = 1 then 1 else 0 end +
case when datepart(dw, @d2) = 1 then 1 else 0 end
You need to close the input element with />
at the end. In React, we have to close every element. Your code should be:
<input id="icon_prefix" type="text" class="validate/">
This is how you get rid of that notice and be able to open those grid cells for edit
1) click "STRUCTURE"
2) go to the field you want to be a primary key (and this usually is the 1st one ) and then click on the "PRIMARY" and "INDEX" fields for that field and accept the PHPMyadmin's pop-up question "OK".
3) pad yourself in the back.
From here what I understand DataFrames are:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
And Series are:
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
Series have a name
attribute which can be accessed like so:
In [27]: s = pd.Series(np.random.randn(5), name='something')
In [28]: s
Out[28]:
0 0.541
1 -1.175
2 0.129
3 0.043
4 -0.429
Name: something, dtype: float64
In [29]: s.name
Out[29]: 'something'
EDIT: Based on OP's comments, I think OP was looking for something like:
>>> df = pd.DataFrame(...)
>>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
>>> print(df.name)
'df'
Date Between Query
SELECT *
FROM emp
WHERE HIREDATE between to_date (to_char(sysdate, 'yyyy') ||'/09/01', 'yyyy/mm/dd')
AND to_date (to_char(sysdate, 'yyyy') + 1|| '/08/31', 'yyyy/mm/dd');
I wrote an ES6 version based on @Halcyon answer
const array = [
{
id: '12',
parentId: '0',
text: 'one-1'
},
{
id: '6',
parentId: '12',
text: 'one-1-6'
},
{
id: '7',
parentId: '12',
text: 'one-1-7'
},
{
id: '9',
parentId: '0',
text: 'one-2'
},
{
id: '11',
parentId: '9',
text: 'one-2-11'
}
];
// Prevent changes to the original data
const arrayCopy = array.map(item => ({ ...item }));
const listToTree = list => {
const map = {};
const roots = [];
list.forEach((v, i) => {
map[v.id] = i;
list[i].children = [];
});
list.forEach(v => (v.parentId !== '0' ? list[map[v.parentId]].children.push(v) : roots.push(v)));
return roots;
};
console.log(listToTree(arrayCopy));
The principle of this algorithm is to use "map" to establish an index relationship. It is easy to find "item" in the list by "parentId", and add "children" to each "item", because "list" is a reference relationship, so "roots" will Build relationships with the entire tree.
use onmouseup
try something like this
<html>
<head>
<script type="text/javascript">
function hide(){
document.getElementById('span_hide').style.display="none";
}
</script>
</head>
<body>
<a href="page" style="text-decoration:none;display:block;">
<span onmouseup="hide()" id="span_hide">Hide me</span>
</a>
</body>
</html>
EDIT:
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function () {
$(this).fadeTo("fast", .5).removeAttr("href");
});
});
function hide(){
document.getElementById('span_hide').style.display="none";
}
</script>
</head>
<body>
<a href="page.html" style="text-decoration:none;display:block;" onclick="return false" >
<span onmouseup="hide()" id="span_hide">Hide me</span>
</a>
</body>
</html>
shell("cls")
if on Windows,
shell("clear")
if on Linux or Mac.
(shell()
passes a command (or any string) to the host terminal.)
(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)
You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.
Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:
telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)
You should get a response like:
250 2.0.0 Ok: queued as 6E414C4643A
The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:
sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected] [email protected]
[email protected] [email protected]
@localdomain.local [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the
generic file)
Happy Trails
Do import the below statement in your JS file.
import 'rxjs/add/operator/map';
Padding is essentially added to the width, therefore when you say width:100%
and padding: 5px 10px
you're actually adding 20px to the 100% width.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
advise the current "best practice" around
Date
andCalendar
is it best to always favour
Calendar
overDate
Avoid these legacy classes entirely. Use java.time classes instead.
Instant
Date
)ZonedDateTime
GregorianCalendar
)OffsetDateTime
LocalDateTime
The Answer by Ortomala Lokni is right to suggest using the modern java.time classes rather than the troublesome old legacy date-time classes (Date
, Calendar
, etc.). But that Answer suggests the wrong class as equivalent (see my comment on that Answer).
The java.time classes are a vast improvement over the legacy date-time classes, night-and-day difference. The old classes are poorly-designed, confusing, and troublesome. You should avoid the old classes whenever possible. But when you need to convert to/from the old/new, you can do so by calling new methods add to the old classes.
For much more information on conversion, see my Answer and nifty diagram to another Question, Convert java.util.Date to what “java.time” type?.
Searching Stack Overflow gives many hundreds of example Questions and Answers on using java.time. But here is a quick synopsis.
Instant
Get the current moment with an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
ZonedDateTime
To see that same simultaneous moment through the lens of some particular region’s wall-clock time, apply a time zone (ZoneId
) to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone();
A time zone is a region’s history of changes in its offset-from-UTC. But sometimes you are given only an offset without the full zone. In that case, use the OffsetDateTime
class.
ZoneOffset offset = ZoneOffset.parse( "+05:30" );
OffsetDateTime odt = instant.atOffset( offset );
Use of a time zone is preferable over use of a mere offset.
LocalDateTime
The “Local” in the Local…
classes means any locality, not a particular locality. So the name can be counter-intuitive.
LocalDateTime
, LocalDate
, and LocalTime
purposely lack any information about offset or time zone. So they do not represent actual moments, they are not points on the timeline. When in doubt or in confusion, use ZonedDateTime
rather than LocalDateTime
. Search Stack Overflow for much more discussion.
Do not conflate date-time objects with strings that represent their value. You can parse a string to get a date-time object, and you can generate a string from a date-time object. But the string is never the date-time itself.
Learn about standard ISO 8601 formats, used by default in the java.time classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
According to Microsoft documentation, should NEVER use async void
Do not do this: The following example uses
async void
which makes the HTTP request complete when the first await is reached:
Which is ALWAYS a bad practice in ASP.NET Core apps.
Accesses the HttpResponse after the HTTP request is complete.
Crashes the process.
I just came up with this neat workaround
var firstChar = Array(string)[0]
for activity
findViewById(android.R.id.content).setBackgroundColor(color)
You can use yahoo to get daily data (a much more managable dataset) but you have to structure the urls. See this link. You are not making lots of little requests you are making a fewer large requests. Lot of free software uses this so they shouldn't shut you down.
EDIT: This guy does it, maybe you can have a look at the calls his software makes.
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
Output without toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student@2kaa9dc
Student@4bbc148
You can see in the above example #1. printing s1 and s2 prints the Hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:
Example#2
Output with overriding toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
//overriding the toString() method
public String toString(){
return id+" "+name+" "+address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:100 Joe success
50 Jeff fail
Note that toString() mostly is related to the concept of polymorphism in Java. In, Eclipse, try to click on toString() and right click on it.Then, click on Open Declaration and see where the Superclass toString() comes from.
Try to enter the full-path of the dll. If it doesn't work, try to copy the dll into the system32 folder.
If you just want to see the current working directory
import os
print(os.getcwd())
If you want to change the current working directory
os.chdir(path)
path is a string containing the required path to be moved. e.g.
path = "C:\\Users\\xyz\\Desktop\\move here"
The code you have given, needs to be corrected. In form tag you have to enclosed the onClick attribute value in double quote:
"window.open('google.htm','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');"
You also need to take care that first parameter of window.open
should also be enclosed using quotes.