If you want you can use reduce to make a sequential promise, for example:
[2,3,4,5,6,7,8,9].reduce((promises, page) => {
return promises.then((page) => {
console.log(page);
return Promise.resolve(page+1);
});
}, Promise.resolve(1));
it'll always works in sequential.
A simple for loop?
for i in range(3):
do()
Or, if you're interested in the results and want to collect them, with the bonus of being a 1 liner:
vals = [do() for _ in range(3)]
I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.
In TextPad's replace dialog, turn on regex; then you could try replacing
<row id="1"/>
by
<row id="\i"/>
Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/
CPUnit (http://cpunit.sourceforge.net) is a framework that is similar to Google Test, but which relies on less macos (asserts are functions), and where the macros are prefixed to avoid the usual macro pitfall. Tests look like:
#include <cpunit>
namespace MyAssetTest {
using namespace cpunit;
CPUNIT_FUNC(MyAssetTest, test_stuff) {
int some_value = 42;
assert_equals("Wrong value!", 666, some_value);
}
// Fixtures go as follows:
CPUNIT_SET_UP(MyAssetTest) {
// Setting up suite here...
// And the same goes for tear-down.
}
}
They auto-register, so you need not more than this. Then it is just compile and run. I find using this framework very much like using JUnit, for those who have had to spend some time programming Java. Very nice!
Well, both will clean. That means they'll remove the target folder. The real question is what's the difference between package and install?
package
will compile your code and also package it. For example, if your pom says the project is a jar, it will create a jar for you when you package it and put it somewhere in the target directory (by default).
install
will compile and package, but it will also put the package in your local repository. This will make it so other projects can refer to it and grab it from your local repository.
ssh -R youruniquesubdomain:80:localhost:3000 serveo.net
And your local environment can be accessed from https://youruniquesubdomain.serveo.net
I couldn't believe when I found this service. It offers everything and it is the easiest to use. If there would be such an easy and painless tool for every problem...
Purely using MSchimpf and Ahmad's code, I made adjustments so I could have the iframe within a div, therefore keeping a header and footer for back button and branding on my page. Updated code:
<script type="text/javascript">
$("#webview").bind('pagebeforeshow', function(event){
$("#iframe").attr('src',cwebview);
});
if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
{
$("#webview-content").css("width","100%");
$("#webview-content").css("height","100%");
$("#iframe").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
iframeWidth = $("#iframe").contents().width();
if (iframeWidth > 400)
$("#webview-content").css("width",(iframeWidth + 182) + 'px');
iframeHeight = $("#iframe").contents().height();
if (iframeHeight>200)
$("#webview-content").css("height",iframeHeight + 'px');
});
}
</script>
and the html
<div class="header" data-role="header" data-position="fixed">
</div>
<div id="webview-content" data-role="content" style="height:380px;">
<iframe id="iframe"></iframe>
</div><!-- /content -->
<div class="footer" data-role="footer" data-position="fixed">
</div><!-- /footer -->
Ok. I found problem.
It was not on the Angular side. To be honest, there were no problem at all.
Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.
Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS
I implemented proper filter on my server-side app.
Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.
For those using git with Jenkins under a windows system, you need to configure the location of git.exe under: Manage Jenkins => Global Tool Configuration => Git => Path to Git executable and fill-in the path to git.exe, for example; C:\Program Files\Git\bin\git.exe
The difference is :
"If you use !=
, it returns sub-second. If you use <>
, it takes 7 seconds to return. Both return the right answer."
Oracle not equals (!=) SQL operator
Regards
Just choose Original image
option when adding an image to assets
in Xcode
If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):
if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi
Have a nice day
SOAP - Simple Object Access Protocol is a protocol!
REST - REpresentational State Transfer is an architectural style!
SOAP
is an XML protocol used to transfer messages, typically over HTTP
REST
and SOAP
are arguably not mutually exclusive. A RESTful architecture might use HTTP
or SOAP
or some other communication protocol. REST
is optimized for the web and thus HTTP
is a perfect choice. HTTP
is also the only protocol discussed in Roy Fielding's paper.
Although REST and SOAP are clearly very different, the question does illuminate the fact that REST
and HTTP
are often used in tandem. This is primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles.
Client-Server Communication
Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in princple.
Stateless
Each each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.
Cacheable
Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.
Uniform Interface
All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!
The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.
See this blog post on REST Design Principals for more details on REST and the above stated bullets.
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
I use javadoc packaged by Allimant since I was in college.
http://www.allimant.org/javadoc/
The javadoc is in the CHM format (standard windows help format), so it's the best viewed when you're using windows.
You can use functional operation for a more neat code
Set<String> set = new HashSet<String>();
set.forEach((s) -> {
System.out.println(s);
});
ServerRoot "xampp\apache"
ServerRoot "D:\Hacking Tools 2\Programs\XAMPP V2\apache"
ServerRoot "D:\XAMPP\apache"
It worked for me, if it doesn't work for you, just comment with the error value after opening the xampp_start.exe
Configuration
The styles and scripts options in your angular.json configuration now allow to reference a package directly:
before: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
after: "styles": ["bootstrap/dist/css/bootstrap.css"]
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"jquery/dist/jquery.min.js",
"bootstrap/dist/js/bootstrap.min.js"
]
},
Angular v6 Onwards
CLI projects in angular 6 onwards will be using angular.json
instead of .angular-cli.json
for build and project configuration.
Each CLI workspace has projects, each project has targets, and each target can have configurations.Docs
. {
"projects": {
"my-project-name": {
"projectType": "application",
"architect": {
"build": {
"configurations": {
"production": {},
"demo": {},
"staging": {},
}
},
"serve": {},
"extract-i18n": {},
"test": {},
}
},
"my-project-name-e2e": {}
},
}
OPTION-1
execute npm install bootstrap@4 jquery --save
The JavaScript parts of Bootstrap
are dependent on jQuery
. So you need the jQuery
JavaScript
library file too.
In your angular.json add the file paths to the styles and scripts array in under build
target
NOTE:
Before v6 the Angular CLI project configuration was stored in <PATH_TO_PROJECT>/.angular-cli.json.
As of v6 the location of the file changed to angular.json.
Since there is no longer a leading dot, the file is no longer hidden by default and is on the same level.
which also means that file paths in angular.json should not contain leading dots and slash
i.e you can provide an absolute path instead of a relative path
In .angular-cli.json
file Path was "../node_modules/"
In angular.json
it is "node_modules/"
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": ["node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"]
},
OPTION 2
Add files from CDN (Content Delivery Network) to your project CDN LINK
Open file src/index.html and insert
the <link>
element at the end of the head section to include the Bootstrap CSS file
a <script>
element to include jQuery at the bottom of the body section
a <script>
element to include Popper.js at the bottom of the body section
a <script>
element to include the Bootstrap JavaScript file at the bottom of the body section
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<app-root>Loading...</app-root>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
OPTION 3
Execute npm install bootstrap
In src/styles.css
add the following line:
@import "~bootstrap/dist/css/bootstrap.css";
OPTION-4
ng-bootstrap It contains a set of native Angular directives based on Bootstrap’s markup and CSS. As a result, it's not dependent on jQuery or Bootstrap’s JavaScript
npm install --save @ng-bootstrap/ng-bootstrap
After Installation import it in your root module and register it in @NgModule
imports` array
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [AppComponent, ...],
imports: [NgbModule.forRoot(), ...],
bootstrap: [AppComponent]
})
NOTE
ng-bootstrap
requires Bootstrap's 4 css to be added in your project. you need to Install it explicitly via:
npm install bootstrap@4 --save
In your angular.json add the file paths to the styles array in under build
target
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
You switch to:
json_decode($response->getBody(), true)
Instead of the other comment if you want it to work exactly as before in order to get arrays instead of objects.
Here is the simple arraylist example for insertion at specific index
ArrayList<Integer> str=new ArrayList<Integer>();
str.add(0);
str.add(1);
str.add(2);
str.add(3);
//Result = [0, 1, 2, 3]
str.add(1, 11);
str.add(2, 12);
//Result = [0, 11, 12, 1, 2, 3]
I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code
For me it turned out that I had a @JsonManagedReferece
in one entity without a @JsonBackReference
in the other referenced entity. This caused the marshaller to throw an error.
You can just use the built-in function count follow by the groupby function
df.groupby(['col5','col2']).count()
On modern CMake (>= 3.1) the best way to set global requirements is:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
It translates to "I want C++11 for all targets, it's not optional, I don’t want to use any GNU or Microsoft extensions." As of C++17, this still is IMHO the best way.
I opened the Properties window for the website project in question and changed Windows Authentication to "Enabled" and that resolved my issue in VS 2019.
In a new upcoming php7 among many other features, they added a support for strings bigger than 2^31 bytes:
Support for strings with length >= 2^31 bytes in 64 bit builds.
Sadly they did not specify how much bigger can it be.
I wasn't happy with any of the answers here, and went looking for a command-line solution.
In macOS Sierra 10.12, Apple introduced a new way for users to remap keys.
If that sounds good to you, take a look at hidutil
.
For example, to remap caps-lock to escape, refer to the key table and find that caps-lock has usage code 0x39 and escape has usage code 0x29. Put these codes or'd with the hex value 0x700000000 in the source and dest like this:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x700000029}]}'
You may add other mappings in the same command. Personally, I like to remap caps-lock to backspace, and remap backspace to delete:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x70000002A}, {"HIDKeyboardModifierMappingSrc":0x70000002A,"HIDKeyboardModifierMappingDst":0x70000004C}]}'
To see the current mapping:
hidutil property --get "UserKeyMapping"
Your changes will be lost at system reboot. If you want them to persist, configure them in a launch agent. Here's mine:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Place in ~/Library/LaunchAgents/ -->
<!-- launchctl load com.ldaws.CapslockBackspace.plist -->
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.ldaws.CapslockEsc</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/hidutil</string>
<string>property</string>
<string>--set</string>
<string>{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000039,"HIDKeyboardModifierMappingDst":0x70000002A},{"HIDKeyboardModifierMappingSrc":0x70000002A,"HIDKeyboardModifierMappingDst":0x70000004C}]}</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
I've placed this content into a file located at ~/Library/LaunchAgents/com.ldaws.CapslockBackspace.plist
and then executed:
launchctl load com.ldaws.CapslockBackspace.plist
Your activity doesn't extend FragmentActivity from the support library, therefore the method is not present in the superclass
If you are targeting api 11 or above, you could use Activity.getFragmentManager instead.
Just for the record if somebody needs a way to handle signals on Windows. I had a requirement to handle from prog A calling prog B through os/exec but prog B never was able to terminate gracefully because sending signals through ex. cmd.Process.Signal(syscall.SIGTERM) or other signals are not supported on Windows. The way I handled is by creating a temp file as a signal ex. .signal.term through prog A and prog B needs to check if that file exists on interval base, if file exists it will exit the program and handle a cleanup if needed, I'm sure there are other ways but this did the job.
From a blog on running sample variance calculations, where the mean is also calculated using Welford's method:
Too bad we can't upload SVG images.
Uff! what is static initializer?
The static initializer is a static {}
block of code inside java class, and run only one time before the constructor or main method is called.
OK! Tell me more...
static { ... }
inside any java class. and executed by virtual machine when class is called.return
statements are supported.this
or super
are supported.Hmm where can I use it?
Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.
Don't just bark! where is example?
package com.example.learnjava;
import java.util.ArrayList;
public class Fruit {
static {
System.out.println("Inside Static Initializer.");
// fruits array
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Pear");
// print fruits
for (String fruit : fruits) {
System.out.println(fruit);
}
System.out.println("End Static Initializer.\n");
}
public static void main(String[] args) {
System.out.println("Inside Main Method.");
}
}
Output???
Inside Static Initializer.
Apple
Orange
Pear
End Static Initializer.
Inside Main Method.
Hope this helps!
You could try catching the onload event. And stopping the propagation dependent on some flag.
var changeHash = false;
$('ul.questions li a').click(function(event) {
var $this = $(this)
$('.tab').hide(); //you can improve the speed of this selector.
$($this.attr('href')).fadeIn('slow');
StopEvent(event); //notice I've changed this
changeHash = true;
window.location.hash = $this.attr('href');
});
$(window).onload(function(event){
if (changeHash){
changeHash = false;
StopEvent(event);
}
}
function StopEvent(event){
event.preventDefault();
event.stopPropagation();
if ($.browser.msie) {
event.originalEvent.keyCode = 0;
event.originalEvent.cancelBubble = true;
event.originalEvent.returnValue = false;
}
}
Not tested, so can't say if it would work
Use find
with a wildcard:
find . -name 'mystring*'
Or if you use the six library
from six.moves import reduce
I found this solution useful in a NodeJS app. I use it just in desperate cases because it launches a timeout in order to wait for the full page load.
The second argument is the callback function which is going to be called once the response is ready.
phantom = require('phantom');
var fullLoad = function(anUrl, callbackDone) {
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open(anUrl, function (status) {
if (status !== 'success') {
console.error("pahtom: error opening " + anUrl, status);
ph.exit();
} else {
// timeOut
global.setTimeout(function () {
page.evaluate(function () {
return document.documentElement.innerHTML;
}, function (result) {
ph.exit(); // EXTREMLY IMPORTANT
callbackDone(result); // callback
});
}, 5000);
}
});
});
});
}
var callback = function(htmlBody) {
// do smth with the htmlBody
}
fullLoad('your/url/', callback);
If you don't need to use the str
after the while loop (scope related) then the second condition i.e.
while(condition){
String str = calculateStr();
.....
}
is better since if you define an object on the stack only if the condition
is true. I.e. use it if you need it
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
GET (multiple parameters):
curl -X GET "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl --request GET "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl "http://localhost:3000/action?result1=gh&result2=ghk"
or
curl -i -H "Application/json" -H "Content-type: application/json" "http://localhost:3000/action?result1=gh&result2=ghk"
I have solved that problem. The only I do is:
private int num_rows;
And then in your method using the resultset put this code
while (this.rs.next())
{
this.num_rows++;
}
That's all
'
Single quotedThe simplest way to specify a string is to enclose it in single quotes. Single quote is generally faster, and everything quoted inside treated as plain string.
Example:
echo 'Start with a simple string';
echo 'String\'s apostrophe';
echo 'String with a php variable'.$name;
"
Double quotedUse double quotes in PHP to avoid having to use the period to separate code (Note: Use curly braces {}
to include variables if you do not want to use concatenation (.
) operator) in string.
Example:
echo "Start with a simple string";
echo "String's apostrophe";
echo "String with a php variable {$name}";
Yes. It is slightly faster to use single quotes.
PHP won't use additional processing to interpret what is inside the single quote. when you use double quotes PHP has to parse to check if there are any variables within the string.
For Xcode 12: (beta 3)
For the code editing windows, use the new
Editor -> Font Size -> Increase
or
Editor -> Font Size -> Decrease
menu items. This globally increases or decreases the font sizes for all editing windows. There is also an
Editor -> Font Size -> Reset
option. These also respond to the ?+ or ?- keyboard shortcuts.
By default, the file navigator on the left side corresponds to the
System Preferences -> General -> Sidebar icon size
You can also override the system size inside Xcode using the
Xcode -> Preferences -> General -> Navigator Size
KvanTTT's code worked great. I extended it a bit to allow a little more flexibility on save format, as well as the ability to save by hWnd, .NET Control/Form. You can get a bitmap or save to file, with a few options.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace MosaiqPerformanceMonitor {
public enum CaptureMode {
Screen, Window
}
public static class ScreenCapturer {
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
[StructLayout(LayoutKind.Sequential)]
private struct Rect {
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();
/// <summary> Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file. </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
/// <param name="format">Optional file save mode. Default is PNG</param>
public static void CaptureAndSave(string filename, CaptureMode mode = CaptureMode.Window, ImageFormat format = null) {
ImageSave(filename, format, Capture(mode));
}
/// <summary> Capture a specific window (or control) and save it to a specified file. </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="handle">hWnd (handle) of the window to capture</param>
/// <param name="format">Optional file save mode. Default is PNG</param>
public static void CaptureAndSave(string filename, IntPtr handle, ImageFormat format = null) {
ImageSave(filename, format, Capture(handle));
}
/// <summary> Capture a specific window (or control) and save it to a specified file. </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="c">Object to capture</param>
/// <param name="format">Optional file save mode. Default is PNG</param>
public static void CaptureAndSave(string filename, Control c, ImageFormat format = null) {
ImageSave(filename, format, Capture(c));
}
/// <summary> Capture the active window (default) or the desktop and return it as a bitmap </summary>
/// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
public static Bitmap Capture(CaptureMode mode = CaptureMode.Window) {
return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow());
}
/// <summary> Capture a .NET Control, Form, UserControl, etc. </summary>
/// <param name="c">Object to capture</param>
/// <returns> Bitmap of control's area </returns>
public static Bitmap Capture(Control c) {
return Capture(c.Handle);
}
/// <summary> Capture a specific window and return it as a bitmap </summary>
/// <param name="handle">hWnd (handle) of the window to capture</param>
public static Bitmap Capture(IntPtr handle) {
Rectangle bounds;
var rect = new Rect();
GetWindowRect(handle, ref rect);
bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);
var result = new Bitmap(bounds.Width, bounds.Height);
using (var g = Graphics.FromImage(result))
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
return result;
}
/// <summary> Position of the cursor relative to the start of the capture </summary>
public static Point CursorPosition;
/// <summary> Save an image to a specific file </summary>
/// <param name="filename">Filename.
/// <para>* If extension is omitted, it's calculated from the type of file</para>
/// <para>* If path is omitted, defaults to %TEMP%</para>
/// <para>* Use %NOW% to put a timestamp in the filename</para></param>
/// <param name="format">Optional file save mode. Default is PNG</param>
/// <param name="image">Image to save. Usually a BitMap, but can be any
/// Image.</param>
static void ImageSave(string filename, ImageFormat format, Image image) {
format = format ?? ImageFormat.Png;
if (!filename.Contains("."))
filename = filename.Trim() + "." + format.ToString().ToLower();
if (!filename.Contains(@"\"))
filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename);
filename = filename.Replace("%NOW%", DateTime.Now.ToString("[email protected]"));
image.Save(filename, format);
}
}
}
For 500 records efficiency is probably not an issue, but if you have millions of records then it can be advantageous to use a WHERE clause to select the next page:
SELECT *
FROM yourtable
WHERE id > 234374
ORDER BY id
LIMIT 20
The "234374" here is the id of the last record from the prevous page you viewed.
This will enable an index on id to be used to find the first record. If you use LIMIT offset, 20
you could find that it gets slower and slower as you page towards the end. As I said, it probably won't matter if you have only 200 records, but it can make a difference with larger result sets.
Another advantage of this approach is that if the data changes between the calls you won't miss records or get a repeated record. This is because adding or removing a row means that the offset of all the rows after it changes. In your case it's probably not important - I guess your pool of adverts doesn't change too often and anyway no-one would notice if they get the same ad twice in a row - but if you're looking for the "best way" then this is another thing to keep in mind when choosing which approach to use.
If you do wish to use LIMIT with an offset (and this is necessary if a user navigates directly to page 10000 instead of paging through pages one by one) then you could read this article about late row lookups to improve performance of LIMIT with a large offset.
Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:
<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
</script>
<br /><br />
<input type="submit" />
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
I use the following (Uses Consolas size 11 on Windows, Menlo Regular size 14 on Mac OS X and Inconsolata size 12 everywhere else):
if has("gui_running")
if has("gui_gtk2")
set guifont=Inconsolata\ 12
elseif has("gui_macvim")
set guifont=Menlo\ Regular:h14
elseif has("gui_win32")
set guifont=Consolas:h11:cANSI
endif
endif
Edit: And while you're at it, you could take a look at Coding Horror's Programming Fonts blog post.
Edit²: Added MacVim.
Assuming that winrar.exe
is in the PATH
, then Runtime.exec
is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe
is installed in C:/Program Files/WinRAR
you would need to use something like...
p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");
Personally, I would recommend that you use ProcessBuilder
as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String
elements, it deals with things like spaces much better then a single String
variable, for example...
ProcessBuilder pb = new ProcessBuilder(
"C:/Program Files/WinRAR/winrar",
"x",
"myjar.jar",
"*.*",
"new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
Don't forget to read the contents of the InputStream
from the process, as failing to do so may stall the process
Answering an old and accepted question here. You can add this in your pom.xml if you want to avoid passing command line argument all the time:
<properties>
<skipTests>true</skipTests>
</properties>
The code:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
The output of java Test abcdef
:
last character: f
To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the BufferedReader return null which means there's no more data to read. Each line will appended to a StringBuilder and returned as String.
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}`
And finally from any class where you want to convert call the function
String dataString = Utils.convertStreamToString(in);
complete
I found mine here on a OSX system /usr/local/var/mongodb
Take a look at this thread: http://code.google.com/p/chromium/issues/detail?id=4158
The problem is caused by javascript method "window.open(URL, windowName[, windowFeatures])". If the 3rd parameter windowFeatures is specified, then alert box doesn't work in the popup constrained window in Chrome, here is a simplified reduction:
http://go/reductions/4158/test-home-constrained.html
If the 3rd parameter windowFeatures is ignored, then alert box works in the popup in Chrome(the popup is actually opened as a new tab in Chrome), like this:
http://go/reductions/4158/test-home-newtab.html
it doesn't happen in IE7, Firefox3 or Safari3, it's a chrome specific issue.
See also attachments for simplified reductions
I also faced a similar error while compiling my C-based code. I fixed the issue by correcting the source file path in my cmake
file. Please check the source file path of each source file mentioned in your cmake
file. This might help you too.
Note that you have to be careful if your row contains a factor. Here is an example:
df_1 = data.frame(V1 = factor(11:15),
V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns
[1] 1 21
Here is another example (by default data.frame() converts characters to factors)
df_2 = data.frame(V1 = letters[1:5],
V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"
To prevent this behavior, you need to take care of the factor, before extracting it:
df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11 21
df_2[3,] %>% as.character()
[1] "c" "3"
I was unable to make use of the most popular answer because the --batch-check
command-line switch to Git 1.8.3 (that I have to use) does not accept any arguments. The ensuing steps have been tried on CentOS 6.5 with Bash 4.1.2
In Git, the term blob implies the contents of a file. Note that a commit might change the contents of a file or pathname. Thus, the same file could refer to a different blob depending on the commit. A certain file could be the biggest in the directory hierarchy in one commit, while not in another. Therefore, the question of finding large commits instead of large files, puts matters in the correct perspective.
Command to print the list of blobs in descending order of size is:
git cat-file --batch-check < <(git rev-list --all --objects | \
awk '{print $1}') | grep blob | sort -n -r -k 3
Sample output:
3a51a45e12d4aedcad53d3a0d4cf42079c62958e blob 305971200
7c357f2c2a7b33f939f9b7125b155adbd7890be2 blob 289163620
To remove such blobs, use the BFG Repo Cleaner, as mentioned in other answers. Given a file blobs.txt
that just contains the blob hashes, for example:
3a51a45e12d4aedcad53d3a0d4cf42079c62958e
7c357f2c2a7b33f939f9b7125b155adbd7890be2
Do:
java -jar bfg.jar -bi blobs.txt <repo_dir>
The question is about finding the commits, which is more work than finding blobs. To know, please read on.
Given a commit hash, a command that prints hashes of all objects associated with it, including blobs, is:
git ls-tree -r --full-tree <commit_hash>
So, if we have such outputs available for all commits in the repo, then given a blob hash, the bunch of commits are the ones that match any of the outputs. This idea is encoded in the following script:
#!/bin/bash
DB_DIR='trees-db'
find_commit() {
cd ${DB_DIR}
for f in *; do
if grep -q $1 ${f}; then
echo ${f}
fi
done
cd - > /dev/null
}
create_db() {
local tfile='/tmp/commits.txt'
mkdir -p ${DB_DIR} && cd ${DB_DIR}
git rev-list --all > ${tfile}
while read commit_hash; do
if [[ ! -e ${commit_hash} ]]; then
git ls-tree -r --full-tree ${commit_hash} > ${commit_hash}
fi
done < ${tfile}
cd - > /dev/null
rm -f ${tfile}
}
create_db
while read id; do
find_commit ${id};
done
If the contents are saved in a file named find-commits.sh
then a typical invocation will be as under:
cat blobs.txt | find-commits.sh
As earlier, the file blobs.txt
lists blob hashes, one per line. The create_db()
function saves a cache of all commit listings in a sub-directory in the current directory.
Some stats from my experiments on a system with two Intel(R) Xeon(R) CPU E5-2620 2.00GHz processors presented by the OS as 24 virtual cores:
Note that the script is single threaded. Therefore, only one core would be used at any one time.
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
If you have vectors destined to become rows, concatenate them using c()
, pass them to a matrix row-by-row, and convert that matrix to a dataframe.
For example, rows
dummydata1=c(2002,10,1,12.00,101,426340.0,4411238.0,3598.0,0.92,57.77,4.80,238.29,-9.9)
dummydata2=c(2002,10,2,12.00,101,426340.0,4411238.0,3598.0,-3.02,78.77,-9999.00,-99.0,-9.9)
dummydata3=c(2002,10,8,12.00,101,426340.0,4411238.0,3598.0,-5.02,88.77,-9999.00,-99.0,-9.9)
can be converted to a data frame thus:
dummyset=c(dummydata1,dummydata2,dummydata3)
col.len=length(dummydata1)
dummytable=data.frame(matrix(data=dummyset,ncol=col.len,byrow=TRUE))
Admittedly, I see 2 major limitations: (1) this only works with single-mode data, and (2) you must know your final # columns for this to work (i.e., I'm assuming that you're not working with a ragged array whose greatest row length is unknown a priori).
This solution seems simple, but from my experience with type conversions in R, I'm sure it creates new challenges down-the-line. Can anyone comment on this?
You can use CTE to get the distinct values of the second table, and then join that with the first table. You also need to get the distinct values based on LastName column. You do this with a Row_Number() partitioned by the LastName, and sorted by the FirstName.
Here's the code
;WITH SecondTableWithDistinctLastName AS
(
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY LastName ORDER BY FirstName) AS [Rank]
FROM AddTbl
)
AS tableWithRank
WHERE tableWithRank.[Rank] = 1
)
SELECT a.FirstName, a.LastName, S.District
FROM SecondTableWithDistinctLastName AS S
INNER JOIN AddTbl AS a
ON a.LastName = S.LastName
ORDER BY a.FirstName
I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh
To get records from the last 24 hours:
SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
While you can do OO in C (e.g. by adding a theType *this
first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).
I would suggest at least looking at a re-design to compare how this would work out.
Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?
Like this:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
The $(this)
refers to the current .target
which will be looped through. Within this .target
I'm looking for the .scrolling img
and get the width. And then keep on going...
Images with different widths
If you want to calculate the width of all images (when they have different widths) you can do it like this:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
I'd say the minimum would be to
There is no need for jQuery here, regular JavaScript will do:
var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);
Or, the .split()
and .pop()
version:
var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();
Or, the regex version (several variants of this):
var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];
For thoroughness, I came across another solution which was part of the functionality introduced in version 1.4.3 of the jQuery click event handler.
It allows you to pass a data map to the event object that automatically gets fed back to the event handler function by jQuery as the first parameter. The data map would be handed to the .click()
function as the first parameter, followed by the event handler function.
Here's some code to illustrate what I mean:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
I know it's late in the game for this question, but the previous answers led me to this solution, so I hope it helps someone sometime!
Since nobody provided this code yet:
SELECT TOP @limit f1, f2, f3...
FROM t1
WHERE c1 = v1, c2 > v2...
AND
t1.id NOT IN
(SELECT TOP @offset id
FROM t1
WHERE c1 = v1, c2 > v2...
ORDER BY o1, o2...)
ORDER BY o1, o2...
Important points:
@limit
can be replaced with number of results to retrieve,@offset
is number of results to skipwhere
and order by
clauses, and will provide incorrect results if they are out of syncorder by
is there explicitly if that's what's needed On linux, if you can afford the run time cost (for debugging), you can use valgrind with the massif tool:
http://valgrind.org/docs/manual/ms-manual.html
It is heavy weight, but very useful.
For convert UNIX(LF) to Windows(CR-LF) use next command
type file.txt > new_file.txt
this is how you mock requests.post, change it to your http method
@patch.object(requests, 'post')
def your_test_method(self, mockpost):
mockresponse = Mock()
mockpost.return_value = mockresponse
mockresponse.text = 'mock return'
#call your target method now
One of many solutions is to create an @Injectable()
class which holds data that you want to show in the header. Other components can also access this class and alter this data, effectively changing the header.
Another option is to set up @Input()
variables and @Output()
EventEmitters which you can use to alter the header data.
Edit Examples as you requested:
@Injectable()
export class HeaderService {
private _data;
set data(value) {
this._data = value;
}
get data() {
return this._data;
}
}
in other component:
constructor(private headerService: HeaderService) {}
// Somewhere
this.headerService.data = 'abc';
in header component:
let headerData;
constructor(private headerService: HeaderService) {
this.headerData = this.headerService.data;
}
I haven't actually tried this. If the get/set doesn't work you can change it to use a Subject();
// Simple Subject() example:
let subject = new Subject();
this.subject.subscribe(response => {
console.log(response); // Logs 'hello'
});
this.subject.next('hello');
I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.
var blob = new Blob([s2ab(atob(data))], {
type: ''
});
href = URL.createObjectURL(blob);
The s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
You can do it in Python 2.7+ with python-dateutil
(which is insalled on Mac by default):
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'
Or you if you want to convert from an existed stored string:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT)
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)
There is no need to kill entire session. In Oracle 18c you could use ALTER SYSTEM CANCEL
:
Cancelling a SQL Statement in a Session
You can cancel a SQL statement in a session using the ALTER SYSTEM CANCEL SQL statement.
Instead of terminating a session, you can cancel a high-load SQL statement in a session. When you cancel a DML statement, the statement is rolled back.
ALTER SYSTEM CANCEL SQL 'SID, SERIAL[, @INST_ID][, SQL_ID]';
If @INST_ID is not specified, the instance ID of the current session is used.
If SQL_ID is not specified, the currently running SQL statement in the specified session is terminated.
class Addition {
public static void main() {
int arr[]={5,10,15,20,25,30}; //Declaration and Initialization of an Array
int sum=0; //To find the sum of array elements
for(int i:arr) {
sum += i;
}
System.out.println("The sum is :"+sum);//To display the sum
}
}
It is 2019 and previous answers to this problem are not using
CSS grid is the way to do forms in 2019 as you can have your labels preceding your inputs without having extra divs, spans, spans with asterisks in and other relics.
Here is where we are going with minimal CSS:
The HTML for the above:
<form action="https://www.example.com/register/" method="post" id="form-validate" enctype="multipart/form-data">
<p class="form-instructions">Please enter the following information to create your account.</p>
<label for="firstname">First name</label>
<input type="text" id="firstname" name="firstname" value="" title="First name" maxlength="255" required="">
<label for="lastname">Last name</label>
<input type="text" id="lastname" name="lastname" value="" title="Last name" maxlength="255" required="">
<label for="email_address">Email address</label>
<input type="email" autocapitalize="off" autocorrect="off" spellcheck="false" name="email" id="email_address" value="" title="Email address" size="30" required="">
<label for="password">Password</label>
<input type="password" name="password" id="password" title="Password" required="">
<label for="confirmation">Confirm password</label>
<input type="password" name="confirmation" title="Confirm password" id="confirmation" required="">
<input type="checkbox" name="is_subscribed" title="Subscribe to our newsletter" value="1" id="is_subscribed" class="checkbox">
<label for="is_subscribed">Subscribe to the newsletter</label>
<input type="checkbox" name="persistent_remember_me" id="remember_meGCJiRe0GbJ" checked="checked" title="Remember me">
<label for="remember_meGCJiRe0GbJ">Remember me</label>
<p class="required">* Required</p>
<button type="submit" title="Register">Register</button>
</form>
Placeholder text can be added too and is highly recommended. (I am just answering this mid-form).
Now for the CSS variables:
--icon-required: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="-10 -6 16 16"> \
<line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(15)"></line> \
<line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(75)"></line> \
<line id="line" y1="-3" y2="3" stroke="%23df0000" stroke-linecap="butt" transform="rotate(-45)"></line> \
</svg>');
--icon-tick: url('data:image/svg+xml,\
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="-2 -2 16 16"> \
<path fill="green" stroke-linejoin="round" d="M2 6L1 7l3 4 7-10h-1L4 8z"/> \
</svg>');
The CSS for the form elements:
input[type=text][required],
input[type=email][required],
input[type=password][required],
input[type=tel][required] {
background-image: var(--icon-required);
background-position-x: right;
background-repeat: no-repeat;
background-size: contain;
}
input:valid {
--icon-required: var(--icon-tick);
}
The form itself should be in CSS grid:
form {
align-items: center;
display: grid;
grid-gap: var(--form-grid-gap);
grid-template-columns: var(--form-grid-template-columns);
margin: auto;
}
The values for the columns can be set to 1fr auto
or 1fr
with anything such as <p>
tags in the form set to span 1/-1. You change the variables in your media queries so that you have the input boxes going full width on mobile and as per above on desktop. You can also change your grid gap on mobile if you wish by using the CSS variables approach.
When the boxes are valid then you should get a green tick instead of the asterisk.
The SVG in CSS is a way of saving the browser from having to do a round trip to the server to get an image of the asterisk. In this way you can fine tune the asterisks, the examples here are at an unusual angle, you can edit this out as the SVG icon above is entirely readable. The viewbox can also be amended to place the asterisk above or below the centre.
Although this question is fairly old, there is another possibility: If you are using Storyboards, you simply have to set the CellIdentifier in the Storyboard.
So if your CellIdentifier is "Cell", just set the "Identifier" property:
Make sure to clean your build after doing so. XCode sometimes has some issues with Storyboard updates
I am a Mac OS user & following credential pair worked for me:
Username: admin
Password: admin
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==
|===
).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false
).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if
. But, on the second one, every true-ish value will enter the if
: false
, 0
, null
, undefined
and empty strings, would not.
Try this in your css:
.a {
transition: color 0.3s ease-in-out;
}
.a {
color:turquoise;
}
.a:hover {
color: #454545;
}
First, to make things more clear, here is a short overview of JSP syntax elements:
There are several mechanisms for reusing content in a JSP file.
The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")
1) The include directive:
<%@ include file="header.html" %>
Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.
2) The
<jsp:include>
standard action:<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.
3) The
<c:import>
JSTL tag:<c:import url=”http://www.example.com/foo/bar.html” />
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like
<jsp:include>
, but it’s more powerful and flexible: unlike the other two includes, the<c:import>
url can be from outside the web Container!4) Preludes and codas:
Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding<include-prelude>
and<include-coda>
elements respectively within a<jsp-property-group>
element in the Web application web.xml deployment descriptor. Read more here:
• Configuring Implicit Includes at the Beginning and End of JSPs
• Defining implicit includes
Tag File is an indirect method of content reuse, the way of encapsulating reusable content. A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.
The PURPOSE of includes and Tag Files is different.
Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags. Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.
Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.
Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can
Be customized by means of attributes passed from the calling page.
Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.
Be nested within one another and communicate by means of private variables.
Also read this from "Pro JSP 2": Understanding JSP Custom Tags.
Difference between include directive and include action in JSP
Very informative and easy to understand tutorial from coreservlet.com with beautiful
explanations that include <jsp:include> VS. <%@ include %>
comparison table:
Including Files and Applets in JSP
Pages
Another nice tutorial from coreservlets.com related to tag libraries and
tag files:
Creating Custom JSP Tag Libraries: The
Basics
The official Java EE 5 Tutorial with examples:
Encapsulating Reusable Content
Using Tag
Files.
This page from the official Java EE 5 tutorial should give you even
more understanding:
Reusing Content in JSP
Pages.
This excerpt from the book "Pro JSP 2" also discuses why do you need
a Tag File instead of using static include:
Reusing Content with Tag
Files
Very useful guide right from the Oracle documentation:
Static Includes Versus Dynamic Includes
Use the right tools for each task.
Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.
As for the including content in JSP (quote from here):
- Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
- Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
For MySQL or PostgreSQL 9.3+, a better way is to use the LEAST
and GREATEST
functions.
SELECT GREATEST(A.date0, B.date0) AS date0,
LEAST(A.date1, B.date1, B.date2) AS date1
FROM A, B
WHERE B.x = A.x
With:
GREATEST(value [, ...])
: Returns the largest (maximum-valued) argument from values providedLEAST(value [, ...])
Returns the smallest (minimum-valued) argument from values providedDocumentation links :
SurfaceView
probably does not work like a regular View
in this regard.
Instead, do the following:
SurfaceView
inside of a
FrameLayout
or RelativeLayout
in
your layout XML file, since both of
those allow stacking of widgets on
the Z-axisView
classFrameLayout
or
RelativeLayout
, but have it appear
after the SurfaceView
This will cause your custom View
class to appear to float above the SurfaceView
.
See here for a sample project that layers popup panels above a SurfaceView
used for video playback.
In this example you can identify different areas:
<html>
<style>
#divContainer {
width: 100%;
height: 100%;
}
#divHeader {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
height: 28px;
background-color:blue;
}
#divContentArea {
position: absolute;
left: 0px;
top: 30px;
right: 0px;
bottom: 30px;
}
#divContentLeft {
position: absolute;
top: 0px;
left: 0px;
width: 200px;
bottom: 0px;
background-color:red;
}
#divContentCenter {
position: absolute;
top: 0px;
left: 200px;
bottom: 0px;
right:200px;
background-color:yellow;
}
#divContentRight {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
width:200px;
background-color:red;
}
#divFooter {
position: absolute;
height: 28px;
left: 0px;
bottom: 0px;
right: 0px;
background-color:blue;
}
</style>
<body >
<div id="divContainer">
<div id="divHeader"> top
</div>
<div id="divContentArea">
<div id="divContentLeft">left
</div>
<div id="divContentCenter">center
</div>
<div id="divContentRight">right
</div>
</div>
<div id="divFooter">bottom
</div>
</div>
</body>
</html>
Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:
print("Why, hello there wonderful "
"stackoverflow people!")
Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/
Floats on both sides now
#wrapper{
background:red;
overflow:auto;
}
#c1{
float:left;
background:blue;
}
#c2{
background:green;
float:right;
}?
<div id="wrapper">
<div id="c1">con1</div>
<div id="c2">con2</div>
</div>?
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
Also, a bit simpler....
>> hash = { "a"=>["a", "b", "c"], "b"=>["b", "c"] }
=> {"a"=>["a", "b", "c"], "b"=>["b", "c"]}
>> hash.values
=> [["a", "b", "c"], ["b", "c"]]
The above answers would help with the ActionBar thing. To add to it, use the following code in case you are using the Splash Screen: Use this before you set the content view:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Just to clarify, here's how you do it:
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
This would make your screen a full screen, i.e remove the top bar where you see the network bar, etc
After I plotted all the lines, I was able to set the transparency of all of them as follows:
for l in fig_field.gca().lines:
l.set_alpha(.7)
EDIT: please see Joe's answer in the comments.
A moving average can also be calculated and visualized directly in a line chart by using the following code:
Example using stock price data:
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
plt.style.use('ggplot')
# Input variables
start = datetime.datetime(2016, 1, 01)
end = datetime.datetime(2018, 3, 29)
stock = 'WFC'
# Extrating data
df = web.DataReader(stock,'morningstar', start, end)
df = df['Close']
print df
plt.plot(df['WFC'],label= 'Close')
plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')
plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')
plt.legend(loc='best')
plt.title('Wells Fargo\nClose and Moving Averages')
plt.show()
Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg
So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:
table.delete(key);
for (K key: table.keySet()) {
// do whatever you need to do with the rest of the keys
}
This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:
def merge_fix_cols(df_company,df_product,uniqueID):
df_merged = pd.merge(df_company,
df_product,
how='left',left_on=uniqueID,right_on=uniqueID)
for col in df_merged:
if col.endswith('_x'):
df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
elif col.endswith('_y'):
to_drop = [col for col in df_merged if col.endswith('_y')]
df_merged.drop(to_drop,axis=1,inplace=True)
else:
pass
return df_merged
Seems to work well with my merges!
In the .NET world there are two types of CLRs, "full" CLRs and Core CLRs, and these are quite different things.
There are two "full" CLR implementations, the Microsoft native .NET CLR (for Windows) and the Mono CLR (which itself has implementations for Windows, linux and unix (Mac OS X and FreeBSD)). A full CLR is exactly that - everything, pretty much, that you need. As such, "full" CLRs tend to be large in size.
Core CLRs are on the other hand are cut down, and much smaller. Because they are only a core implementation, they are unlikely to have everything you need in them, so with Core CLRs you add feature sets to the CLR that your specific software product uses, using NuGet. There are Core CLR implementations for Windows, linux (various) and unix (Mac OS X and FreeBSD) in the mix. Microsoft have or are refactoring the .NET framework libraries for Core CLR too, to make them more portable for the core context. Given mono's presence on *nix OSs it would be a surprise if the Core CLRs for *nix did not include some mono code base, but only the Mono community and Microsoft could tell us that for sure.
Also, I'd concur with Nico in that Core CLRs are new -- it's at RC2 at the moment I think. I wouldn't depend on it for production code yet.
To answer your question you could delivery your site on linux using Core CLR or Mono, and these are two different ways of doing it. If you want a safe bet right now I'd go with mono on linux, then port if you want to later, to Core.
AssemblyInformationalVersion
and AssemblyFileVersion
are displayed when you view the "Version" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a VERSION_INFO
resource that is created by the compiler.
AssemblyInformationalVersion
is the "Product version" value. AssemblyFileVersion
is the "File version" value.
The AssemblyVersion
is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.
Out of these, the only one that is absolutely required by .NET is the AssemblyVersion
attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
There's several ways to do it, depending on your intent.
thisSession.hasOwnProperty('merchant_id');
will tell you if thisSession has that key itself (i.e. not something it inherits from elsewhere)
"merchant_id" in thisSession
will tell you if thisSession has the key at all, regardless of where it got it.
thisSession["merchant_id"]
will return false if the key does not exist, or if its value evaluates to false for any reason (e.g. if it's a literal false
or the integer 0 and so on).
If you execute pip install virtualenvwrapper
without sudo as a normal user pip will run but won't copy the files in the required locations because the lack of permissions.
mortiz@florida:~# sudo pip3 install virtualenvwrapper
Use sudo and the files will be created under their respective paths:
root@florida:/usr/local/bin# ls -ltr
total 8008
-rwxr-xr-x 1 root staff 8136192 Jun 11 17:45 chromedriver
-rwxr-xr-x 1 root staff 41697 Sep 5 16:06 virtualenvwrapper.sh
-rwxr-xr-x 1 root staff 2210 Sep 5 16:06 virtualenvwrapper_lazy.sh
-rwxr-xr-x 1 root staff 215 Sep 5 16:06 pbr
-rwxr-xr-x 1 root staff 218 Sep 5 16:06 virtualenv-clone
-rwxr-xr-x 1 root staff 213 Sep 5 16:06 virtualenv
root@florida:/usr/local/bin#
Worked for me on Debian GNU/Linux 9
Assuming that your search is stylus photo 2100
. Try the following example is using RLIKE
.
SELECT * FROM `buckets` WHERE `bucketname` RLIKE REPLACE('stylus photo 2100', ' ', '+.*');
EDIT
Another way is to use FULLTEXT
index on bucketname
and MATCH ... AGAINST
syntax in your SELECT
statement. So to re-write the above example...
SELECT * FROM `buckets` WHERE MATCH(`bucketname`) AGAINST (REPLACE('stylus photo 2100', ' ', ','));
I ran into similar problems, you might be able to get it to work using a similar method.
First, try this with your current configuration, exclude httpclient
from httpmime
:
dependencies {
compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'
}
In my case, I fixed it by using the following jars :
Then, in the build.gradle, excluding httpclient
from httpmime
:
dependencies {
compile 'com.google.android.gms:play-services:+'
compile('org.apache.httpcomponents:httpmime:4.3.5') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
}
Linux Solution: For example, you want to see all files/folder list of your home (/) directory according to file/folder size (Descending order).
sudo du -xm / | sort -rn | more
while system.gc works,it will stop the world:all respones are stopped so garbage collector can scan every object to check if it is needed deleted. if the application is a web project, all request are stopped until gc finishes,and this will cause your web project can not work in a monent.
Your array.xml is not right. change it to like this
Here is array.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
I had this problem and it wasnt solved by the deleting of any keys (at least deleting them didnt fix it, maybe had an effect after i did fix it though)
I actually had a discrepancy between my sdk-tools version and my Android Studio version. After updating my tools it still didnt work, but after updating AS (to 1.4) everything worked fine again.
Always update both sdk-tools and AS version together ;)
I like to do this by ranking the records by some column. In this case, rank rev
values grouped by id
. Those with higher rev
will have lower rankings. So highest rev
will have ranking of 1.
select id, rev, content
from
(select
@rowNum := if(@prevValue = id, @rowNum+1, 1) as row_num,
id, rev, content,
@prevValue := id
from
(select id, rev, content from YOURTABLE order by id asc, rev desc) TEMP,
(select @rowNum := 1 from DUAL) X,
(select @prevValue := -1 from DUAL) Y) TEMP
where row_num = 1;
Not sure if introducing variables makes the whole thing slower. But at least I'm not querying YOURTABLE
twice.
I had the same problem but I was confused with @Vladislav's answer and couldn't seem to find the solution from that. Of course, my problem may not be exactly the same as I encountered the problem when trying to upgrade XAMPP, but it also gave the same Error 1067 message.
With further search I found this:
The answer from that is straightforward, that is, to completely clean up the folder, which doesn't always happen. As in regards to XAMPP, I guess I backed up the necessary files first (data folder from mysql folder and the htdocs folder). Uninstall XAMPP. Check the xampp folder for any content that remains and delete everything. You may want to reboot afterwards, just in case. Then reinstall XAMPP. Copy the backed-up folders back to their respective places, and hopefully, mySql will work again in XAMPP.
This should solve the issue.
I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.
As the rule of thumb, NumPy arrays often outperform other solutions while working with POD, Plain Old Data. A string is an example of POD and a character too. To find all the indices of only one char in a string, NumPy ndarrays may be the fastest way:
def find1(str, ch):
# 0.100 seconds for 1MB str
npbuf = np.frombuffer(str, dtype=np.uint8) # Reinterpret str as a char buffer
return np.where(npbuf == ord(ch)) # Find indices with numpy
def find2(str, ch):
# 0.920 seconds for 1MB str
return [i for i, c in enumerate(str) if c == ch] # Find indices with python
I know this is old, but here is a one liner solution:
const hourDiff = start.diff(end, "hours");
Where start and end are moment objects.
Enjoy!
NameValueCollection nvclc = Request.Form;
string uName= nvclc ["txtUserName"];
string pswod= nvclc ["txtPassword"];
//try login
CheckLogin(uName, pswod);
For me, this was the best solution:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
}
As per the hibernate
docs here,
Connection connection()
Deprecated. (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use doWork(org.hibernate.jdbc.Work) ...
Use Hibernate Work API instead:
Session session = entityManager.unwrap(Session.class);
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do whatever you need to do with the connection
}
});
Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class
In the shell, you can't execute more than one statement at a time:
>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement
You need to execute them one by one:
>>> x = 5
>>> y = 6
>>>
When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.
If you have this in your CSS file:
.myApp
{
border-bottom-color:#FF0000;
}
and a div for instance of:
<div id="myDiv">test text</div>
you can use:
$("#myDiv").addClass('myApp');// to add the style
$("#myDiv").removeClass('myApp');// to remove the style
or you can just use
$("#myDiv").css( 'border-bottom-color','#FF0000');
I prefer the first example, keeping all the CSS related items in the CSS files.
As string[]
implements IEnumerable
IEnumerable<string> m_oEnum = new string[] {"1","2","3"}
You need to use an iframe
.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content" src="about:blank"></iframe>
</body>
</html
Since the glyphicons image is a sprite, you really can't do that: fundamentally what you want is to limit the size of the background, but there's no way to specify how big the background is. Either you cut out the icon you want, size it down and use it, or use something like the input field prepend/append option (http://twitter.github.io/bootstrap/base-css.html#forms and then search for prepended inputs).
Highlight the cells, format cells, select Custom then select zero.
Two things. First, you must base64 decode the mykey.pem
file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey
ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec
, which is based on the SubjectPublicKeyInfo
ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
// ...
String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
In my case:
sudo -E add-apt-repository ppa:linuxuprising/java
sudo apt-get update
sudo apt install oracle-java12-installer
that works fine
Based on my own testing and the OP's comments, I think at some point they goofed on the casing of the branch name.
First, I believe the OP is on a case insensitive operating system like OS X or Windows. Then they did something like this...
$ git checkout -b SQLMigration/ReportFixes
Switched to a new branch 'SQLMigration/ReportFixes'
$ git push origin SqlMigration/ReportFixes
fatal: SqlMigration/ReportFixes cannot be resolved to branch.
Note the casing difference. Also note the error is very different from if you just typo the name.
$ git push origin SQLMigration/ReportFixme
error: src refspec SQLMigration/ReportFixme does not match any.
error: failed to push some refs to '[email protected]:schwern/testing123.git'
Because Github uses the filesystem to store branch names, it tries to open .git/refs/heads/SqlMigration/ReportFixes
. Because the filesystem is case insensitive it successfully opens .git/refs/heads/SqlMigration/ReportFixes
but gets confused when it tries to compare the branch names case-sensitively and they don't match.
How they got into a state where the local branch is SQLMigration/ReportFixes
and the remote branch is SqlMigration/ReportFixes
I'm not sure. I don't believe Github messed with the remote branch name. Simplest explanation is someone else with push access changed the remote branch name. Otherwise, at some point they did something which managed to create the remote with the typo. If they check their shell history, perhaps with history | grep -i sqlmigration/reportfixes
they might be able to find a command where they mistyped the casing.
You've almost done it. However setting flex: 0 0 <basis>
declaration to the columns would prevent them from growing/shrinking; And the <basis>
parameter would define the width of columns.
In addition, you could use CSS3 calc()
expression to specify the height
of columns with the respect to the height of the header.
#productShowcaseTitle {
flex: 0 0 100%; /* Let it fill the entire space horizontally */
height: 100px;
}
#productShowcaseDetail,
#productShowcaseThumbnailContainer {
height: calc(100% - 100px); /* excluding the height of the header */
}
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 0 0 34%; /* ~ 33.33% */_x000D_
height: calc(100% - 100px); /* excluding the height of the header */_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div>
element, it would be achieved without using calc()
as follows:
<div class="contentContainer"> <!-- Added wrapper -->
<div id="productShowcaseDetail"></div>
<div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
display: flex;
flex-direction: column;
height: 600px; width: 580px;
}
.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }
#productShowcaseContainer {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
height: 100px;_x000D_
background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
flex: 3;_x000D_
background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
<div id="productShowcaseTitle"></div>_x000D_
_x000D_
<div class="contentContainer"> <!-- Added wrapper -->_x000D_
<div id="productShowcaseDetail"></div>_x000D_
<div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
(Vendor prefixes omitted due to brevity)
you probably want to use a separate value that tracks if the input is valid:
good_input = None
while not good_input:
user_input = raw_input("enter the right letter : ")
if user_input in list_of_good_values:
good_input = user_input
Short & Sweet:
/**
* Get a diff between two dates
*
* @param oldDate the old date
* @param newDate the new date
* @return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
try {
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Usage:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
dateDifference: 2
Kotlin Version:
@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
content = `cat file`
I think this method is the most "uncommon" one. Maybe it is kind of tricky, but it works if cat
is installed.
Try to change the layout_width to android:layout_width="match_parent"
because gravity:"right"
aligns the text inside the layout_width, and if you choose wrap content it does not have where to go, but if you choose match parent it can go to the right.
Here's what I've come up with (edit: plus some tweaks provided by sfstewman, levigroker, Kyle Strand, and Rob Kennedy), that seems to mostly fit my "better" criteria:
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
That SCRIPTPATH
line seems particularly roundabout, but we need it rather than SCRIPTPATH=`pwd`
in order to properly handle spaces and symlinks.
The inclusion of output redirection (>/dev/null 2>&1
) handles the rare(?) case where cd
might produce output that would interfere with the surrounding $( ... )
capture. (Such as cd
being overridden to also ls
a directory after switching to it.)
Note also that esoteric situations, such as executing a script that isn't coming from a file in an accessible file system at all (which is perfectly possible), is not catered to there (or in any of the other answers I've seen).
Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.
If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
In my case i forgot to add the () after the function name inside the render function of a react component
public render() {
let ctrl = (
<>
<div className="aaa">
{this.renderView}
</div>
</>
);
return ctrl;
};
private renderView() : JSX.Element {
// some html
};
Changing the render method, as it states in the error message to
<div className="aaa">
{this.renderView()}
</div>
fixed the problem
Here is a
Usage example:
timeout 1 | TimeIt.cmd
Execution took ~969 milliseconds.
Copy & paste this into some editor like for example Notepad++ and save it as TimeIt.cmd:
:: --- TimeIt.cmd ----
@echo off
setlocal enabledelayedexpansion
call :ShowHelp
:: Set pipeline initialization time
set t1=%time%
:: Wait for stdin
more
:: Set time at which stdin was ready
set t2=!time!
:: Calculate difference
Call :GetMSeconds Tms1 t1
Call :GetMSeconds Tms2 t2
set /a deltaMSecs=%Tms2%-%Tms1%
echo Execution took ~ %deltaMSecs% milliseconds.
endlocal
goto :eof
:GetMSeconds
Call :Parse TimeAsArgs %2
Call :CalcMSeconds %1 %TimeAsArgs%
goto :eof
:CalcMSeconds
set /a %1= (%2 * 3600*1000) + (%3 * 60*1000) + (%4 * 1000) + (%5)
goto :eof
:Parse
:: Mask time like " 0:23:29,12"
set %1=!%2: 0=0!
:: Replace time separators with " "
set %1=!%1::= !
set %1=!%1:.= !
set %1=!%1:,= !
:: Delete leading zero - so it'll not parsed as octal later
set %1=!%1: 0= !
goto :eof
:ShowHelp
echo %~n0 V1.0 [Dez 2015]
echo.
echo Usage: ^<Command^> ^| %~nx0
echo.
echo Wait for pipe getting ready... :)
echo (Press Ctrl+Z ^<Enter^> to Cancel)
goto :eof
^ - Based on 'Daniel Sparks' Version
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
From the documentation Restore activity UI state using saved instance state it is stated as:
Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:
IMO, this is more clear way than checking this at onCreate, and better fits with single responsiblity principle.
If you want to call JavaScript function in C#, this will help you:
public string functionname(arg)
{
if (condition)
{
Page page = HttpContext.Current.CurrentHandler as Page;
page.ClientScript.RegisterStartupScript(
typeof(Page),
"Test",
"<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");
}
}
Each link has five different states: link
, hover
, active
, focus
and visited
.
Link
is the normal appearance, hover
is when you mouse over, active
is the state when it's clicked, focus
follows active and visited
is the state you end up when you unfocus the recently clicked link.
I'm guessing you want to achieve a different style on either focus
or visited
, then you can add the following CSS:
a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }
A recommended order in your CSS to not cause any trouble is the following:
a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }
You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools
There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.
If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save
method to throw an exception or limit the data going into the field.
And this option?
list_name<-list()
for(i in 1:100){
paste("orca",i,sep="")->list_name[[i]]
}
It works perfectly. In the example you put, first line is missing, and then gives you the error message.
try this :
driver = webdriver.Chrome(ChromeDriverManager().install())
I found this to be exactly what I was looking for related to key binding in WPF:
<Window.InputBindings>
<KeyBinding Modifiers="Control"
Key="N"
Command="{Binding CreateCustomerCommand}" />
</Window.InputBindings>
See blog post MVVM CommandReference and KeyBinding
As of 2018-04-20 Git for Windows has a bug which effectively limits the file size to 4GB max using that particular implementation (this bug propagates to lfs as well).
Have a look at sys.path
:
>>> import sys
>>> print(sys.path)
M-x replace-string
RET ;
RET C-q C-j.
C-q for quoted-insert
,
C-j is a newline.
Cheers!
The above example using sort is close, but in the case of strings simply use SearchString:
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.SearchStrings(files, target)
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
I think, that you have to declare the associated sheet!
Try something like this
objsheet(1).Cells[i,j].Value;
If you just want to test a library from the command line, you could do:
cat somelibrary.js mytestfile.js | node
I often do this way. Try this way :
ps aux | grep script_Name
Here, script_Name could be any script/file run by nohup. This command gets you a process ID. Then use this command below to kill the script running on nohup.
kill -9 1787 787
Here, 1787 and 787 are Process ID as mentioned in the question as an example. This should do what was intended in the question.
That is the HTML code. Anyone can use this:
<div class="card-header">Contact Information</div>
<div class="card-body" formArrayName="funds">
<div class="row">
<div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
<div [formGroupName]="i" class="row">
<div class="form-group col-6">
<label>Type of Contact</label>
<select class="form-control" formControlName="fundName" type="text">
<option value="01">Balance Fund</option>
<option value="02">Equity Fund</option>
</select>
</div>
<div class="form-group col-12">
<label>Allocation</label>
<input class="form-control" formControlName="allocation" type="number">
<span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched &&
getContactsFormGroup(i).controls['allocation'].hasError('required')">
Allocation % is required! </span>
</div>
<div class="form-group col-12 text-right">
<button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>
It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
According to the React documentation on setState, using Object.assign
as suggested by other answers here is not ideal. Due to the nature of setState
's asynchronous behavior, subsequent calls using this technique may override previous calls causing undesirable outcomes.
Instead, the React docs recommend to use the updater form of setState
which operates on the previous state. Keep in mind that when updating an array or object you must return a new array or object as React requires us to preserve state immutability. Using ES6 syntax's spread operator to shallow copy an array, creating or updating a property of an object at a given index of the array would look like this:
this.setState(prevState => {
const newItems = [...prevState.items];
newItems[index].name = newName;
return {items: newItems};
})
There are many places where someone might want to deploy this kind of scenario, but due to the way integrated authentication works, it is not possible.
As gbn mentioned, integrated authentication uses a special token that corresponds to your Windows identity. There are coding practices called "impersonation" (probably used by the Run As... command) that allow you to effectively perform an activity as another Windows user, but there is not really a way to arbitrarily act as a different user (à la Linux) in Windows applications aside from that.
If you really need to administer multiple servers across several domains, you might consider one of the following:
Hopefully this helps!
Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat
is a bit confusing. I was trying to use r'?.*'
as a pattern, and thought it was complaining for some strange reason about the *
, but the problem is actually that ?
is a way of saying "repeat zero or one times". So I needed to say r'\?.*'
to match a literal ?
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
There is a DateTimePicker
available in the Extended Toolkit.
You can use any decompiler to first decompile the file.
I had once faced a simillar problem where I didn't have source code of the application and had to make a very small change in a file.
Below is what I did:
Extracted the class file from the jar
Opened it in a decompiler (I use JD GUI, you can get it easily from many resources on internet) You may download it from here
You can actually view all the files in a jar using JD GUI.
I would recommend the approach mentioned by Stefan (i.e. follow the guidelines in Improved Persistent Login Cookie Best Practice) and also recommend that you make sure your cookies are HttpOnly cookies so they are not accessible to, potentially malicious, JavaScript.
Add onclick="window.location = this.href"
to your <a>
element. After this modification it could be .click()
ed with expected behaviour. To do so with every link on your page, you can add this:
<script type="text/javascript">
$(function () {
$("a").attr("onclick", "window.location = this.href");
});
</script>
Try this in the .htaccess of the external root folder :
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
And if it only concerns .js scripts you should wrap the above code inside this:
<FilesMatch "\.(js)$">
...
</FilesMatch>
You could use crypto-js.
I would also recommend using SHA256, rather than MD5.
To install crypto-js via NPM:
npm install crypto-js
Alternatively you can use a CDN and reference the JS file.
Then to display a MD5 and SHA256 hash, you can do the following:
<script type="text/javascript">
var md5Hash = CryptoJS.MD5("Test");
var sha256Hash = CryptoJS.SHA256("Test1");
console.log(md5Hash.toString());
console.log(sha256Hash.toString());
</script>
Working example located here, JSFiddle
There are also other JS functions that will generate an MD5
hash, outlined below.
http://www.myersdaily.org/joseph/javascript/md5-text.html
http://pajhome.org.uk/crypt/md5/md5.html
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [], i; /* Andy King said do it this way. */
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i)
+ (s.charCodeAt(i+1) << 8)
+ (s.charCodeAt(i+2) << 16)
+ (s.charCodeAt(i+3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}
if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
function add32(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}
Then simply use the MD5 function, as shown below:
alert(md5("Test string"));
Another working JS Fiddle here
Maybe a bit late, but hope it hellps:
@echo off
if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause
Is this any good at all (will it do what I want?)
You can do so. Another feasible way is using java.net.Socket
.
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
There's also the InetAddress#isReachable()
:
boolean reachable = InetAddress.getByName(hostname).isReachable();
This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.
Do I have to somehow close the connection?
No, you don't explicitly need. It's handled and pooled under the hoods.
I suppose this is a GET request. Is there a way to send HEAD instead?
You can cast the obtained URLConnection
to HttpURLConnection
and then use setRequestMethod()
to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.
Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)
Indeed, connecting a host only informs if the host is available, not if the content is available. It can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. You can determine that by checking if the HTTP response code is 200.
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
// Not OK.
}
// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error
For more detail about response status codes see RFC 2616 section 10. Calling connect()
is by the way not needed if you're determining the response data. It will implicitly connect.
For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:
/**
* Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in
* the 200-399 range.
* @param url The HTTP URL to be pinged.
* @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
* given timeout, otherwise <code>false</code>.
*/
public static boolean pingURL(String url, int timeout) {
url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
return (200 <= responseCode && responseCode <= 399);
} catch (IOException exception) {
return false;
}
}
From lodash.js.
var undefined;
function isUndefined(value) {
return value === undefined;
}
It creates a local variable named undefined
which is initialized with the default value -- the real undefined
, then compares value
with the variable undefined
.
Update 9/9/2019
I found Lodash updated its implementation. See my issue and the code.
To be bullet-proof, simply use:
function isUndefined(value) {
return value === void 0;
}
If you’re asking what I think you’re asking, you can open it by executing this:
explorer.exe "C:\WINDOWS\Tasks\"
The answer from Lauri Oherd works well for most strings seen in the wild, but will fail if the string contains lone characters in the surrogate pair range, 0xD800 to 0xDFFF. E.g.
byteCount(String.fromCharCode(55555))
// URIError: URI malformed
This longer function should handle all strings:
function bytes (str) {
var bytes=0, len=str.length, codePoint, next, i;
for (i=0; i < len; i++) {
codePoint = str.charCodeAt(i);
// Lone surrogates cannot be passed to encodeURI
if (codePoint >= 0xD800 && codePoint < 0xE000) {
if (codePoint < 0xDC00 && i + 1 < len) {
next = str.charCodeAt(i + 1);
if (next >= 0xDC00 && next < 0xE000) {
bytes += 4;
i++;
continue;
}
}
}
bytes += (codePoint < 0x80 ? 1 : (codePoint < 0x800 ? 2 : 3));
}
return bytes;
}
E.g.
bytes(String.fromCharCode(55555))
// 3
It will correctly calculate the size for strings containing surrogate pairs:
bytes(String.fromCharCode(55555, 57000))
// 4 (not 6)
The results can be compared with Node's built-in function Buffer.byteLength
:
Buffer.byteLength(String.fromCharCode(55555), 'utf8')
// 3
Buffer.byteLength(String.fromCharCode(55555, 57000), 'utf8')
// 4 (not 6)
Just Bash :) (4.0+)
function print_reversed {
local lines i
readarray -t lines
for (( i = ${#lines[@]}; i--; )); do
printf '%s\n' "${lines[i]}"
done
}
print_reversed < file
If you already have the package name you wish to activate, you can use the following code which is a bit more generic:
PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
if (null != appStartIntent)
{
context.startActivity(appStartIntent);
}
I found that it works better for cases where the main activity was not found by the regular method of start the MAIN activity.
Using JSONSerialization
always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable
in Swift 4. If you wield a [String:Any]
in front of a simple struct
it will ... hurt. Check out this in a Playground:
import Cocoa
let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!
struct Form: Codable {
let id: Int
let name: String
let description: String?
private enum CodingKeys: String, CodingKey {
case id = "form_id"
case name = "form_name"
case description = "form_desc"
}
}
do {
let f = try JSONDecoder().decode([Form].self, from: data)
print(f)
print(f[0])
} catch {
print(error)
}
With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.
this is very basic method to send plain text email using mail function.
<?php
$to = '[email protected]';
$subject = 'This is subject';
$message = 'This is body of email';
$from = "From: FirstName LastName <[email protected]>";
mail($to,$subject,$message,$from);
Use:
var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {
if (obj.id === '5') { // id.toString() if it is int
retObj = obj;
return false;
}
});
return retObj;
It should return an object by id.
.NET has spoiled us :) Your declaration is not valid for VBA.
Only constants can be given a value upon application load. You declare them like so:
Public Const APOSTROPHE_KEYCODE = 222
Here's a sample declaration from one of my vba projects:
If you're looking for something where you declare a public variable and then want to initialize its value, you need to create a Workbook_Open sub and do your initialization there. Example:
Private Sub Workbook_Open()
Dim iAnswer As Integer
InitializeListSheetDataColumns_S
HideAllMonths_S
If sheetSetupInfo.Range("D6").Value = "Enter Facility Name" Then
iAnswer = MsgBox("It appears you have not yet set up this workbook. Would you like to do so now?", vbYesNo)
If iAnswer = vbYes Then
sheetSetupInfo.Activate
sheetSetupInfo.Range("D6").Select
Exit Sub
End If
End If
Application.Calculation = xlCalculationAutomatic
sheetGeneralInfo.Activate
Load frmInfoSheet
frmInfoSheet.Show
End Sub
Make sure you declare the sub in the Workbook Object itself:
Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave
Uncheck
"Work Offline"
in Settings -> Maven ! It worked for me ! :D
You put your image in resources folder and use follow code:
JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));
create a global temp table with a GUID in the name dynamically. Then you can work with it in your code, via dyn sql, without worry that another process calling same sproc will use it. This is useful when you dont know what to expect from the underlying selected table each time it runs so you cannot created a temp table explicitly beforehand. ie - you need to use SELECT * INTO syntax
DECLARE @TmpGlobalTable varchar(255) = 'SomeText_' + convert(varchar(36),NEWID())
-- select @TmpGlobalTable
-- build query
SET @Sql =
'SELECT * INTO [##' + @TmpGlobalTable + '] FROM SomeTable'
EXEC (@Sql)
EXEC ('SELECT * FROM [##' + @TmpGlobalTable + '] ')
EXEC ('DROP TABLE [##' + @TmpGlobalTable + ']')
PRINT 'Dropped Table ' + @TmpGlobalTable
Hope it helps. for more detail you can follow this Link
.parent{
display: flex;
flex-wrap: wrap;
}
.parent .child{
flex: 1 1 25%;
/*Start Run Code Snippet output CSS*/
padding: 5px;
box-sizing: border-box;
text-align: center;
border: 1px solid #000;
/*End Run Code Snippet output CSS*/
}
_x000D_
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
<div class="child">7</div>
<div class="child">8</div>
</div>
_x000D_
See std::clock()
function.
const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;
If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ).
EDIT:
responsible header files - <ctime>
or <time.h>
In 2019 using ES6:
const ids = [1, 4, 5],_x000D_
data = {_x000D_
records: [{_x000D_
"empid": 1,_x000D_
"fname": "X",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 2,_x000D_
"fname": "A",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 3,_x000D_
"fname": "B",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 4,_x000D_
"fname": "C",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 5,_x000D_
"fname": "C",_x000D_
"lname": "Y"_x000D_
}]_x000D_
};_x000D_
_x000D_
_x000D_
data.records = data.records.filter( i => ids.includes( i.empid ) );_x000D_
_x000D_
console.info( data );
_x000D_
Have a look at the following apache commons function:
org.apache.commons.io.FileUtils.readFileToByteArray(File)
Yesterday, I got the same error: Failed building wheel for hddfancontrol
when I ran pip3 install hddfancontrol
. The result was Failed to build hddfancontrol
. The cause was error: invalid command 'bdist_wheel'
and Running setup.py bdist_wheel for hddfancontrol ... error
. The error was fixed by running the following:
pip3 install wheel
(From here.)
Alternatively, the "wheel" can be downloaded directly from here. When downloaded, it can be installed by running the following:
pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"
Welcome to the fickle world of SQL Server log management.
SOMETHING is wrong, though I don't think anyone will be able to tell you more than that without some additional information. For example, has this database ever been used for Transactional SQL Server replication? This can cause issues like this if a transaction hasn't been replicated to a subscriber.
In the interim, this should at least allow you to kill the log file:
You should now be able to shrink the files (if performing the backup didn't do that for you).
Good luck!
i use php5.6
code:
$person = ["name"=>"mohammed", "age"=>30];
$person['addr'] = "Sudan";
print_r($person)
output
Array( ["name"=>"mohammed", "age"=>30, "addr"=>"Sudan"] )
If you are willing to use custom table header as table header, try the followings....
Updated for swift 3.0
Step 1
Create UITableViewHeaderFooterView for custom header..
import UIKit
class MapTableHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var testView: UIView!
}
Step 2
Add custom header to UITableView
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
//register the header view
let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")
}
extension BranchViewController : UITableViewDelegate{
}
extension BranchViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView
return headerView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
// retuen no of rows in sections
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// retuen your custom cells
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func numberOfSections(in tableView: UITableView) -> Int {
// retuen no of sections
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// retuen height of row
}
}
The first thing I will try - determine if your code with alerts is actually rendered. I see some server "if" code in what you posted, so may be condition to render javascript is not satisfied. So, on the page you working on, right-click -> view source. Try to find the js code there. Please tell us if you found the code on the page.
I'd guess that your iMac isn't 64-bit (you state in another thread it is an original white intel iMac). Try the 32-bit version of MySQL–it should install directly over the 64-bit version, I think.
How to tell if your Intel-based Mac has a 32-bit or 64-bit processor
http://support.apple.com/kb/HT3696
I spent quite a bit of time spelunking through the internet for an elegant solution to this. As is usually the case, I found a lot of conflicting information.
I finally ended with:
EXIT_ON_CLOSE
as this can leave resources behind;Do use something like the following in the JFrame initialization:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame()
returns a reference to the JFrame:
public class AppMenuFileExit extends JMenuItem implements ActionListener
{
// do your normal menu item code here
@Override
public void actionPerformed(ActionEvent e)
{
WindowEvent we;
we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING);
App.getFrame().dispatchEvent(we);
}
}
JFrame is a subclass of Window so may be cast to Window for this purpose.
And, have the following in your JFrame class to handle Window messages:
public class AppFrame extends JFrame implements WindowListener
{
// Do all the things you need to for the class
@Override
public void windowOpened(WindowEvent e)
{}
@Override
public void windowClosing(WindowEvent e)
{/* can do cleanup here if necessary */}
@Override
public void windowClosed(WindowEvent e)
{
dispose();
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e)
{}
@Override
public void windowDeactivated(WindowEvent e)
{}
@Override
public void windowDeiconified(WindowEvent e)
{}
@Override
public void windowIconified(WindowEvent e)
{}
}
This is a project for getting IP address of any website , it's usefull and so easy to make.
import java.net.InetAddress;
import java.net.UnkownHostExceptiin;
public class Main{
public static void main(String[]args){
try{
InetAddress addr = InetAddresd.getByName("www.yahoo.com");
System.out.println(addr.getHostAddress());
}catch(UnknownHostException e){
e.printStrackTrace();
}
}
}
Try this:
$arr = (array) null;
var_dump($arr);
// will print
// array(0) { }
So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.
Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.
Below is a blog for more details..
https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/
Happy coding.. :)
Thanks, Ayan
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo()
can be called only after creation.
(function() { ... }());
Crockford recommends to use function expression because it makes it clear that foo
is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.
or you may try something like
"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
(emphasis mine)
Try this
$(function() {
$( "#datepicker" ).datepicker({ maxDate: new Date() });
});
Or you can achieve this using as below:
$(function() {
$( "#datepicker" ).datepicker({ maxDate: 0 });
});
It's not a better idea to override the core.common file of codeigniter. Because that's the more tested and system files....
I make a solution for this problem. In your ckeditor_helper.php file line- 65
if($k !== end (array_keys($data['config']))) {
$return .= ",";
}
Change this to-->
$segment = array_keys($data['config']);
if($k !== end($segment)) {
$return .= ",";
}
I think this is the best solution and then your problem notice will dissappear.
I just tested benmajor's GitHub jQuery Touch Events plugin for both 1.4 and 1.7+ versions of jQuery. It is lightweight and works perfectly with both on
and bind
while providing support for an exhaustive set of touch events.
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
Before you call setContentView()
, call setTheme(android.R.style...)
and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)
i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.
This worked for me:
a &= a && b()
Change android:stretchColumns
value to *
.
Value 0
means stretch the first column. Value 1
means stretch the second column and so on.
Value *
means stretch all the columns.
In MySQL TRUE
and FALSE
are synonyms for TINYINT(1)
.
So therefore its basically the same thing, but MySQL is converting to 0/1 - so just use a TINYINT
if that's easier for you
P.S.
The performance is likely to be so minuscule (if at all), that if you need to ask on StackOverflow, then it won't affect your database :)
As far as best practices, keep an eye for recursive functions. In my case I ran into issues with recursion (where there didn't need to be). A simplified example of what I was doing:
def my_function():
# lots of memory intensive operations
# like operating on images or huge dictionaries and lists
.....
my_flag = True
if my_flag: # restart the function if a certain flag is true
my_function()
def main():
my_function()
operating in this recursive manner won't trigger the garbage collection and clear out the remains of the function, so every time through memory usage is growing and growing.
My solution was to pull the recursive call out of my_function() and have main() handle when to call it again. this way the function ends naturally and cleans up after itself.
def my_function():
# lots of memory intensive operations
# like operating on images or huge dictionaries and lists
.....
my_flag = True
.....
return my_flag
def main():
result = my_function()
if result:
my_function()
Regarding you question about betterhost and such, see host; basically every IP address is a host.
I suggest you start reading-up from host and only than go on to localhost (which is a type of host)
Remember you can access good old ECMAScript APIs, in this case, JSON.stringify()
.
For simple arrays like the one in your example:
require('fs').writeFile(
'./my.json',
JSON.stringify(myArray),
function (err) {
if (err) {
console.error('Crap happens');
}
}
);