The pointer str
is never allocated. It should be malloc
'd before use.
How about using underscorejs
str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
For a nice inset shadow in right and left sides on images, or any other content, use it this way
***The z-index:-1 does a nice trick when showing images or inner objects with insets
<html>
<div class="shadowcontainer">
<img src="https://www.google.es/images/srpr/logo11w.png" class="innercontent" style="with:100%"/>
</div>
<style>
.shadowcontainer{
display:inline-flex;
box-shadow: inset -40px 0px 30px -30px rgba(0,0,0,0.9),inset 40px 0px 30px -30px rgba(0,0,0,0.9);
}
.innercontent{
z-index:-1
}
</style>
</html>
Simple and easy way to show back button on toolbar
Paste this code in onCreate method
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Paste this override method outside the onCreate method
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
It means you haven't assigned a provisioning profile to the configuration.
Usually it's because "Any iOS SDK" must have a profile and cannot be set to "Don't sign".
All this and more is answered in the TN2250 Tech Note about Code Signing and Troubleshooting.
I was also looking for this answer until I came across this post.
I've found another solution to know the keycode of the different keys, courtesy to my problem. I just wanted to share my solution.
Just use keyup/keydown event to write the value in the console/alert the same using event.keyCode
. like-
console.log(event.keyCode)
// or
alert(event.keyCode)
- rupam
a simpler solution based on this answer:
public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
public static String prettyFormat(String input) {
return prettyFormat(input, 2);
}
testcase:
prettyFormat("<root><child>aaa</child><child/></root>");
returns:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>aaa</child>
<child/>
</root>
Containers are meant to run to completion. You need to provide your container with a task that will never finish. Something like this should work:
apiVersion: v1
kind: Pod
metadata:
name: ubuntu
spec:
containers:
- name: ubuntu
image: ubuntu:latest
# Just spin & wait forever
command: [ "/bin/bash", "-c", "--" ]
args: [ "while true; do sleep 30; done;" ]
I made a simple tool that will display an image given a filename or image object or url.
It's crude, but it'll do in a hurry.
Installation:
$ pip install simple-imshow
Usage:
from simshow import simshow
simshow('some_local_file.jpg') # display from local file
simshow('http://mathandy.com/escher_sphere.png') # display from url
You should look into Video For Everyone:
Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.
The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.
In other browsers that do not support , it falls back to QuickTime.
If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.
The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).
<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
<source src="__VIDEO__.mp4" type="video/mp4" />
<source src="__VIDEO__.webm" type="video/webm" />
<source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
<object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
[endif]--><!--[if !IE]><!-->
<object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
<param name="src" value="__VIDEO__.mp4" />
<param name="autoplay" value="false" />
<param name="showlogo" value="false" />
<object width="640" height="380" type="application/x-shockwave-flash"
data="__FLASH__.swf?image=__POSTER__.jpg&file=__VIDEO__.mp4">
<param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&file=__VIDEO__.mp4" />
<img src="__POSTER__.jpg" width="640" height="360" />
<p>
<strong>No video playback capabilities detected.</strong>
Why not try to download the file instead?<br />
<a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
<a href="__VIDEO__.ogv">Ogg Theora & Vorbis “.ogv” (Linux)</a>
</p>
</object><!--[if gt IE 6]><!-->
</object><!--<![endif]-->
</video>
There is an updated version that is a bit more readable:
<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
=================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0 -->
<video width="640" height="360" controls preload="none">
<!-- MP4 must be first for iPad! -->
<source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video -->
<source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
<source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
<!-- fallback to Flash: -->
<object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
<!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
<param name="movie" value="__FLASH__.SWF" />
<param name="flashvars" value="image=__POSTER__.JPG&file=__VIDEO__.MP4" />
<!-- fallback image. note the title field below, put the title of the video there -->
<img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
title="No video playback capabilities, please download the video below" />
</object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
Closed Format: <a href="__VIDEO__.MP4">"MP4"</a>
Open Format: <a href="__VIDEO__.OGV">"OGG"</a>
</p>
Use Reflection:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list
Edit: You can also specify a BindingFlags value to type.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
You don't need to specify BindingFlags.GetProperty
, you use that when calling type.InvokeMember()
to get the value of a property.
Suppose you want to use, say ID in any other webpage then you can do it by following code snippet :
String id=(String)session.getAttribute("uid");
Here uid is the attribute in which you have stored the ID earlier. You can set it by:
session.setAttribute("uid",id);
For bootstrap 4
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<form class="form-inline my-2 my-lg-0">
<div class="input-group">
<input class="form-control" type="search" placeholder="Search">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-search"></i></div>
</div>
</div>
</form>
I would put decimal.MaxValue.ToString()
since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.
Element.innerHTML
is pretty much the way to go. Here are a few ways to use it:
<div class="results"></div>
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div>
I usually just add an empty element with a class like value
or one I want to replace the contents of to the main <div>
. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
// Plain Javascript Example_x000D_
var $jsName = document.querySelector('.name');_x000D_
var $jsValue = document.querySelector('.jsValue');_x000D_
_x000D_
$jsName.addEventListener('input', function(event){_x000D_
$jsValue.innerHTML = $jsName.value;_x000D_
}, false);_x000D_
_x000D_
_x000D_
// JQuery example_x000D_
var $jqName = $('.name');_x000D_
var $jqValue = $('.jqValue');_x000D_
_x000D_
$jqName.on('input', function(event){_x000D_
$jqValue.html($jqName.val());_x000D_
});
_x000D_
html {_x000D_
font-family: sans-serif;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
margin: 1em 0 0.25em 0;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
padding: 0.5em;_x000D_
}_x000D_
_x000D_
.jsValue, .jqValue {_x000D_
color: red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>Setting HTML content example</title>_x000D_
</head>_x000D_
<body>_x000D_
<!-- This <input> field is where I'm getting the name from -->_x000D_
<label>Enter your name: <input class="name" type="text" value="World"/></label>_x000D_
_x000D_
<!-- Plain Javascript Example -->_x000D_
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>_x000D_
_x000D_
<!-- jQuery Example -->_x000D_
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>_x000D_
</body>_x000D_
</html>
_x000D_
$(document).ready(function(){_x000D_
$('input').on("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
For all of you who answered correctly with the jQuery method of $('#idnamehere').show()/.hide()
, thank you.
It seems <script src="http://code.jquery.com/jquery.js"></script>
was misspelled in my header (which would explain why no alert calls were working on that page).
Thanks a million, though, and sorry for wasting your time!
I put this in my makefile, right the next line after adb install ...
adb shell monkey -p `cat .identifier` -c android.intent.category.LAUNCHER 1
For this to work there must be a .identifier file with the app's bundle identifier in it, like com.company.ourfirstapp
No need to hunt activity name.
I found another quite simple approach. If start and end date of daterange1 falls before start date of daterange2 or start and end date of daterange1 falls after end date of daterange2 this means they don't intersect with each other.
public boolean doesIntersect(DateRangeModel daterange1, DateRangeModel daterange2) {
return !(
(daterange1.getStartDate().isBefore(daterange2.getStartDate())
&& daterange1.getEndDate().isBefore(daterange2.getStartDate())) ||
(daterange1.getStartDate().isAfter(daterange2.getStartDate())
&& daterange1.getEndDate().isAfter(daterange2.getEndDate())));
}
I had a VC++ project that was always compiling all files and had been previously upgraded from VS2005 to VS2010 (by other people). I found that all cpp files in the project except StdAfx.cpp were set to Create (/Yc) the precompiled header. I changed this so that only StdAfx.cpp was set to create the precompiled header and the rest were set to Use (/Yu) the precompiled header and this fixed the problem for me.
In theory, malloc gets memory from the operating system for this application. However, since you may only want 4 bytes, and the OS needs to work in pages (often 4k), malloc does a little more than that. It takes a page, and puts it's own information in there so it can keep track of what you have allocated and freed from that page.
When you allocate 4 bytes, for instance, malloc gives you a pointer to 4 bytes. What you may not realize is that the memory 8-12 bytes before your 4 bytes is being used by malloc to make a chain of all the memory you have allocated. When you call free, it takes your pointer, backs up to where it's data is, and operates on that.
When you free memory, malloc takes that memory block off the chain... and may or may not return that memory to the operating system. If it does, than accessing that memory will probably fail, as the OS will take away your permissions to access that location. If malloc keeps the memory ( because it has other things allocated in that page, or for some optimization ), then the access will happen to work. It's still wrong, but it might work.
DISCLAIMER: What I described is a common implementation of malloc, but by no means the only possible one.
You can refer Windows command prompt help using following command : xcopy /?
in windows you can get cpu usage by code bellow:
#include <windows.h>
#include <stdio.h>
//------------------------------------------------------------------------------------------------------------------
// Prototype(s)...
//------------------------------------------------------------------------------------------------------------------
CHAR cpuusage(void);
//-----------------------------------------------------
typedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
static pfnGetSystemTimes s_pfnGetSystemTimes = NULL;
static HMODULE s_hKernel = NULL;
//-----------------------------------------------------
void GetSystemTimesAddress()
{
if( s_hKernel == NULL )
{
s_hKernel = LoadLibrary( L"Kernel32.dll" );
if( s_hKernel != NULL )
{
s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress( s_hKernel, "GetSystemTimes" );
if( s_pfnGetSystemTimes == NULL )
{
FreeLibrary( s_hKernel ); s_hKernel = NULL;
}
}
}
}
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
// cpuusage(void)
// ==============
// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.
//----------------------------------------------------------------------------------------------------------------
CHAR cpuusage()
{
FILETIME ft_sys_idle;
FILETIME ft_sys_kernel;
FILETIME ft_sys_user;
ULARGE_INTEGER ul_sys_idle;
ULARGE_INTEGER ul_sys_kernel;
ULARGE_INTEGER ul_sys_user;
static ULARGE_INTEGER ul_sys_idle_old;
static ULARGE_INTEGER ul_sys_kernel_old;
static ULARGE_INTEGER ul_sys_user_old;
CHAR usage = 0;
// we cannot directly use GetSystemTimes on C language
/* add this line :: pfnGetSystemTimes */
s_pfnGetSystemTimes(&ft_sys_idle, /* System idle time */
&ft_sys_kernel, /* system kernel time */
&ft_sys_user); /* System user time */
CopyMemory(&ul_sys_idle , &ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...
CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...
CopyMemory(&ul_sys_user , &ft_sys_user , sizeof(FILETIME)); // Could been optimized away...
usage =
(
(
(
(
(ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
(ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)
)
-
(ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)
)
*
(100)
)
/
(
(ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
(ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)
)
);
ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;
ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;
ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;
return usage;
}
//------------------------------------------------------------------------------------------------------------------
// Entry point
//------------------------------------------------------------------------------------------------------------------
int main(void)
{
int n;
GetSystemTimesAddress();
for(n=0;n<20;n++)
{
printf("CPU Usage: %3d%%\r",cpuusage());
Sleep(2000);
}
printf("\n");
return 0;
}
Updated 2018
The dropdown-submenu
has been removed in Bootstrap 3 RC. In the words of Bootstrap author Mark Otto..
"Submenus just don't have much of a place on the web right now, especially the mobile web. They will be removed with 3.0" - https://github.com/twbs/bootstrap/pull/6342
But, with a little extra CSS you can get the same functionality.
Bootstrap 4 (navbar submenu on hover)
.navbar-nav li:hover > ul.dropdown-menu {
display: block;
}
.dropdown-submenu {
position:relative;
}
.dropdown-submenu>.dropdown-menu {
top:0;
left:100%;
margin-top:-6px;
}
Navbar submenu dropdown hover
Navbar submenu dropdown hover (right aligned)
Navbar submenu dropdown click (right aligned)
Navbar dropdown hover (no submenu)
Bootstrap 3
Here is an example that uses 3.0 RC 1: http://bootply.com/71520
Here is an example that uses Bootstrap 3.0.0 (final): http://bootply.com/86684
CSS
.dropdown-submenu {
position:relative;
}
.dropdown-submenu>.dropdown-menu {
top:0;
left:100%;
margin-top:-6px;
margin-left:-1px;
-webkit-border-radius:0 6px 6px 6px;
-moz-border-radius:0 6px 6px 6px;
border-radius:0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display:block;
}
.dropdown-submenu>a:after {
display:block;
content:" ";
float:right;
width:0;
height:0;
border-color:transparent;
border-style:solid;
border-width:5px 0 5px 5px;
border-left-color:#cccccc;
margin-top:5px;
margin-right:-10px;
}
.dropdown-submenu:hover>a:after {
border-left-color:#ffffff;
}
.dropdown-submenu.pull-left {
float:none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left:-100%;
margin-left:10px;
-webkit-border-radius:6px 0 6px 6px;
-moz-border-radius:6px 0 6px 6px;
border-radius:6px 0 6px 6px;
}
Sample Markup
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="menu-item dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Drop Down<b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="menu-item dropdown dropdown-submenu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 1</a>
<ul class="dropdown-menu">
<li class="menu-item ">
<a href="#">Link 1</a>
</li>
<li class="menu-item dropdown dropdown-submenu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 2</a>
<ul class="dropdown-menu">
<li>
<a href="#">Link 3</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
P.S. - Example in navbar that adjusts left position: http://bootply.com/92442
webView.setBackgroundColor(0x00000000);
webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
this will definitely work.. set background in XML with Editbackground. Now that background will be shown
In plain JS add { passive: false }
as third argument
document.addEventListener('wheel', function(e) {
e.preventDefault();
doStuff(e);
}, { passive: false });
Modifying Adam Rosenfield's code:
import sys
def send_msg(sock, msg):
size_of_package = sys.getsizeof(msg)
package = str(size_of_package)+":"+ msg #Create our package size,":",message
sock.sendall(package)
def recv_msg(sock):
try:
header = sock.recv(2)#Magic, small number to begin with.
while ":" not in header:
header += sock.recv(2) #Keep looping, picking up two bytes each time
size_of_package, separator, message_fragment = header.partition(":")
message = sock.recv(int(size_of_package))
full_message = message_fragment + message
return full_message
except OverflowError:
return "OverflowError."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
I would, however, heavily encourage using the original approach.
Given that 'table-layout:fixed' is the essential layout requirement, that this creates evenly spaced non-adjustable columns, but that you need to make cells of different percentage widths, perhaps set the 'colspan' of your cells to a multiple?
For example, using a total width of 100 for easy percentage calculations, and saying that you need one cell of 80% and another of 20%, consider:
<TABLE width=100% style="table-layout:fixed;white-space:nowrap;overflow:hidden;">
<tr>
<td colspan=100>
text across entire width of table
</td>
<tr>
<td colspan=80>
text in lefthand bigger cell
</td>
<td colspan=20>
text in righthand smaller cell
</td>
</TABLE>
Of course, for columns of 80% and 20%, you could just set the 100% width cell colspan to 5, the 80% to 4, and the 20% to 1.
Put this code into your <head>
tag of your page.
<script type="text/javascript">
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
This will disable right click on your whole web page, but only when JavaScript is enabled.
Shouldn't you add to the login form?;
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
As stated in the here in the Spring security documentation
It could also be that you have a python3 system only. You therefore have installed the necessary packages via pip3 install , like pip3 install wheel.
You'll need to build your stuff using python3 specifically.
python3 setup.py sdist
python3 setup.py bdist_wheel
Cheers.
Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.
$(this).parent().closest('.a');
Thanks
Make your size a factor in your dataframe by:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
Then change the facet_grid(.~size)
to facet_grid(.~size_f)
Then plot:
The graphs are now in the correct order.
I've been struggling from this issue as well. I believe that this works for all release candidates aka rc but I didn't test is though. For @angular rc.2 it works well.
core-js
as npm dependency in package.json
typings install core-js --save
"es6-shim"
occurances in your package.json
. You don't need it anymore.Cheers!
I'm using .Net CORE 3.1 and I spent ages banging my head against a wall with this one when I realised that my code has started actually working but my debugging environment was broken, so here's 2 hints if you're trying to troubleshoot the problem:
If you're trying to log response headers using ASP.NET middleware, the "Access-Control-Allow-Origin" header will never show up even if it's there. I don't know how but it seems to be added outside the pipeline (in the end I had to use wireshark to see it).
.NET CORE won't send the "Access-Control-Allow-Origin" in the response unless you have an "Origin" header in your request. Postman won't set this automatically so you'll need to add it yourself.
You can use Google S2 Converter.
http://www.google.com/s2/favicons?domain=google.com
Source: http://www.labnol.org/internet/get-favicon-image-of-websites-with-google/4404/
Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:
require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)
The result is the days in the interval [0,..,6].
If you want the interval to be [1,..7], use the following:
df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)
... or, alternatively:
df$day = df$day + 1
Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern
it will create 0 byte file and not write anything:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="maxFileSize" value="1GB"/>
<param name="maxBackupIndex" value="2"/>
<param name="file" value="/tmp/bd.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<logger name="com.example.mypackage" additivity="false">
<level value="debug"/>
<appender-ref ref="bdfile"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="bdfile"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>
This worked for me.
def parse_data():
if request.method == "POST":
data = request.get_json()
print(data['answers'])
return render_template('output.html', data=data)
$.ajax({
type: 'POST',
url: "/parse_data",
data: JSON.stringify({values}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
// do something with the received data
}
});
MoreLinq has IEnumerable<T>.ForEach
and a ton of other useful extensions. It's probably not worth taking the dependency just for ForEach
, but there's a lot of useful stuff in there.
I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b
Consider the following servlet conf:
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet/*</url-pattern>
</servlet-mapping>
Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi
, it will invoke NewServlet
as it is mapped with the pattern described above.
Here:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
We have those ones:
getPathInfo()
returns
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
getRequestURI()
returns
a String containing the part of the URL from the protocol name up to the query string
I believe you can use...
RESET QUERY CACHE;
...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...
FLUSH QUERY CACHE;
See the Query Cache Status and Maintenance section of the MySQL manual for more information.
Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly.
I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as
content://com.android.providers.media.documents/document/image%3A52530
while if user select gallery from sliding drawer instead of recent then we will get uri as
content://media/external/images/media/52530
So I have handle it in getRealPathFromURI_API19()
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (uri.getHost().contains("com.android.providers.media")) {
// Image pick from recent
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
} else {
// image pick from gallery
return getRealPathFromURI_BelowAPI11(context,uri)
}
}
EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question
EDIT2 Here is complete code with handling virtual files and host other than com.android.providers
I have tested this method with content://com.adobe.scan.android.documents/document/
Instead of classes we can also directly use the HashMap<String, Object>
to send body parameters
for example
interface Foo {
@POST("/jayson")
FooResponse postJson(@Body HashMap<String, Object> body);
}
This depends upon scenarios.
Let's say you have some business functionality and you need to process something with that value further but having null
value at time of processing would impact it.
Then, in that case, you can use Optional<?>
.
String nullName = null;
String name = Optional.ofNullable(nullName)
.map(<doSomething>)
.orElse("Default value in case of null");
None of the above answers worked for me when binding back on POST, until I added the following in CSHTML
<div class="checkbox c-checkbox">
<label>
<input type="checkbox" id="xPrinting" name="xPrinting" value="true" @Html.Raw( Model.xPrinting ? "checked" : "")>
<span class=""></span>Printing
</label>
</div>
// POST: Index
[HttpPost]
public ActionResult Index([Bind(Include = "dateInHands,dateFrom,dateTo,pgStatus,gpStatus,vwStatus,freeSearch,xPrinting,xEmbroidery,xPersonalization,sortOrder,radioOperator")] ProductionDashboardViewModel model)
You need to follow this instructions https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair
If get "Permission denied (publickey)." with the follow command
ssh -i ~/.ssh/my-ssh-key [USERNAME]@[IP_ADDRESS]
you need to modify the /etc/ssh/sshd_config file and add the line
AllowUsers [USERNAME]
Then restart the ssh service with
service ssh restart
if you get the message "Could not load host key: /etc/ssh/ssh_host_ed25519_key" execute:
ssh-keygen -A
and finally restart the ssh service again.
service ssh restart
You need to find the location of what you're looking for with .indexOf()
then remove it with .splice()
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var array = new Array();
array.push("A");
array.push("B");
array.push("C");
?
remove(array, 'B');
alert(array)????;
This will take care of all occurrences.
create external table table_name(
Year int,
Month int,
column_name data_type )
row format delimited fields terminated by ','
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');
Unfortunately it's not just about reading uncommitted data. In the background you may end up reading pages twice (in the case of a page split), or you may miss the pages altogether. So your results may be grossly skewed.
Check out Itzik Ben-Gan's article. Here's an excerpt:
" With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice. "
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
Some special characters give this type of error, so use
$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";
You can add a new formula for unique record count
=IF(COUNTIF($A$2:A2,A2)>1,0,1)
Now you can use a pivot table and get a SUM
of unique record count.
This solution works best if you have two or more rows where the same value exist, but you want the pivot table to report an unique count.
function starts_with($s, $prefix){
// returns a bool
return strpos($s, $prefix) === 0;
}
starts_with($variable, "_");
I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);
plt.show()
This is the output:
That didn't work for me, I used some code parts from web, what I did:
new activity: FullScreenImage with:
package yourpackagename;
import yourpackagename.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class FullScreenImage extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_full);
Bundle extras = getIntent().getExtras();
Bitmap bmp = (Bitmap) extras.getParcelable("imagebitmap");
ImageView imgDisplay;
Button btnClose;
imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FullScreenImage.this.finish();
}
});
imgDisplay.setImageBitmap(bmp );
}
}
Then create a xml: layout_full
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imgDisplay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter" />
<Button
android:id="@+id/btnClose"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:textColor="#ffffff"
android:text="Close" />
</RelativeLayout>
And finally, send the image name from your mainactivity
final ImageView im = (ImageView)findViewById(R.id.imageView1) ;
im.setBackgroundDrawable(getResources().getDrawable(id1));
im.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NAMEOFYOURCURRENTACTIVITY.this, FullScreenImage.class);
im.buildDrawingCache();
Bitmap image= im.getDrawingCache();
Bundle extras = new Bundle();
extras.putParcelable("imagebitmap", image);
intent.putExtras(extras);
startActivity(intent);
}
});
I think that the best way is with View Composers
. If someone came here and want to find how can do it with View Composers way, read my answer => How to share a variable across all views?
use the following rule for validating radio button group selection
myRadioGroupName : {required :true}
myRadioGroupName is the value you have given to name attribute
RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.
rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.
Update (new Package 2013-12-03):
jsonlite: This package is a fork of the RJSONIO
package. It builds on the parser from RJSONIO
but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO
Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON
and toJSON
, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.
If you are filtering by common date this will return it:
dfs = [df1, df2, df3]
checker = dfs[-1]
check = set(checker.loc[:, 0])
for df in dfs[:-1]:
check = check.intersection(set(df.loc[:, 0]))
print(checker[checker.loc[:, 0].isin(check)])
C++20 concept usage
https://en.cppreference.com/w/cpp/language/constraints cppreference is giving the inheritance use case as an explicit concept example:
template <class T, class U>
concept Derived = std::is_base_of<U, T>::value;
template<Derived<Base> T>
void f(T); // T is constrained by Derived<T, Base>
For multiple bases I'm guessing the syntax will be:
template <class T, class U, class V>
concept Derived = std::is_base_of<U, T>::value || std::is_base_of<V, T>::value;
template<Derived<Base1, Base2> T>
void f(T);
GCC 10 appears to have implemented it: https://gcc.gnu.org/gcc-10/changes.html and you can get it as a PPA on Ubuntu 20.04. https://godbolt.org/ My local GCC 10.1 did not recognize concept
yet, so not sure what is going on.
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
In SQL Server 2016 you can use new DIE statements.
ALTER TABLE Table_name DROP COLUMN IF EXISTS Column_name
The above query is re-runnable it drops
the column only if it exists
in the table else it will not throw error.
Instead of using big IF
wrappers to check the existence of column
before dropping it you can just run the above DDL
statement
try with new Date(obj).getTime()
if( new Date(fit_start_time).getTime() > new Date(fit_end_time).getTime() )
{
alert(fit_start_time + " is greater."); // your code
}
else if( new Date(fit_start_time).getTime() < new Date(fit_end_time).getTime() )
{
alert(fit_end_time + " is greater."); // your code
}
else
{
alert("both are same!"); // your code
}
SSH into a Docker container using this command:
sudo docker exec -i -t (container ID) bash
A really simple implementation is:
out = "".join(c for c in asking if c not in ('!','.',':'))
and keep adding any other types of punctuation.
A more efficient way would be
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)
Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python
There is a VSCode extension called "Python Auto Venv" that automatically detects and uses your virtual environment if there is one.
If you set a static height for your header, you can use that in a calculation for the size of your wrapper.
http://jsfiddle.net/ske5Lqyv/5/
Using your example code, you can add this CSS:
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
height: 100%;
}
.header {
height: 64px;
background-color: lightblue;
}
.wrapper {
height: calc(100% - 64px);
overflow-y: auto;
}
Or, you can use flexbox for a more dynamic approach http://jsfiddle.net/19zbs7je/3/
<div id="container">
<div class="section">
<div class="header">Heading</div>
<div class="wrapper">
<p>Large Text</p>
</div>
</div>
</div>
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
display: flex;
flex-direction: column;
height: 100%;
}
.section {
flex-grow: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.header {
height: 64px;
background-color: lightblue;
flex-shrink: 0;
}
.wrapper {
flex-grow: 1;
overflow: auto;
min-height: 100%;
}
And if you'd like to get even fancier, take a look at my response to this question https://stackoverflow.com/a/52416148/1513083
final int[] positions=new int[2];
Spinner sp=findViewByID(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText( arg2....);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Well, you have [[
and ]]
to go to the start and end of file. This works in vi.
Square brackets are lists while parentheses are tuples.
A list is mutable, meaning you can change its contents:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
while tuples are not:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Note that, as many people have pointed out, you can add tuples together. For example:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
Whereas, if you were to construct this same example with a list, y
would also be updated:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
Use float-right
for block elements, or text-right
for inline elements:
<div class="row">
<div class="col">left</div>
<div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
<div class="col">left</div>
<div class="col">
<div class="float-right">element needs to be right aligned</div>
</div>
</div>
http://www.codeply.com/go/oPTBdCw1JV
If float-right
is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right
from working.
In some cases, the utility classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto
(margin-left:auto) is used in a flexbox element to push elements to the right.
To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:
I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).
So to resolve this:
Either
1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe
1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe
Then
2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.
From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.
I just add this line exactly as it appears below (if you need a second delay):
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// Process exception
}
I find the catch IS necessary (Your app can crash due to Android OS as much as your own code).
Query to check percentage "usage" of AUTO_INCREMENT for all tables of one given schema (except columns with type bigint unsigned):
SELECT
c.TABLE_NAME,
c.COLUMN_TYPE,
c.MAX_VALUE,
t.AUTO_INCREMENT,
IF (c.MAX_VALUE > 0, ROUND(100 * t.AUTO_INCREMENT / c.MAX_VALUE, 2), -1) AS "Usage (%)"
FROM
(SELECT
TABLE_SCHEMA,
TABLE_NAME,
COLUMN_TYPE,
CASE
WHEN COLUMN_TYPE LIKE 'tinyint(1)' THEN 127
WHEN COLUMN_TYPE LIKE 'tinyint(1) unsigned' THEN 255
WHEN COLUMN_TYPE LIKE 'smallint(%)' THEN 32767
WHEN COLUMN_TYPE LIKE 'smallint(%) unsigned' THEN 65535
WHEN COLUMN_TYPE LIKE 'mediumint(%)' THEN 8388607
WHEN COLUMN_TYPE LIKE 'mediumint(%) unsigned' THEN 16777215
WHEN COLUMN_TYPE LIKE 'int(%)' THEN 2147483647
WHEN COLUMN_TYPE LIKE 'int(%) unsigned' THEN 4294967295
WHEN COLUMN_TYPE LIKE 'bigint(%)' THEN 9223372036854775807
WHEN COLUMN_TYPE LIKE 'bigint(%) unsigned' THEN 0
ELSE 0
END AS "MAX_VALUE"
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE EXTRA LIKE '%auto_increment%'
) c
JOIN INFORMATION_SCHEMA.TABLES t ON (t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME)
WHERE
c.TABLE_SCHEMA = 'YOUR_SCHEMA'
ORDER BY
`Usage (%)` DESC;
ports:
expose:
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
It seems that if
Content-Type: application/json
andThen MVC doesn't really bind the POST body to any particular class. Nor can you just fetch the POST body as a param of the ActionResult (suggested in another answer). Fair enough. You need to fetch it from the request stream yourself and process it.
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
Update:
for Asp.Net Core, you have to add [FromBody]
attrib beside your param name in your controller action for complex JSON data types:
[HttpPost]
public ActionResult JsonAction([FromBody]Customer c)
Also, if you want to access the request body as string to parse it yourself, you shall use Request.Body
instead of Request.InputStream
:
Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
java.exe
is the console app while javaw.exe
is windows app (console-less). You can't have Console
with javaw.exe
.
I had the same problem but we can use the time zone we want
we use .toLocaleDateString()
eg:
var day=new Date();
const options= {day:'numeric', month:'long', year:"numeric", timeZone:"Asia/Kolkata"};
const today=day.toLocaleDateString("en-IN", options);
console.log(today);
_x000D_
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
I take no issue with the accepted answer as it certainly helped me. However, after implementing it, I still got the same error.
Turns out this was because I was calling the pipes incorrectly in my component as well:
My custom-pipe.ts file:
@Pipe({ name: 'doSomething' })
export class doSomethingPipe implements PipeTransform {
transform(input: string): string {
// Do something
}
}
So far, so good, but in my component.html file I was calling the pipes as follows:
{{ myData | doSomethingPipe }}
This will again throw the error that the pipe is not found. This is because Angular looks up the pipes by the name defined in the Pipe decorator. So in my example, the pipe should instead be called like this:
{{ myData | doSomething }}
Silly mistake, but it cost me a fair amount of time. Hope this helps!
I got same php warring in my wordpress site...
Err: Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:50547 Library:50628 in /home/lhu/public_html/innovacarrentalschennai.com/wp-includes/wp-db.php on line 1515
Cause: I updated wp 4.2 to 4.5 version (PHP and MySql mismatch )
I changed wp-db.php on line 1515
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
to
if ( WP_DEBUG ) {
$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}
Its got without warring err on my wordpress site
<video id="myvideo">
<source src="path/to/movie.mp4" />
</video>
<p onclick="toggleControls();">Toggle</p>
<script>
var video = document.getElementById("myvideo");
function toggleControls() {
if (video.hasAttribute("controls")) {
video.removeAttribute("controls")
} else {
video.setAttribute("controls","controls")
}
}
</script>
See it working on jsFiddle: http://jsfiddle.net/dgLds/
var doc = new DOMParser().parseFromString(html, "text/html");
var links = doc.querySelectorAll("a");
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.
Just a guess what does the variable json
contain after
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?
If it is a valid json object like {'foo':'foovalue', 'bar':'barvalue'}
then jQuery might not send it as json data but instead serialize it to foor=foovalue&bar=barvalue
thus you get the error "Invalid JSON primitive: foo"
Try instead setting the data as string
$.ajax({
...
data: "{'foo':'foovalue', 'bar':'barvalue'}", //note the additional quotation marks
...
})
This way jQuery should leave the data alone and send the string as is to the server which should allow ASP.NET to parse the json server side.
If you want to find all commits where commit message contains given word, use
$ git log --grep=word
If you want to find all commits where "word" was added or removed in the file contents (to be more exact: where number of occurences of "word" changed), i.e. search the commit contents, use so called 'pickaxe' search with
$ git log -Sword
In modern git there is also
$ git log -Gword
to look for differences whose added or removed line matches "word" (also commit contents).
Note that -G
by default accepts a regex, while -S
accepts a string, but can be modified to accept regexes using the --pickaxe-regex
.
To illustrate the difference between
-S<regex> --pickaxe-regex
and-G<regex>
, consider a commit with the following diff in the same file:+ return !regexec(regexp, two->ptr, 1, ®match, 0); ... - hit = !regexec(regexp, mf2.ptr, 1, ®match, 0);
While
git log -G"regexec\(regexp"
will show this commit,git log -S"regexec\(regexp" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
With Git 2.25.1 (Feb. 2020), the documentation is clarified around those regexes.
See commit 9299f84 (06 Feb 2020) by Martin Ågren (``).
(Merged by Junio C Hamano -- gitster
-- in commit 0d11410, 12 Feb 2020)
diff-options.txt
: avoid "regex" overload in exampleReported-by: Adam Dinwoodie
Signed-off-by: Martin Ågren
Reviewed-by: Taylor BlauWhen we exemplify the difference between
-G
and-S
(using--pickaxe-regex
), we do so using an example diff andgit diff
invocation involving "regexec", "regexp", "regmatch", ...The example is correct, but we can make it easier to untangle by avoiding writing "regex.*" unless it's really needed to make our point.
Use some made-up, non-regexy words instead.
The git diff
documentation now includes:
To illustrate the difference between
-S<regex> --pickaxe-regex
and-G<regex>
, consider a commit with the following diff in the same file:+ return frotz(nitfol, two->ptr, 1, 0); ... - hit = frotz(nitfol, mf2.ptr, 1, 0);
While
git log -G"frotz\(nitfol"
will show this commit,git log -S"frotz\(nitfol" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
You can do as @rmobis has specified in his answer, [Adding something more into it]
Using order by
twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by
:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As @rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate
in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
If you are interested in a "smooth" version of a signal that is periodic (like your example), then a FFT is the right way to go. Take the fourier transform and subtract out the low-contributing frequencies:
import numpy as np
import scipy.fftpack
N = 100
x = np.linspace(0,2*np.pi,N)
y = np.sin(x) + np.random.random(N) * 0.2
w = scipy.fftpack.rfft(y)
f = scipy.fftpack.rfftfreq(N, x[1]-x[0])
spectrum = w**2
cutoff_idx = spectrum < (spectrum.max()/5)
w2 = w.copy()
w2[cutoff_idx] = 0
y2 = scipy.fftpack.irfft(w2)
Even if your signal is not completely periodic, this will do a great job of subtracting out white noise. There a many types of filters to use (high-pass, low-pass, etc...), the appropriate one is dependent on what you are looking for.
Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
if ($.isNumeric(id)) {
//it's numeric
}
CORRECTION: that would not ensure an integer. This would:
if ( (id+"").match(/^\d+$/) ) {
//it's all digits
}
That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works
This one works for me:
function removeDirectory($path) {
$files = glob($path . '/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}
I had massive problems with getting any of those scripts to work with sending mail in powershell. Turned out you need to create an app-password for your gmail-account to authenticate in the script. Now it works flawlessly!
You can do that by applying your rotate CSS to an inner element and then adjusting the height of the element to match its width since the element was rotated to fit it into the <td>
.
Also make sure you change your id
#rotate
to a class since you have multiple.
$(document).ready(function() {_x000D_
$('.rotate').css('height', $('.rotate').width());_x000D_
});
_x000D_
td {_x000D_
border-collapse: collapse;_x000D_
border: 1px black solid;_x000D_
}_x000D_
tr:nth-of-type(5) td:nth-of-type(1) {_x000D_
visibility: hidden;_x000D_
}_x000D_
.rotate {_x000D_
/* FF3.5+ */_x000D_
-moz-transform: rotate(-90.0deg);_x000D_
/* Opera 10.5 */_x000D_
-o-transform: rotate(-90.0deg);_x000D_
/* Saf3.1+, Chrome */_x000D_
-webkit-transform: rotate(-90.0deg);_x000D_
/* IE6,IE7 */_x000D_
filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=0.083);_x000D_
/* IE8 */_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)";_x000D_
/* Standard */_x000D_
transform: rotate(-90.0deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>10kg</div>_x000D_
</td>_x000D_
<td>B</td>_x000D_
<td>C</td>_x000D_
<td>D</td>_x000D_
<td>E</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>20kg</div>_x000D_
</td>_x000D_
<td>G</td>_x000D_
<td>H</td>_x000D_
<td>I</td>_x000D_
<td>J</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div class='rotate'>30kg</div>_x000D_
</td>_x000D_
<td>L</td>_x000D_
<td>M</td>_x000D_
<td>N</td>_x000D_
<td>O</td>_x000D_
</tr>_x000D_
_x000D_
_x000D_
</table>
_x000D_
JavaScript
The equivalent to the above in pure JavaScript is as follows:
window.addEventListener('load', function () {
var rotates = document.getElementsByClassName('rotate');
for (var i = 0; i < rotates.length; i++) {
rotates[i].style.height = rotates[i].offsetWidth + 'px';
}
});
Check the encoding of your file. I was using netbeans and had to use iso windows 1252 encoding for an old project and netbeans was using this encoding since then for every new file. json_decode will then return NULL. Saving the file again with UTF-8 encoding solved the problem for me.
GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.
Hiding the cursor can be done with ShowCursor().
I'm guessing you used Brew to install Node, so the guide here might be helpful http://madebyhoundstooth.com/blog/install-node-with-homebrew-on-os-x/.
You need to ensure that the npm/bin is in your path as it describes export PATH="/usr/local/share/npm/bin:$PATH"
. This is the location that npm will install the bin stubs for the installed packages.
The nano version will also work as described here http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/ but a restart of Terminal may be required to have the new path picked up.
A endpoint is a URL for web service.And Endpoints also is a distributed API.
The Simple Object Access Protocol (SOAP) endpoint is a URL. It identifies the location on the built-in HTTP service where the web services listener listens for incoming requests.
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if
" statements to do it, either:
if (x >= 0.001 && x <= 0.009) {
// something
}
You could write yourself a "between()" function:
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
select s.id, s.age, c.count
from students s
inner join (
select age, count(*) as count
from students
group by age
) c on s.age = c.age
order by id
After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class
<td>
myClassNameProperty
</td>
<td>
myClassNameProperty, This is direct from Item
</td>
This is the generated HTML from below code
<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)
</td>
<td>
@item.Genre.Name, This is direct from Item
</td>
At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least
i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below
@item.Genre.Name
@item.Genre.Id
@item.Genre.Description
and so on depending on number of properties.
You can use a turn-around and just deploy the application into tomcat server: just copy/paste under the webapps folder. Once tomcat is started, it will create a folder with the app name and you can access the contents directly
1.Use git reflog
to get all references update.
2.git reset <id_of_commit_to_which_you_want_restore>
use this regex: /<[^<]+?>/g
$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);
$businessDesc = substr(val,0,110);
from your example should stay: Ref no: 30001
server_name supports suffix matches using .mydomain.com syntax:
server {
server_name .mydomain.com;
rewrite ^ http://www.adifferentdomain.com$request_uri? permanent;
}
or on any version 0.9.1 or higher:
server {
server_name .mydomain.com;
return 301 http://www.adifferentdomain.com$request_uri;
}
I think the easiest way is to hide the broken image icon by the text-indent property.
img {
text-indent: -10000px
}
Obviously it doesn't work if you want to see the "alt" attribute.
First you should remove existing key. SSH keys in most of Linux-based OS will be saved this file "/root/.ssh/known_hosts", so in order to remove the key related to host the following command will be used:
ssh-keygen -f "/root/.ssh/known_hosts" -R [Hostname]
Regards K1
Using the function above, you would do:
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
Of course, the following would also work:
var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];
since all objects in JavaScript are hash tables! It would, however, be harder to iterate over since using foreach(var item in object)
would also get you all its functions, etc., but that might be enough depending on your needs.
Try... for YUI
Dom.get("gadget_url").set("value","");
with normal Javascript
document.getElementById('gadget_url').value = '';
with JQuery
$("#gadget_url").val("");
I'm writtinga phonegap app, and checkboxes vary in size, look, etc. So I made my own simple checkbox:
First the HTML code:
<span role="checkbox"/>
Then the CSS:
[role=checkbox]{
background-image: url(../img/checkbox_nc.png);
height: 15px;
width: 15px;
display: inline-block;
margin: 0 5px 0 5px;
cursor: pointer;
}
.checked[role=checkbox]{
background-image: url(../img/checkbox_c.png);
}
To toggle checkbox state, I used JQuery:
CLICKEVENT='touchend';
function createCheckboxes()
{
$('[role=checkbox]').bind(CLICKEVENT,function()
{
$(this).toggleClass('checked');
});
}
But It can easily be done without it...
Hope it can help!
I wanted to check on multiple file types and was to lazy to calculate the total by hand. So I use this now to get the total in one go.
find . -name '*.js' -or -name '*.php' | xargs wc -l | grep 'total' | awk '{ SUM += $1; print $1} END { print "Total text lines in PHP and JS",SUM }'
79351
15318
Total text lines in PHP and JS 94669
This allows you to chain multiple extension types you wish to filter on. Just add them in the -name '*.js' -or -name '*.php'
part, and possibly modify the otuput message to your liking.
As per this example:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
will produce:
To unpack your data from pairs into lists use zip
:
x, y = zip(*li)
So, the one-liner:
plt.scatter(*zip(*li))
If there is XML file with 2 different tables then will:
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1
LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table2
work
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n0 = input.nextInt(); // number of intended input.
int [] MyList = new int [n0];
for (int i = 0; i < n0; i++)
MyList[i] = input.nextInt();
//input values stored in an array
int i = 0;
int count = 0;
int gcd = 1; // Initial gcd is 1
int k = 2; // Possible gcd
while (k <= MyList[i] && k <= MyList[i]) {
if (MyList[i] % k == 0 && MyList[i] % k == 0)
gcd = k; // Update gcd
k++;
count++; //checking array for gcd
}
// int i = 0;
MyList [i] = gcd;
for (int e: MyList) {
System.out.println(e);
}
}
}
The correct scheme should be:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<simpleContent>
<extension base="string">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</extension>
</simpleContent>
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code generated for SportType will be:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlValue
protected String value;
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
I find the answers to this question to be problematic, confusing and incomplete, so I'll make an effort to do better.
Nobody has really answered this in any complete fashion. The information on setting locks in the Access options has nothing to do with read vs. write locking. No Locks vs. All Records vs. Edited Record is how you set the default record locking for WRITES.
No locks means you are using OPTIMISTIC locking, which means you allow multiple users to edit the record and then inform them after the fact if the record has changed since they launched their own edits. Optimistic locking is what you should start with as it requires no coding to implement it, and for small users populations it hardly ever causes a problem.
All Records means that the whole table is locked any time an edit is launched.
Edited Record means that fewer records are locked, but whether or not it's a single record or more than one record depends on whether your database is set up to use record-level locking (first added in Jet 4) or page-level locking. Frankly, I've never thought it worth the trouble to set up record-level locking, as optimistic locking takes care of most of the problems.
One might think that you want to use record-level pessimistic locking, but the fact is that in the vast majority of apps, two users are almost never editing the same record. Now, obviously, certain kinds of apps might be exceptions to that, but if I ran into such an app, I'd likely try to engineer it away by redesigning the schema so that it would be very uncommon for two users to edit the same record (usually by going to some form of transactional editing instead, where changes are made by adding records, rather than editing the existing data).
Now, for your actual question, there are a number of ways to accomplish restricting some users to read-only and granting others write privileges. Jet user-level security was intended for this purpose and works fine insofar as it's "security" for any meaningful definition of the term. In general, as long as you're using a Jet/ACE data store, the best security you're going to get is that provided by Jet ULS. It's crackable, yes, but your users would be committing a firable offense by breaking it, so it might be sufficient.
I would tend to not implement Jet ULS at all and instead just architect the data editing forms such that they checked the user's Windows logon and made the forms read-only or writable depending on which users are supposed to get which access. Whether or not you want to record group membership in a data table, or maintain Windows security groups for this purpose is up to you. You could also use a Jet workgroup file to deal with it, and provide a different system.mdw file for the write users. The read-only users would log on transparently as admin, and those logged on as admin would be granted only read-only access. The write users would log on as some other username (transparently, in the shortcut you provide them for launching the app, supplying no password), and that would be used to set up the forms as read or write.
If you use Jet ULS, it can become really hairy to get it right. It involves locking down all the tables as read-only (or maybe not even that) and then using RWOP queries to provide access to the data. I haven't done but one such app in my 14 years of professional Access development.
To summarize my answers to the parts of your question:
I would recommend doing this in the application, setting forms to read/only or editable at runtime depending on the user logon. The easiest approach is to set your forms to be read-only and change to editable for the write users when they open the form.
Not in any meaningful sense. Jet/ACE does have read locks, but they are there only for the purpose of maintaining state for individual views, and for refreshing data for the user. They do not lock out write operations of any kind, though the overhead of tracking them theoretically slows things down. It's not enough to worry about.
Access in combination with Jet/ACE does this for you automatically, particularly if you choose optimistic locking as your default. The key point here is that Access apps are databound, so as soon as a form is loaded, the record has a read lock, and as soon as the record is edited, whether or not it is write-locked for other users is determined by whether you are using optimistic or pessimistic locking. Again, this is the kind of thing Access takes care of for you with its default behaviors in bound forms. You don't worry about any of it until the point at which you encounter problems.
Basically, other than setting editability at runtime (according to who has write access), there is no coding necessary if you're using optimistic locking. With pessimistic locking, you don't have to code, but you will almost always need to, as you can't just leave the user stuck with the default behaviors and error messages.
Jet/ACE has support for commit/rollback transactions, but it's not clear to me if that's what you mean in this question. In general, I don't use transactions except for maintaining atomicity, e.g., when creating an invoice, or doing any update that involves multiple tables. It works about the way you'd expect it to but is not really necessary for the vast majority of operations in an Access application.
Perhaps one of the issues here (particularly in light of the first question) is that you may not quite grasp that Access is designed for creating apps with data bound to the forms. "Transactions" is a topic of great importance for unbound and stateless apps (e.g., browser-based), but for data bound apps, the editing and saving all happens transparently.
For certain kinds of operations this can be problematic, and occasionally it's appropriate to edit data in Access with unbound forms. But that's very seldom the case, in my experience. It's not that I don't use unbound forms -- I use lots of them for dialogs and the like -- it's just that my apps don't edit data tables with unbound forms. With almost no exceptions, all my apps edit data with bound forms.
Now, unbound forms are actually fairly easy to implement in Access (particularly if you name your editing controls the same as the underlying fields), but going with unbound data editing forms is really missing the point of using Access, which is that the binding is all done for you. And the main drawback of going unbound is that you lose all the record-level form events, such as OnInsert, BeforeUpdate and so forth.
This is one of the questions that's been well-addressed. All multi-user or replicated Access apps should be split, and most single-user apps should be, too. It's good design and also makes the apps more stable, as only the data tables end up being opened by more than one user at a time.
"Things?" What things?
I don't know anything specifically about Oracle (none of my clients could afford it even if they wanted to), but asking for a comparison of Access and Oracle betrays a fundamental misunderstanding somewhere along the line.
Access is an application development tool.
Oracle is an industrial strength database server.
Apples and oranges.
Now, of course, Access ships with a default database engine, originally called Jet and now revised and renamed ACE, but there are many levels at which Access the development platform can be entirely decoupled from Jet/ACE, the default database engine.
In this case, you've chosen to use a Jet/ACE back end, which will likely be just fine for small user populations, i.e., under 25. Jet/ACE can also be fine up to 50 or 100, particularly when only a few of the simultaneous users have write permission. While the 255-user limit in Jet/ACE includes both read-only and write users, it's the number of write users that really controls how many simultaneous users you can support, and in your case, you've got an app with mostly read-only users, so it oughtn't be terribly difficult to engineer a good app that has no problems with the back end.
Basically, I think your Oracle background is likely leading you to misunderstand how to develop in Access, where the expected approach is to bind your forms to recordsources that are updated without any need to write code. Now, for efficiency's sake it's a good idea to bind your forms to subsets of records, rather than to whole tables, but even with an entire table in the recordsource behind a data editing form, Access is going to be fairly efficient in editing Jet/ACE tables (the old myth about pulling the whole table across the wire is still out there) as long your data tables are efficiently indexed.
Record locking is something you mostly shouldn't have any cause to worry about, and one of the reasons for that is because of bound editing, where the form knows what's going on in the back end at all times (well, at intervals about a second apart, the default refresh interval). That is, it's not like a web page where you retrieve a copy of the data and then post your edits back to the server in a transaction completely unconnected to the original data retrieval operation. In a bound environment like Access, the locking file on the back-end data file is always going to be keeping track of the fact that someone has the record open for editing. This prevents a user's edits from stomping on someone else's edits, because Access knows the state and informs the user. This all happens without any coding on the part of the developer and is one of the great advantages of the bound editing model (aside from not having to write code to post the edits).
For all those who are experienced database programmers familiar with other platforms who are coming to Access for the first time, I strongly suggest using Access like an end user. Try out all the point and click features. Run the form and report wizards and check out the results that they produce. I can't vouch for all of them as demonstrating good practices, but they definitely demonstrate the default assumptions behind the way Access is intended to be used.
If you find yourself writing a lot of code, then you're likely missing the point of Access.
Would it be as easy as running a LINQ query on your List?
List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();
If nginx_ajp_module is used, try adding
ajp_read_timeout 10m;
in nginx.conf file.
Would you please try with below code block, which is exactly what you're looking for:
SqlConnection conn = new SqlConnection
{
ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Database.sdf"
};
If you want input comma separated string as input & apply in in query in that then you can make Function like:
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(MAX))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end;
You can use it like :
Declare @Values VARCHAR(MAX);
set @Values ='1,2,5,7,10';
Select * from DBTable
Where id in (select items from [dbo].[Split] (@Values, ',') )
Alternatively if you don't have comma-separated string as input, You can try Table variable
OR TableType
Or Temp table
like: INSERT using LIST into Stored Procedure
fun rotateArrow(view: View): Boolean {
return if (view.rotation == 0F) {
view.animate().setDuration(200).rotation(180F)
true
} else {
view.animate().setDuration(200).rotation(0F)
false
}
}
simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1
SET @a = 50000835 ;
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1
WHERE external_identifier IS NULL;
@classmethod
can be useful for easily instantiating objects of that class from outside resources. Consider the following:
import settings
class SomeClass:
@classmethod
def from_settings(cls):
return cls(settings=settings)
def __init__(self, settings=None):
if settings is not None:
self.x = settings['x']
self.y = settings['y']
Then in another file:
from some_package import SomeClass
inst = SomeClass.from_settings()
Accessing inst.x will give the same value as settings['x'].
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.
An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478
Why not keep it simple?!
GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()
giving you,
print(GB)
abc xyz
2013 6 80 250
8 40 -5
2014 1 25 15
2 60 80
and then you can plot like asked using,
GB.plot('abc','xyz',kind='scatter')
Could you use jQuery, since it's cross-browser compatible?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };
Assuming that you've written an equals method for Dog correctly that compares based on the id of the Dog the easiest and simplest way to return an item in the list is as follows.
if (dogList.contains(dog)) {
return dogList.get(dogList.indexOf(dog));
}
That's less performance intensive that other approaches here. You don't need a loop at all in this case. Hope this helps.
P.S You can use Apache Commons Lang to write a simple equals method for Dog as follows:
@Override
public boolean equals(Object obj) {
EqualsBuilder builder = new EqualsBuilder().append(this.getId(), obj.getId());
return builder.isEquals();
}
From, Programming Recommendations, PEP 8:
Comparisons to singletons like None should always be done with
is
oris not
, never the equality operators.Also, beware of writing
if x
when you really meanif x is not None
— e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
PEP 8 is essential reading for any Python programmer.
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
It surprises me that this is a highly voted answers without mentioning the origin of MVVM. MVVM is a popular term used in Microsoft community and it is originated from Martin Fowler's Presentation Model. So to understand the motive of the pattern and the differences with others, the original article about the pattern is the first thing to read.
If make config
works for your program or you have a shell script which copies your two files to the appropriate place you can use checkinstall. Just go to the directory where your makefile is in and call it with the parameter -R
(for RPM) and optionally with the installation script.
Three things.
tr
(or cat
, etc.) is absolutely not needed. (GNU) sed
and (GNU) awk
, when combined, can do 99.9% of any text processing you need.
stream != line based. ed
is a line-based editor. sed
is not. See sed lecture for more information on the difference. Most people confuse sed
to be line-based because it is, by default, not very greedy in its pattern matching for SIMPLE matches - for instance, when doing pattern searching and replacing by one or two characters, it by default only replaces on the first match it finds (unless specified otherwise by the global command). There would not even be a global command if it were line-based rather than STREAM-based, because it would evaluate only lines at a time. Try running ed
; you'll notice the difference. ed
is pretty useful if you want to iterate over specific lines (such as in a for-loop), but most of the times you'll just want sed
.
That being said,
sed -e '{:q;N;s/\n/ /g;t q}' file
works just fine in GNU sed
version 4.2.1. The above command will replace all newlines with spaces. It's ugly and a bit cumbersome to type in, but it works just fine. The {}
's can be left out, as they're only included for sanity reasons.
In your example:
items.map! { |x| process_x url } # [1, 2, 3, 4, 5] => [1, nil, 3, nil, nil]
it does not look like the values have changed other than being replaced with nil
. If that is the case, then:
items.select{|x| process_x url}
will suffice.
Including this worked for me.
Please include the line mentioned below in the section.
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js'>
Do you create the DataTables yourself? Because iterating through the children of any Object (as in DataSet.Tables) is usually not needed, as it's the job of the Parent to dispose all its child members.
Generally, the rule is: If you created it and it implements IDisposable, Dispose it. If you did NOT create it, then do NOT dispose it, that's the job of the parent object. But each object may have special rules, check the Documentation.
For .NET 3.5, it explicitly says "Dispose it when not using anymore", so that's what I would do.
If you're using Bash or zsh, use this:
type -a lshw
This will show whether the target is a builtin, a function, an alias or an external executable. If the latter, it will show each place it appears in your PATH
.
bash$ type -a lshw
lshw is /usr/bin/lshw
bash$ type -a ls
ls is aliased to `ls --color=auto'
ls is /bin/ls
bash$ zsh
zsh% type -a which
which is a shell builtin
which is /usr/bin/which
In Bash, for functions type -a
will also display the function definition. You can use declare -f functionname
to do the same thing (you have to use that for zsh, since type -a
doesn't).
A common PyTorch convention is to save models using either a .pt or .pth file extension.
Save/Load Entire Model Save:
path = "username/directory/lstmmodelgpu.pth"
torch.save(trainer, path)
Load:
model = torch.load(PATH)
model.eval()
This article has a good discussion on this issue. You can use
SELECT *
FROM Y
INNER JOIN X ON EXISTS(SELECT X.QID
INTERSECT
SELECT y.QID);
Here's my humble opinion. !!!! Don't !!!! change settings on the server to make your parameters work correctly. This is a time bomb waiting to happen someday when you change servers.
The best way I have found is to just convert the parameter to base 64 encoding. So in my case, I'm calling a php service from Angular and passing a parameter that could contain any value.
So my typescript code in the client looks like this:
private encodeParameter(parm:string){
if (!parm){
return null;
}
return btoa(parm);
}
And to retrieve the parameter in php:
$item_name = $request->getAttribute('item_name');
$item_name = base64_decode($item_name);
The swift way to do it:
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()
Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,
+----------+
| _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|
I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.
df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")
Here I'm creating a temporary view and store the year values using this single line and the output will be,
+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
| 1872|
| 1873|
| 1874|
| 1875|
| 1876|
| 1876|
| 1877|
| 1877|
| 1878|
| 1878|
| 1879|
| 1879|
| 1879|
This is currently on the Preferences tab which is the default. You may need to scroll down. This checkbox has been moved at least a couple times since this question was asked. Last I checked, it was in the middle column at the bottom. If you have it open on a thinner screen and there are 2 columns under Preferences, it may be near the top right. Feel free to update this post if it changes or comment and I'll update the post.
Below mentioned link gives the clear explanation with example.
http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx
Code from the same link
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
modal: true,
autoOpen: false,
title: "jQuery Dialog",
width: 300,
height: 150
});
$("#btnShow").click(function () {
$('#dialog').dialog('open');
});
});
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
This is a jQuery Dialog.
</div>
You can limit the depth of the history while cloning:
--depth <depth>
Create a shallow clone with a history truncated to the specified
number of revisions.
Use this if you want limited history, but still some.
this way is a bit more flexible than using all()
:
my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False
or more succinctly:
all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]
You may want to look into os dependent line separators, e.g.:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
Create a xml file in drawable folder like below
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
<solid android:color="#ABABAB"/>
<corners android:radius="10dp"/>
</shape>
Apply this as background to button you want make corners round.
Or you can use separate radius for every corner like below
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
CSS Keyframes support is pretty good these days:
.fade-in {_x000D_
opacity: 1;_x000D_
animation-name: fadeInOpacity;_x000D_
animation-iteration-count: 1;_x000D_
animation-timing-function: ease-in;_x000D_
animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
If you want to find the folder in a platform independent way, you should query the registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache
Suppose you store float value in "X"
and you are storing integer value in "Y"
.
Var Y = Int(x);
or
var myIntValue = Int(myFloatValue)
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2
WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO
In my case the error happened when i move from my local PC Windows 10 to a dedicated server with Windows 2012. The solution for was to add to the web.config the following lines
<webServices>
<protocols>
<add name="Documentation"/>
</protocols>
</webServices>
One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint
create table Customer ( id int primary key identity (1,1) , name nvarchar(128) )
--Commands completed successfully.
sp_help Customer
---> index
--index_name index_description index_keys
--PK__Customer__3213E83FCC4A1DFA clustered, unique, primary key located on PRIMARY id
---> constraint
--constraint_type constraint_name delete_action update_action status_enabled status_for_replication constraint_keys
--PRIMARY KEY (clustered) PK__Customer__3213E83FCC4A1DFA (n/a) (n/a) (n/a) (n/a) id
---- now adding the unique constraint
ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)
-- Commands completed successfully.
sp_help Customer
---> index
---index_name index_description index_keys
---PK__Customer__3213E83FCC4A1DFA clustered, unique, primary key located on PRIMARY id
---U_Name nonclustered, unique, unique key located on PRIMARY name
---> constraint
---constraint_type constraint_name delete_action update_action status_enabled status_for_replication constraint_keys
---PRIMARY KEY (clustered) PK__Customer__3213E83FCC4A1DFA (n/a) (n/a) (n/a) (n/a) id
---UNIQUE (non-clustered) U_Name (n/a) (n/a) (n/a) (n/a) name
as you can see , there is a new constraint and a new index U_Name
both would work the same, its just two different methods to call the same function. Try the following:
<a href="javascript:history.back();">[Go Back]</a>
To get that file use the below code.
include(Mage::getBaseDir('skin').'myfunc.php');
But it is not a correct way. To add your custom functions you can use the below file.
app/code/core/Mage/core/functions.php
Kindly avoid to use the PHP function under skin dir.
Some receivers expect EOL sequence, which is typically two characters \r\n
, so try in your code replace the line
unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};
with
unsigned char cmd[] = "INIT\r\n";
BTW, the above way is probably more efficient. There is no need to quote every character.
You have an error in your code. This line:
for(int i=0;i<v[n];i++)
should be
for(int i=0;i<n;i++)
because you want to search n
places in your vector, not v[n]
places (which wouldn't mean anything)
Kotlin allows for even simpler code than what's shown in other answers.
To get the new token whenever it's refreshed:
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onNewToken(token: String?) {
Log.d("FMS_TOKEN", token)
}
...
}
To get the token from anywhere at runtime:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
Log.d("FMS_TOKEN", it.token)
}
The first version is a null object while the second is an Array object with zero elements.
Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.
You should use this GBDeviceInfo framework or ...
Apple defines this:
public enum UIUserInterfaceIdiom : Int {
case unspecified
case phone // iPhone and iPod touch style UI
case pad // iPad style UI
@available(iOS 9.0, *)
case tv // Apple TV style UI
@available(iOS 9.0, *)
case carPlay // CarPlay style UI
}
so for the strict definition of the device can be used this code
struct ScreenSize
{
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType
{
static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_6_7 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_6P_7P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
static let IS_IPAD_PRO = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0
}
how to use
if DeviceType.IS_IPHONE_6P_7P {
print("IS_IPHONE_6P_7P")
}
to detect iOS version
struct Version{
static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
static let iOS7 = (Version.SYS_VERSION_FLOAT < 8.0 && Version.SYS_VERSION_FLOAT >= 7.0)
static let iOS8 = (Version.SYS_VERSION_FLOAT >= 8.0 && Version.SYS_VERSION_FLOAT < 9.0)
static let iOS9 = (Version.SYS_VERSION_FLOAT >= 9.0 && Version.SYS_VERSION_FLOAT < 10.0)
}
how to use
if Version.iOS8 {
print("iOS8")
}
Add a trigger in database:
DELIMITER //
CREATE TRIGGER update_user_password
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
IF OLD.password <> NEW.password THEN
SET NEW.password_changed_on = NOW();
END IF;
END //
DELIMITER ;
The password changed time will update only when password column is changed.
|*| Installing Bootstrap 4 for Angular 2, 4, 5, 6 + :
|+> Install Bootstrap with npm
npm install bootstrap --save
npm install popper.js --save
|+> Add styles and scripts to angular.json
"architect": [{
...
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.scss"
],
"scripts": [
"node_modules/jquery/dist/jquery.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
...
}]
All three template options - <%@include>
, <jsp:include>
and <%@tag>
are valid, and all three cover different use cases.
With <@include>
, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include
). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include>
(and JSTL's <c:import>
, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import>
also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute>
and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
I would do it this way (Reference http://www.w3.org/TR/page-visibility/):
window.onload = function() {
// check the visiblility of the page
var hidden, visibilityState, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
}
else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
}
else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
}
else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
}
if (typeof document.addEventListener === "undefined" || typeof hidden === "undefined") {
// not supported
}
else {
document.addEventListener(visibilityChange, function() {
console.log("hidden: " + document[hidden]);
console.log(document[visibilityState]);
switch (document[visibilityState]) {
case "visible":
// visible
break;
case "hidden":
// hidden
break;
}
}, false);
}
if (document[visibilityState] === "visible") {
// visible
}
};
Also you can use apache commons lib DateUtils.truncate()
:
Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);
Time will be set to 00:00:00
so you can work with this date or print it formatted:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(now); // 2010-05-11 11:32:47
System.out.println(dateFormat.format(truncated); // 2010-05-11 00:00:00
I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html
The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...
However, I’m not sure about using canvas to compress images, but you can certainly resize them.
Lets Think this is your HTML Form in step2.php
step2.php
<form name="new user" method="post" action="step2_check.php">
<input type="text" name="mail"/> <br />
<input type="password" name="password"/><br />
<input type="submit" value="continue"/>
</form>
I think you need it for your database, so you can assign your HTML Form Value to php Variable, now you can use Real Escape String and below must be your
step2_check.php
if(isset($_POST['mail']) && !empty($_POST['mail']))
{
$mail = mysqli_real_escape_string($db, $_POST['mail']);
}
Where $db is your Database Connection.
No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:
$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
After setting the gems directory to the user directory that runs the gem install
, using export GEM_HOME=/home/<user>/gems
, the issue has been solved.
you may also like this
var Grp = Model.GroupBy(item => item.Order.Customer)
.Select(group => new
{
Customer = Model.First().Customer,
CustomerId= group.Key,
Orders= group.ToList()
})
.ToList();
You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.
You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.
I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.
Try this...
var str = 'f 34 545 323 12345 54321 123456',
matches = str.match(/\b\d{5}\b/g);
console.log(matches); // ["12345", "54321"]
The word boundary \b
is your friend here.
My regex will get a number like this 12345
, but not like a12345
. The other answers provide great regexes if you require the latter.
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
Modern browsers support native querySelectorAll
so you can do:
document.querySelectorAll('[data-foo="value"]');
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
Details about browser compatibility:
You can use jQuery to support obsolete browsers (IE9 and older):
$('[data-foo="value"]');
Follow these steps to run your application on the device connected.
1. Change directories to the root of your Android project and execute:
ant debug
2. Make sure the Android SDK platform-tools/
directory is included in your PATH
environment variable, then execute: adb install bin/<*your app name*>-debug.apk
On your device, locate <*your app name*>
and open it.
Refer Running App
I know this post is super old, but I have an answer that's surprisingly missing from the above and is also much simpler than most.
<Button>
<Button.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="5"/>
</Style>
</Button.Resources>
</Button>
Since the default ControlTemplate for the Button control uses a Border element, adding a style for Border to the Button's resources applies that style to that Border. This lets you add rounded corners without having to make your own ControlTemplate and without any code. It also works on all varieties of Button (e.g. ToggleButton and RepeatButton).
You need to add schema locations to your bean definition, and then they can be found in classpath instead of fetched over the net. Given your formatting problems, I'm not 100% sure that you aren't doing this already.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- empty: the beans we use are in the base class's context. -->
</beans>
Open a new connection when the Node.js application starts, and reuse the existing db
connection object:
/server.js
import express from 'express';
import Promise from 'bluebird';
import logger from 'winston';
import { MongoClient } from 'mongodb';
import config from './config';
import usersRestApi from './api/users';
const app = express();
app.use('/api/users', usersRestApi);
app.get('/', (req, res) => {
res.send('Hello World');
});
// Create a MongoDB connection pool and start the application
// after the database connection is ready
MongoClient.connect(config.database.url, { promiseLibrary: Promise }, (err, db) => {
if (err) {
logger.warn(`Failed to connect to the database. ${err.stack}`);
}
app.locals.db = db;
app.listen(config.port, () => {
logger.info(`Node.js app is listening at http://localhost:${config.port}`);
});
});
/api/users.js
import { Router } from 'express';
import { ObjectID } from 'mongodb';
const router = new Router();
router.get('/:id', async (req, res, next) => {
try {
const db = req.app.locals.db;
const id = new ObjectID(req.params.id);
const user = await db.collection('user').findOne({ _id: id }, {
email: 1,
firstName: 1,
lastName: 1
});
if (user) {
user.id = req.params.id;
res.send(user);
} else {
res.sendStatus(404);
}
} catch (err) {
next(err);
}
});
export default router;
$_SERVER['HTTP_REFERER']
will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _
, is that a typo?
You probablly have 2 different versions of hibernate-jpa-api on the classpath. To check that run:
mvn dependency:tree >dep.txt
Then search if there are hibernate-jpa-2.0-api and hibernate-jpa-2.1-api. And exclude the excess one.
FractionallySizedBox
may also be useful.
You can also read the screen width directly out of MediaQuery.of(context).size
and create a sized box based on that
MediaQuery.of(context).size.width * 0.65
if you really want to size as a fraction of the screen regardless of what the layout is.
Above methods will remove your output file data whenever you run above nohup command.
To Append output in user defined file you can use >>
in nohup command.
nohup your_command >> filename.out &
This command will append all output in your file without removing old data.
This can also be done in the GUI:
The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:
new google.maps.Size(42,68)
I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
Your nav
div
is actually centered correctly. But the ul
inside is not. Give the ul
a specific width and center that as well.
EDIT 2 (final) : According to the bootstrap 4 documentation, class="font-weight-bold"
is what you are looking for.
EDIT : You can use class="font-weight-bold"
as shown here (Bootstrap 4 alpha).
I kept the original answer below for clarity purposes.
I am posting this answer because this thread seems to have a lot of visitors, yet it had no proper solution to solve this issue. But there will be soon now a way with Bootstrap 4 :
As this GitHub pull request shows, you will just have to use the text-weight-normal
, text-weight-bold
and text-weight-italic
classes.
This can maybe change until the official stable release. At this date of writing, this pull request is not merged yet in the alpha branch.
I will update this post once Bootstrap v4 has been released.
Here is a way that I would do it:
public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint.
try {
Integer.parseInt(player);
return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST);
} catch (Exception e) {
}
Message msg = new Message(player, "Hello " + player);
return new ResponseEntity < Message > (msg, HttpStatus.OK);
}
@RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint.
try {
Integer.parseInt(player);
List < ErrorResponse > errs = new ArrayList < ErrorResponse > ();
errs.add(new ErrorResponse("111", "player is not found"));
return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST);
} catch (Exception e) {
}
Message msg = new Message(player, "Hello " + player);
List < Message > msgList = new ArrayList < Message > ();
msgList.add(msg);
return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK);
}
It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
There where a lot of solutions with .addImage, I tried many of them, but nothing worked out. So I found the .html() function and after some tries the html2canvas-scale-option. This solution is no general solution, you have to adjust the scale so it will fit your pdf, but this is the only solution, which works for me.
var doc = new jspdf.jsPDF({
orientation: 'p',
unit: 'pt',
format: 'a4'
});
doc.html(document.querySelector('#styledTable'), {
callback: function (doc) {
doc.save('file.pdf');
},
margin: [60, 60, 60, 60],
x: 32,
y: 32,
html2canvas: {
scale: 0.3, //this was my solution, you have to adjust to your size
width: 1000 //for some reason width does nothing
},
});
It got simplified with newer version of rxjs .
import {map} from 'rxjs/operators';
import {Observable,of, from } from 'rxjs';
Instead of chaining we need to pipe . For example
Old syntax :
source.map().switchMap().subscribe()
New Syntax:
source.pipe(map(), switchMap()).subscribe()
Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:
do
-> tap
,
catch
-> catchError
switch
-> switchAll
finally
-> finalize
I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.
import { Rx } from 'rxjs/Rx'
;This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.
public cache = new Rx.BehaviorSubject('');
Or you can import individual operators .
This will Optimize your app to use only those files :
import { _______ } from 'rxjs/_________';
This syntax usually used for main Object like Rx
itself or Observable
etc.,
Keywords which can be imported with this syntax
Observable, Observer, BehaviorSubject, Subject, ReplaySubject
import 'rxjs/add/observable/__________';
Update for Angular 5
With Angular 5, which uses rxjs 5.5.2+
import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';
These are usually accompanied with Observable directly. For example
Observable.from()
Observable.of()
Other such keywords which can be imported using this syntax:
concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of,
range, throw, timer, using, zip
import 'rxjs/add/operator/_________';
Update for Angular 5
With Angular 5, which uses rxjs 5.5.2+
import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';
These usually come in the stream after the Observable is created. Like flatMap
in this code snippet:
Observable.of([1,2,3,4])
.flatMap(arr => Observable.from(arr));
Other such keywords using this syntax:
audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay,
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck,
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take,
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip
FlatMap:
flatMap
is alias to mergeMap
so we need to import mergeMap
to use flatMap
.
Note for /add
imports :
We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.
Go To Build.Gradle(module:app)
use this - minifyEnabled false