Usually all users will have write access to /tmp. Place the file to /tmp and then login to putty , then you can sudo and copy the file.
You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.
You have two options:
Grant write permissions to the folder to the user or group you log in with (myuser
), or change the ownership of the folder to the user, or
Disable a transfer to temporary file.
In Preferences, go to Transfer > Endurance page and in Enable transfer resume/transfer to temporary file name for select Disable:
copssh - OpenSSH for Windows
http://www.itefix.no/i2/copssh
Packages essential Cygwin binaries.
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.
Download WinSCP .NET assembly.
The latest package as of now is WinSCP-5.17.10-Automation.zip
;
Extract the .zip
archive along your script;
Use a code like this (based on the official PowerShell upload example):
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload
$session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
You can have WinSCP generate the PowerShell script for the upload for you:
You will get a code like above with all session and transfer settings filled in.
(I'm the author of WinSCP)
Personally, I think the concatenation is the better solution. The generic implementation would be
entity shifter is
generic (
REGSIZE : integer := 8);
port(
clk : in str_logic;
Data_in : in std_logic;
Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;
architecture bhv of shifter is
signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
process (clk) begin
if rising_edge(clk) then
shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
end if;
end process;
end bhv;
Data_out <= shift_reg;
Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.
SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
SQLParam.Value = DBNull.Value
Else
SQLParam.Value = p_RetailerID
End If
It seems like there is permission on mobile keypad setting, so the easiest way to do this is:
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
hope this will work
Use Convert.ToDouble(value)
rather than (double)value
. It takes an object
and supports all of the types you asked for! :)
Also, your method is always returning a string
in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value)
)
The ==
operator tests value equivalence. The is
operator tests object identity, and Python tests whether the two are really the same object (i.e., live at the same address in memory).
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a
and b
refers to it. The reason is that Python internally caches and reuses some strings as an optimization. There really is just a string 'banana' in memory, shared by a and b. To trigger the normal behavior, you need to use longer strings:
>>> a = 'a longer banana'
>>> b = 'a longer banana'
>>> a == b, a is b
(True, False)
When you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.
If a
refers to an object and you assign b = a
, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
Maybe simple, economic way (less signs to use)...
$array = [];
We can read in php manual :
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
SELECT
CASE WHEN LEN(listing.OfferText) > 0 THEN listing.OfferText
ELSE COALESCE(Company.OfferText, '') END
AS Offer_Text,
...
In this example, if listing.OfferText
is NULL, the LEN() function should also return NULL, but that's still not > 0.
Update
I've learned some things in the 5 1/2 years since posting this, and do it much differently now:
COALESCE(NULLIF(listing.OfferText,''), Company.OfferText, '')
This is similar to the accepted answer, but it also has a fallback in case Company.OfferText
is also null. None of the other current answers using NULLIF()
also do this.
This error is caused because the function createObjectURL
is deprecated for Google Chrome
I changed this:
video.src=vendorUrl.createObjectURL(stream);
video.play();
to this:
video.srcObject=stream;
video.play();
This worked for me.
As the question is answered. For web develoment. I came so far and found a good explanation about bootsrapping in Laravel doc. Here is the link
In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes.
hope it will help someone who learning web application development.
I did as per sid saying my env after updating is
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<mygmailaddress>
MAIL_PASSWORD=<gmailpassword>
MAIL_ENCRYPTION=tls
this did work without 2 step verification. with 2 step verification enabled it did not work for me.
Plain and simple:
plt.plot(x, y, 'r-', alpha=0.7)
(I know I add nothing new, but the straightforward answer should be visible).
Yes l1
and l2
will point to the same reference, same object.
If you want to create a new ArrayList based on the other ArrayList you do this:
List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");
The result will be l1
will still have 2 elements and l2
will have 3 elements.
This line is missing path
:
<Route name="ideas" handler={CreateIdeaView} />
Should be:
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
Given the following Link
(outdated v1):
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
Up to date as of v4:
const backUrl = '/some/other/value'
// this.props.testvalue === "hello"
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />
and in the withRouter(CreateIdeaView)
components render()
:
console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value
From the link that you posted on the docs, towards the bottom of the page:
Given a route like
<Route name="user" path="/users/:userId"/>
Updated code example with some stubbed query examples:
// import React, {Component, Props, ReactDOM} from 'react';_x000D_
// import {Route, Switch} from 'react-router'; etc etc_x000D_
// this snippet has it all attached to window since its in browser_x000D_
const {_x000D_
BrowserRouter,_x000D_
Switch,_x000D_
Route,_x000D_
Link,_x000D_
NavLink_x000D_
} = ReactRouterDOM;_x000D_
_x000D_
class World extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
console.dir(props); _x000D_
this.state = {_x000D_
fromIdeas: props.match.params.WORLD || 'unknown'_x000D_
}_x000D_
}_x000D_
render() {_x000D_
const { match, location} = this.props;_x000D_
return (_x000D_
<React.Fragment>_x000D_
<h2>{this.state.fromIdeas}</h2>_x000D_
<span>thing: _x000D_
{location.query _x000D_
&& location.query.thing}_x000D_
</span><br/>_x000D_
<span>another1: _x000D_
{location.query _x000D_
&& location.query.another1 _x000D_
|| 'none for 2 or 3'}_x000D_
</span>_x000D_
</React.Fragment>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
class Ideas extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
console.dir(props);_x000D_
this.state = {_x000D_
fromAppItem: props.location.item,_x000D_
fromAppId: props.location.id,_x000D_
nextPage: 'world1',_x000D_
showWorld2: false_x000D_
}_x000D_
}_x000D_
render() {_x000D_
return (_x000D_
<React.Fragment>_x000D_
<li>item: {this.state.fromAppItem.okay}</li>_x000D_
<li>id: {this.state.fromAppId}</li>_x000D_
<li>_x000D_
<Link _x000D_
to={{_x000D_
pathname: `/hello/${this.state.nextPage}`, _x000D_
query:{thing: 'asdf', another1: 'stuff'}_x000D_
}}>_x000D_
Home 1_x000D_
</Link>_x000D_
</li>_x000D_
<li>_x000D_
<button _x000D_
onClick={() => this.setState({_x000D_
nextPage: 'world2',_x000D_
showWorld2: true})}>_x000D_
switch 2_x000D_
</button>_x000D_
</li>_x000D_
{this.state.showWorld2 _x000D_
&& _x000D_
<li>_x000D_
<Link _x000D_
to={{_x000D_
pathname: `/hello/${this.state.nextPage}`, _x000D_
query:{thing: 'fdsa'}}} >_x000D_
Home 2_x000D_
</Link>_x000D_
</li> _x000D_
}_x000D_
<NavLink to="/hello">Home 3</NavLink>_x000D_
</React.Fragment>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
class App extends React.Component {_x000D_
render() {_x000D_
return (_x000D_
<React.Fragment>_x000D_
<Link to={{_x000D_
pathname:'/ideas/:id', _x000D_
id: 222, _x000D_
item: {_x000D_
okay: 123_x000D_
}}}>Ideas</Link>_x000D_
<Switch>_x000D_
<Route exact path='/ideas/:id/' component={Ideas}/>_x000D_
<Route path='/hello/:WORLD?/:thing?' component={World}/>_x000D_
</Switch>_x000D_
</React.Fragment>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render((_x000D_
<BrowserRouter>_x000D_
<App />_x000D_
</BrowserRouter>_x000D_
), document.getElementById('ideas'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.3.1/react-router-dom.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.3.1/react-router.min.js"></script>_x000D_
_x000D_
<div id="ideas"></div>
_x000D_
From the upgrade guide from 1.x to 2.x:
<Link to>
, onEnter, and isActive use location descriptors
<Link to>
can now take a location descriptor in addition to strings. The query and state props are deprecated.// v1.0.x
<Link to="/foo" query={{ the: 'query' }}/>
// v2.0.0
<Link to={{ pathname: '/foo', query: { the: 'query' } }}/>
// Still valid in 2.x
<Link to="/foo"/>
Likewise, redirecting from an onEnter hook now also uses a location descriptor.
// v1.0.x
(nextState, replaceState) => replaceState(null, '/foo') (nextState, replaceState) => replaceState(null, '/foo', { the: 'query' })
// v2.0.0
(nextState, replace) => replace('/foo') (nextState, replace) => replace({ pathname: '/foo', query: { the: 'query' } })
For custom link-like components, the same applies for router.isActive, previously history.isActive.
// v1.0.x
history.isActive(pathname, query, indexOnly)
// v2.0.0
router.isActive({ pathname, query }, indexOnly)
https://github.com/ReactTraining/react-router/pull/3288
The interface is basically still the same as v2, best to look at the CHANGES.md for react-router, as that is where the updates are.
"legacy migration documentation" for posterity
To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:
AllowSameSiteAttribute.cs
public class AllowSameSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.RequestContext.HttpContext.Response;
if(response != null)
{
response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
//Add more headers...
}
base.OnActionExecuting(filterContext);
}
}
HomeController.cs
[AllowSameSite] //For the whole controller
public class UserController : Controller
{
}
or
public class UserController : Controller
{
[AllowSameSite] //For the method
public ActionResult Index()
{
return View();
}
}
Run this following command inside the project
npm install --save @bootsrap@4
and if you get a confirmation like this
+ [email protected]
updated 1 package in 8.245s
It means boostrap 4 is successfully installed. However, in order to use it, you need to update the "styles" array under the angular.json file.
Update it the following way so that bootstrap will be able to override the existing styles
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
To make sure everything is set up correctly, run ng serve > open browser at http://localhost:4200/ or a port you run the angular app > right click > inspect > under the head check the styles if you have bootsrap like shown below
, then you are good to use boostrap.
And let's not forget ActiveState's PDK. It will allow you to compile UI, command line, Windows services and installers.
I highly recommend it, it has served me very well over the years, but it is around 300$ for a licence.
A hex color code is #RRGGBB
RR, GG, BB are hex values ranging from 0-255
Let's call RR XY where X and Y are hex character 0-9A-F, A=10, F=15
The decimal value is X*16+Y
If RR = B7, the decimal for B is 11, so value is 11*16 + 7 = 183
public int[] getRGB(String rgb){
int[] ret = new int[3];
for(int i=0; i<3; i++){
ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
}
return ret;
}
public int hexToInt(char a, char b){
int x = a < 65 ? a-48 : a-55;
int y = b < 65 ? b-48 : b-55;
return x*16+y;
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
[RoutePrefix("File")]
[Route("{action=index}")]
public class FileController : Controller
{
// GET: File
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[Route("Image/{extension?}/{filename}")]
public ActionResult Image(string extension, string filename)
{
var dir = Server.MapPath("/app_data/images");
var path = Path.Combine(dir, filename+"."+ (extension!=null? extension:"jpg"));
// var extension = filename.Substring(0,filename.LastIndexOf("."));
return base.File(path, "image/jpeg");
}
}
}
That should work, but don't kill yourself trying to figure it out. Just use 2 passes.
str = str.replaceAll("(\r\n)", "<br />");
str = str.replaceAll("(\n)", "<br />");
Disclaimer: this is not very efficient.
after searching for a reliable way to detect Async functions or even Promises, i ended up using the following test :
() => fn.constructor.name === 'Promise' || fn.constructor.name === 'AsyncFunction'
PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');
Try this out.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
this would do it excluding exactly 'Music'
cp -a ^'Music' /target
this and that for excluding things like Music?* or *?Music
cp -a ^\*?'complete' /target
cp -a ^'complete'?\* /target
This is what I used for Swift
var date = NSDate()
let currentTime = Int64(date.timeIntervalSince1970 * 1000)
print("Time in milliseconds is \(currentTime)")
used this site to verify accuracy http://currentmillis.com/
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
Use the SqlDataAdapter, this would simplify everything.
//Your code to this point
DataTable dt = new DataTable();
using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
using(var da = new SqlDataAdapter(cmd))
{
da.Fill(dt):
}
}
and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).
Using case
#!/bin/bash
fun1 () {
echo "run function1"
[[ "$@" ]] && echo "options: $@"
}
fun2 () {
echo "run function2"
[[ "$@" ]] && echo "options: $@"
}
case $1 in
fun1) "$@"; exit;;
fun2) "$@"; exit;;
esac
fun1
fun2
This script will run functions fun1 and fun2 but if you start it with option fun1 or fun2 it'll only run given function with args(if provided) and exit. Usage
$ ./test
run function1
run function2
$ ./test fun2 a b c
run function2
options: a b c
Works for me on Google Chrome v5.0.375.127 (I get the alert):
$.get('http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=?&minx=-30&miny=0&maxx=0&maxy=150',
function(json) {
alert(json.photos[1].photoUrl);
});
Also I would recommend you using the $.getJSON()
method instead as the previous doesn't work on IE8 (at least on my machine):
$.getJSON('http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=?&minx=-30&miny=0&maxx=0&maxy=150',
function(json) {
alert(json.photos[1].photoUrl);
});
You may try it online from here.
UPDATE:
Now that you have shown your code I can see the problem with it. You are having both an anonymous function and inline function but both will be called processImages
. That's how jQuery's JSONP support works. Notice how I am defining the callback=?
so that you can use an anonymous function. You may read more about it in the documentation.
Another remark is that you shouldn't call eval. The parameter passed to your anonymous function will already be parsed into JSON by jQuery.
There's no such thing as a "localhost" folder; the word "localhost" is an alias for your local computer. The document root for your apache server, by default, is "Sites" in your home directory.
Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.
e.g. I may have a Vehicle
class. A Car
would derive from a Vehicle
, as would a Motorbike
. I can ask each Vehicle
for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars
and Motorbikes
.
In my code I can often just deal with Vehicles
via common methods go()
, stop()
etc. When I add a new Vehicle type later (e.g. Scooter
) the majority of my code would remain oblivious to this fact, and the implementation of Scooter
alone worries about Scooter
particularities.
Try this Script:
function addclassName(){
setTimeout(function(){
var c = document.querySelectorAll(".modal-backdrop");
for (var i = 0; i < c.length; i++) {
c[i].style.zIndex = 1040 + i * 20 ;
}
var d = document.querySelectorAll(".modal.fade");
for(var i = 0; i<d.length; i++){
d[i].style.zIndex = 1050 + i * 20;
}
}, 10);
}
Add the following in the base.mk file. The following 3rd line is important
-include $(TOP)/defs.mk
CFLAGS=$(DEBUG) -Wall -W -Wwrite-strings
CFLAGS_C=-Wmissing-prototypes
CFLAGS_CXX=-std=c++0x
LDFLAGS=
LIBS=
to avoid the #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options
There's been a lot of answer, but I think I found what is causing it, at least for me. It looks like if you put your computer to sleep (or it falls asleep on its own), when it reopens, it tries to open the the mysql process again. At one point I looked at my activity monitor and I had 5 instances running - killing all of them and then starting mysql works.
This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:
boolean
MySQLDatabase: BIT(1)
SQLiteDatabase: BOOLEAN
H2Database: BOOLEAN
PostgresDatabase: BOOLEAN
UnsupportedDatabase: BOOLEAN
DB2Database: SMALLINT
MSSQLDatabase: [bit]
OracleDatabase: NUMBER(1)
HsqlDatabase: BOOLEAN
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: BOOLEAN
SybaseDatabase: BIT
SybaseASADatabase: BIT
tinyint
MySQLDatabase: TINYINT
SQLiteDatabase: TINYINT
H2Database: TINYINT
PostgresDatabase: SMALLINT
UnsupportedDatabase: TINYINT
DB2Database: SMALLINT
MSSQLDatabase: [tinyint]
OracleDatabase: NUMBER(3)
HsqlDatabase: TINYINT
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: TINYINT
SybaseDatabase: TINYINT
SybaseASADatabase: TINYINT
int
MySQLDatabase: INT
SQLiteDatabase: INTEGER
H2Database: INT
PostgresDatabase: INT
UnsupportedDatabase: INT
DB2Database: INTEGER
MSSQLDatabase: [int]
OracleDatabase: INTEGER
HsqlDatabase: INT
FirebirdDatabase: INT
DerbyDatabase: INTEGER
InformixDatabase: INT
SybaseDatabase: INT
SybaseASADatabase: INT
mediumint
MySQLDatabase: MEDIUMINT
SQLiteDatabase: MEDIUMINT
H2Database: MEDIUMINT
PostgresDatabase: MEDIUMINT
UnsupportedDatabase: MEDIUMINT
DB2Database: MEDIUMINT
MSSQLDatabase: [int]
OracleDatabase: MEDIUMINT
HsqlDatabase: MEDIUMINT
FirebirdDatabase: MEDIUMINT
DerbyDatabase: MEDIUMINT
InformixDatabase: MEDIUMINT
SybaseDatabase: MEDIUMINT
SybaseASADatabase: MEDIUMINT
bigint
MySQLDatabase: BIGINT
SQLiteDatabase: BIGINT
H2Database: BIGINT
PostgresDatabase: BIGINT
UnsupportedDatabase: BIGINT
DB2Database: BIGINT
MSSQLDatabase: [bigint]
OracleDatabase: NUMBER(38, 0)
HsqlDatabase: BIGINT
FirebirdDatabase: BIGINT
DerbyDatabase: BIGINT
InformixDatabase: INT8
SybaseDatabase: BIGINT
SybaseASADatabase: BIGINT
float
MySQLDatabase: FLOAT
SQLiteDatabase: FLOAT
H2Database: FLOAT
PostgresDatabase: FLOAT
UnsupportedDatabase: FLOAT
DB2Database: FLOAT
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT
HsqlDatabase: FLOAT
FirebirdDatabase: FLOAT
DerbyDatabase: FLOAT
InformixDatabase: FLOAT
SybaseDatabase: FLOAT
SybaseASADatabase: FLOAT
double
MySQLDatabase: DOUBLE
SQLiteDatabase: DOUBLE
H2Database: DOUBLE
PostgresDatabase: DOUBLE PRECISION
UnsupportedDatabase: DOUBLE
DB2Database: DOUBLE
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT(24)
HsqlDatabase: DOUBLE
FirebirdDatabase: DOUBLE PRECISION
DerbyDatabase: DOUBLE
InformixDatabase: DOUBLE PRECISION
SybaseDatabase: DOUBLE
SybaseASADatabase: DOUBLE
decimal
MySQLDatabase: DECIMAL
SQLiteDatabase: DECIMAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL
MSSQLDatabase: [decimal](18, 0)
OracleDatabase: DECIMAL
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL
DerbyDatabase: DECIMAL
InformixDatabase: DECIMAL
SybaseDatabase: DECIMAL
SybaseASADatabase: DECIMAL
number
MySQLDatabase: numeric
SQLiteDatabase: NUMBER
H2Database: NUMBER
PostgresDatabase: numeric
UnsupportedDatabase: NUMBER
DB2Database: numeric
MSSQLDatabase: [numeric](18, 0)
OracleDatabase: NUMBER
HsqlDatabase: numeric
FirebirdDatabase: numeric
DerbyDatabase: numeric
InformixDatabase: numeric
SybaseDatabase: numeric
SybaseASADatabase: numeric
blob
MySQLDatabase: LONGBLOB
SQLiteDatabase: BLOB
H2Database: BLOB
PostgresDatabase: BYTEA
UnsupportedDatabase: BLOB
DB2Database: BLOB
MSSQLDatabase: [varbinary](MAX)
OracleDatabase: BLOB
HsqlDatabase: BLOB
FirebirdDatabase: BLOB
DerbyDatabase: BLOB
InformixDatabase: BLOB
SybaseDatabase: IMAGE
SybaseASADatabase: LONG BINARY
function
MySQLDatabase: FUNCTION
SQLiteDatabase: FUNCTION
H2Database: FUNCTION
PostgresDatabase: FUNCTION
UnsupportedDatabase: FUNCTION
DB2Database: FUNCTION
MSSQLDatabase: [function]
OracleDatabase: FUNCTION
HsqlDatabase: FUNCTION
FirebirdDatabase: FUNCTION
DerbyDatabase: FUNCTION
InformixDatabase: FUNCTION
SybaseDatabase: FUNCTION
SybaseASADatabase: FUNCTION
UNKNOWN
MySQLDatabase: UNKNOWN
SQLiteDatabase: UNKNOWN
H2Database: UNKNOWN
PostgresDatabase: UNKNOWN
UnsupportedDatabase: UNKNOWN
DB2Database: UNKNOWN
MSSQLDatabase: [UNKNOWN]
OracleDatabase: UNKNOWN
HsqlDatabase: UNKNOWN
FirebirdDatabase: UNKNOWN
DerbyDatabase: UNKNOWN
InformixDatabase: UNKNOWN
SybaseDatabase: UNKNOWN
SybaseASADatabase: UNKNOWN
datetime
MySQLDatabase: datetime
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: datetime
DB2Database: TIMESTAMP
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: datetime
time
MySQLDatabase: time
SQLiteDatabase: time
H2Database: time
PostgresDatabase: TIME WITHOUT TIME ZONE
UnsupportedDatabase: time
DB2Database: time
MSSQLDatabase: [time](7)
OracleDatabase: DATE
HsqlDatabase: time
FirebirdDatabase: time
DerbyDatabase: time
InformixDatabase: INTERVAL HOUR TO FRACTION(5)
SybaseDatabase: time
SybaseASADatabase: time
timestamp
MySQLDatabase: timestamp
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: timestamp
DB2Database: timestamp
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: timestamp
date
MySQLDatabase: date
SQLiteDatabase: date
H2Database: date
PostgresDatabase: date
UnsupportedDatabase: date
DB2Database: date
MSSQLDatabase: [date]
OracleDatabase: date
HsqlDatabase: date
FirebirdDatabase: date
DerbyDatabase: date
InformixDatabase: date
SybaseDatabase: date
SybaseASADatabase: date
char
MySQLDatabase: CHAR
SQLiteDatabase: CHAR
H2Database: CHAR
PostgresDatabase: CHAR
UnsupportedDatabase: CHAR
DB2Database: CHAR
MSSQLDatabase: [char](1)
OracleDatabase: CHAR
HsqlDatabase: CHAR
FirebirdDatabase: CHAR
DerbyDatabase: CHAR
InformixDatabase: CHAR
SybaseDatabase: CHAR
SybaseASADatabase: CHAR
varchar
MySQLDatabase: VARCHAR
SQLiteDatabase: VARCHAR
H2Database: VARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: VARCHAR
DB2Database: VARCHAR
MSSQLDatabase: [varchar](1)
OracleDatabase: VARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: VARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: VARCHAR
SybaseDatabase: VARCHAR
SybaseASADatabase: VARCHAR
nchar
MySQLDatabase: NCHAR
SQLiteDatabase: NCHAR
H2Database: NCHAR
PostgresDatabase: NCHAR
UnsupportedDatabase: NCHAR
DB2Database: NCHAR
MSSQLDatabase: [nchar](1)
OracleDatabase: NCHAR
HsqlDatabase: CHAR
FirebirdDatabase: NCHAR
DerbyDatabase: NCHAR
InformixDatabase: NCHAR
SybaseDatabase: NCHAR
SybaseASADatabase: NCHAR
nvarchar
MySQLDatabase: NVARCHAR
SQLiteDatabase: NVARCHAR
H2Database: NVARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: NVARCHAR
DB2Database: NVARCHAR
MSSQLDatabase: [nvarchar](1)
OracleDatabase: NVARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: NVARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: NVARCHAR
SybaseDatabase: NVARCHAR
SybaseASADatabase: NVARCHAR
clob
MySQLDatabase: LONGTEXT
SQLiteDatabase: TEXT
H2Database: CLOB
PostgresDatabase: TEXT
UnsupportedDatabase: CLOB
DB2Database: CLOB
MSSQLDatabase: [varchar](MAX)
OracleDatabase: CLOB
HsqlDatabase: CLOB
FirebirdDatabase: BLOB SUB_TYPE TEXT
DerbyDatabase: CLOB
InformixDatabase: CLOB
SybaseDatabase: TEXT
SybaseASADatabase: LONG VARCHAR
currency
MySQLDatabase: DECIMAL
SQLiteDatabase: REAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL(19, 4)
MSSQLDatabase: [money]
OracleDatabase: NUMBER(15, 2)
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL(18, 4)
DerbyDatabase: DECIMAL
InformixDatabase: MONEY
SybaseDatabase: MONEY
SybaseASADatabase: MONEY
uuid
MySQLDatabase: char(36)
SQLiteDatabase: TEXT
H2Database: UUID
PostgresDatabase: UUID
UnsupportedDatabase: char(36)
DB2Database: char(36)
MSSQLDatabase: [uniqueidentifier]
OracleDatabase: RAW(16)
HsqlDatabase: char(36)
FirebirdDatabase: char(36)
DerbyDatabase: char(36)
InformixDatabase: char(36)
SybaseDatabase: UNIQUEIDENTIFIER
SybaseASADatabase: UNIQUEIDENTIFIER
For reference, this is the groovy script I've used to generate this output:
@Grab('org.liquibase:liquibase-core:3.5.1')
import liquibase.database.core.*
import liquibase.datatype.core.*
def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
datatypes.each {
def datatype = it.newInstance()
datatype.finishInitialization("")
println datatype.name
databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
println ''
}
/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'
This will list down the exact ip address for the machine
The problem may be that ssh is trying to connect to all the different IPs that www.google.com
resolves to. For example on my machine:
# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out
If I run it with a specific IP, it returns much faster.
EDIT: I've timed it (with time
) and the results are:
Standard CSS3 rotate should work in IE9, but I believe you need to give it a vendor prefix, like so:
-ms-transform: rotate(10deg);
It is possible that it may not work in the beta version; if not, try downloading the current preview version (preview 7), which is a later revision that the beta. I don't have the beta version to test against, so I can't confirm whether it was in that version or not. The final release version is definitely slated to support it.
I can also confirm that the IE-specific filter
property has been dropped in IE9.
[Edit]
People have asked for some further documentation. As they say, this is quite limited, but I did find this page: http://css3please.com/ which is useful for testing various CSS3 features in all browsers.
But testing the rotate feature on this page in IE9 preview caused it to crash fairly spectacularly.
However I have done some independant tests using -ms-transform:rotate()
in IE9 in my own test pages, and it is working fine. So my conclusion is that the feature is implemented, but has got some bugs, possibly related to setting it dynamically.
Another useful reference point for which features are implemented in which browsers is www.canIuse.com -- see http://caniuse.com/#search=rotation
[EDIT]
Reviving this old answer because I recently found out about a hack called CSS Sandpaper which is relevant to the question and may make things easier.
The hack implements support for the standard CSS transform
for for old versions of IE. So now you can add the following to your CSS:
-sand-transform: rotate(10deg);
...and have it work in IE 6/7/8, without having to use the filter
syntax. (of course it still uses the filter syntax behind the scenes, but this makes it a lot easier to manage because it's using similar syntax to other browsers)
Try this:
CREATE TABLE #t(
[name] varchar NULL,
[val] [int] NULL,
[ID] [int] NULL
) ON [PRIMARY]
insert into #t (id,name,val) values
(1,'A',10), (2,'B',20), (3,'C',30)
select t1.id, t1.val, SUM(t2.val) as cumSum
from #t t1 inner join #t t2 on t1.id >= t2.id
group by t1.id, t1.val order by t1.id
You sure can. Create an HTML page with the form in it that will contain the necessary components from the login.aspx page (i.e. username, etc), and make sure they have the same IDs. For you action, make sure it's a post.
You might have to do some code on the login.aspx page in the Page_Load function to read the form (in the Request.Form object) and call the appropriate functions to log the user in, but other than that, you should have access to the form, and can do what you want with it.
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
Personally, I use ... | Out-Null
because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null
and [void] ...
. $null = ...
is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null
and ... > $null
come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null
), compared to putting $null =
or [void]
before the expression to determine what happens after executing it.
Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help
command or your favorite search engine to try to find out what Out-Null
does. You get a useful result immediately, right? Now try to do the same with [void]
and $null =
. Not so easy, is it?
Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void]
, $null =
, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*
* I am presuming that Out-Null
is clear and well-known, which I don't know to be $true
. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.
Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen.
This causes every flex container to move to a new line on the screen.
Display:inline-flex apply flex layout to the flex items or children as well as to the container itself. As a result the container behaves as an inline flex element just like the children do and thus takes up the width required by its items/children only and not the entire width of the screen.
This causes two or more flex containers one after another, displayed as inline-flex, align themselves side by side on the screen until the whole width of the screen is taken.
For Ubuntu:
sudo apt-get install ca-certificates
Hit this problem trying to curl things as ROOT inside of Dockerfile
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:
<table align='center' style='text-align:center'>
<tr>
<td align='center' style='text-align:center'>
<!-- AMAZING CONTENT! -->
</td>
</tr>
</table>
I only listed some of the key things that resolved my Microsoft email issues.
Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/
It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.
this is supported from version hive 0.14
INSERT INTO TABLE pd_temp(dept,make,cost,id,asmb_city,asmb_ct,retail) VALUES('production','thailand',10,99202,'northcarolina','usa',20)
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.
In case anyone wishes to do this with bootstrap, version 4 offers the following:
The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
Where property is one of:
m - for classes that set margin
p - for classes that set padding
Where sides is one of:
t - for classes that set margin-top or padding-top
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
blank - for classes that set a margin or padding on all 4 sides of the element
Where size is one of:
0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
auto - for classes that set the margin to auto
For example:
.mt-0 {
margin-top: 0 !important;
}
.ml-1 {
margin-left: ($spacer * .25) !important;
}
.px-2 {
padding-left: ($spacer * .5) !important;
padding-right: ($spacer * .5) !important;
}
.p-3 {
padding: $spacer !important;
}
Reference: https://getbootstrap.com/docs/4.0/utilities/spacing/
std::queue
is a container adaptor, and you can specify the container used (it defaults to use a deque
). If you need functionality beyond that in the adaptor then just use a deque
or another container directly.
There's a difference between the raw queries and standard selects (between the DB::raw
and DB::select
methods).
You can do what you want using a DB::select
and simply dropping in the ?
placeholder much like you do with prepared statements (it's actually what it's doing).
A small example:
$results = DB::select('SELECT * FROM user WHERE username=?', ['jason']);
The second parameter is an array of values that will be used to replace the placeholders in the query from left to right.
If you want to use the REST end point,
$friends = $facebook->api(array('method' => 'friends.get'));
else if you are using the graph api, then use,
$friends = $facebook->api('/me/friends');
Here are a couple dplyr
options:
library(dplyr)
# all columns:
df %>%
mutate_all(~na_if(., ''))
# specific column types:
df %>%
mutate_if(is.factor, ~na_if(., ''))
# specific columns:
df %>%
mutate_at(vars(A, B), ~na_if(., ''))
# or:
df %>%
mutate(A = replace(A, A == '', NA))
# replace can be used if you want something other than NA:
df %>%
mutate(A = as.character(A)) %>%
mutate(A = replace(A, A == '', 'used to be empty'))
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
@basarat's answer was great. Here is simplified but a little bit extended example you can use:
export type TMyEnumType = 'value1'|'value2';
export class MyEnumType {
static VALUE1: TMyEnumType = 'value1';
static VALUE2: TMyEnumType = 'value2';
}
console.log(MyEnumType.VALUE1); // 'value1'
const variable = MyEnumType.VALUE2; // it has the string value 'value2'
switch (variable) {
case MyEnumType.VALUE1:
// code...
case MyEnumType.VALUE2:
// code...
}
Also, to note - the Active Record Class also has a $this->db->where_in()
method.
I agree withe the other answers regarding the correct way to loop through the files. However the OP asked:
The code above doesn't work, do you know why?
Yes!
An excellent article What is the difference between test, [ and [[ ?] explains in detail that among other differences, you cannot use expression matching
or pattern matching
within the test
command (which is shorthand for [
)
Feature new test [[ old test [ Example Pattern matching = (or ==) (not available) [[ $name = a* ]] || echo "name does not start with an 'a': $name" Regular Expression =~ (not available) [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!" matching
So this is the reason your script fails. If the OP is interested in an answer with the [[
syntax (which has the disadvantage of not being supported on as many platforms as the [
command), I would be happy to edit my answer to include it.
EDIT: Any protips for how to format the data in the answer as a table would be helpful!
I use the following code as a simple sliding window that uses generators to drastically increase readability. Its speed has so far been sufficient for use in bioinformatics sequence analysis in my experience.
I include it here because I didn't see this method used yet. Again, I make no claims about its compared performance.
def slidingWindow(sequence,winSize,step=1):
"""Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be sliceable."""
# Verify the inputs
if not ((type(winSize) == type(0)) and (type(step) == type(0))):
raise Exception("**ERROR** type(winSize) and type(step) must be int.")
if step > winSize:
raise Exception("**ERROR** step must not be larger than winSize.")
if winSize > len(sequence):
raise Exception("**ERROR** winSize must not be larger than sequence length.")
# Pre-compute number of chunks to emit
numOfChunks = ((len(sequence)-winSize)/step)+1
# Do the work
for i in range(0,numOfChunks*step,step):
yield sequence[i:i+winSize]
In Access, you will probably find a Join is quicker unless your tables are very small:
SELECT DISTINCT Table1.Column1
FROM Table1
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1
WHERE Table2.Column1 Is Null
This will exclude from the list all records with a match in Table2.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
If you want to make the first item unselectable, try this:
DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");
As explained in below code: Execute below queries and verify yourself.
CREATE TABLE `table_name` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`tele` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Insert a record:
INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_name`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Nazir | Kolkata | 033 |
+----+--------+-----------+------+
Now, try to insert the same record again:
INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Nazir', 'Kolkata', '033') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_name WHERE name = 'Nazir'
) LIMIT 1;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Nazir | Kolkata | 033 |
+----+--------+-----------+------+
Insert a different record:
INSERT INTO table_name (name, address, tele)
SELECT * FROM (SELECT 'Santosh', 'Kestopur', '044') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_name WHERE name = 'Santosh'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_name`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Nazir | Kolkata | 033 |
| 2 | Santosh| Kestopur | 044 |
+----+--------+-----------+------+
Since I wrote my prior answer, I have formulated a new definition of the declarative property which is quoted below. I have also defined imperative programming as the dual property.
This definition is superior to the one I provided in my prior answer, because it is succinct and it is more general. But it may be more difficult to grok, because the implication of the incompleteness theorems applicable to programming and life in general are difficult for humans to wrap their mind around.
The quoted explanation of the definition discusses the role pure functional programming plays in declarative programming.
All exotic types of programming fit into the following taxonomy of declarative versus imperative, since the following definition claims they are duals.
Declarative vs. Imperative
The declarative property is weird, obtuse, and difficult to capture in a technically precise definition that remains general and not ambiguous, because it is a naive notion that we can declare the meaning (a.k.a semantics) of the program without incurring unintended side effects. There is an inherent tension between expression of meaning and avoidance of unintended effects, and this tension actually derives from the incompleteness theorems of programming and our universe.
It is oversimplification, technically imprecise, and often ambiguous to define declarative as “what to do” and imperative as “how to do”. An ambiguous case is the “what” is the “how” in a program that outputs a program— a compiler.
Evidently the unbounded recursion that makes a language Turing complete, is also analogously in the semantics— not only in the syntactical structure of evaluation (a.k.a. operational semantics). This is logically an example analogous to Gödel's theorem— “any complete system of axioms is also inconsistent”. Ponder the contradictory weirdness of that quote! It is also an example that demonstrates how the expression of semantics does not have a provable bound, thus we can't prove2 that a program (and analogously its semantics) halt a.k.a. the Halting theorem.
The incompleteness theorems derive from the fundamental nature of our universe, which as stated in the Second Law of Thermodynamics is “the entropy (a.k.a. the # of independent possibilities) is trending to maximum forever”. The coding and design of a program is never finished— it's alive!— because it attempts to address a real world need, and the semantics of the real world are always changing and trending to more possibilities. Humans never stop discovering new things (including errors in programs ;-).
To precisely and technically capture this aforementioned desired notion within this weird universe that has no edge (ponder that! there is no “outside” of our universe), requires a terse but deceptively-not-simple definition which will sound incorrect until it is explained deeply.
Definition:
The declarative property is where there can exist only one possible set of statements that can express each specific modular semantic.
The imperative property3 is the dual, where semantics are inconsistent under composition and/or can be expressed with variations of sets of statements.
This definition of declarative is distinctively local in semantic scope, meaning that it requires that a modular semantic maintain its consistent meaning regardless where and how it's instantiated and employed in global scope. Thus each declarative modular semantic should be intrinsically orthogonal to all possible others— and not an impossible (due to incompleteness theorems) global algorithm or model for witnessing consistency, which is also the point of “More Is Not Always Better” by Robert Harper, Professor of Computer Science at Carnegie Mellon University, one of the designers of Standard ML.
Examples of these modular declarative semantics include category theory functors e.g. the
Applicative
, nominal typing, namespaces, named fields, and w.r.t. to operational level of semantics then pure functional programming.Thus well designed declarative languages can more clearly express meaning, albeit with some loss of generality in what can be expressed, yet a gain in what can be expressed with intrinsic consistency.
An example of the aforementioned definition is the set of formulas in the cells of a spreadsheet program— which are not expected to give the same meaning when moved to different column and row cells, i.e. cell identifiers changed. The cell identifiers are part of and not superfluous to the intended meaning. So each spreadsheet result is unique w.r.t. to the cell identifiers in a set of formulas. The consistent modular semantic in this case is use of cell identifiers as the input and output of pure functions for cells formulas (see below).
Hyper Text Markup Language a.k.a. HTML— the language for static web pages— is an example of a highly (but not perfectly3) declarative language that (at least before HTML 5) had no capability to express dynamic behavior. HTML is perhaps the easiest language to learn. For dynamic behavior, an imperative scripting language such as JavaScript was usually combined with HTML. HTML without JavaScript fits the declarative definition because each nominal type (i.e. the tags) maintains its consistent meaning under composition within the rules of the syntax.
A competing definition for declarative is the commutative and idempotent properties of the semantic statements, i.e. that statements can be reordered and duplicated without changing the meaning. For example, statements assigning values to named fields can be reordered and duplicated without changed the meaning of the program, if those names are modular w.r.t. to any implied order. Names sometimes imply an order, e.g. cell identifiers include their column and row position— moving a total on spreadsheet changes its meaning. Otherwise, these properties implicitly require global consistency of semantics. It is generally impossible to design the semantics of statements so they remain consistent if randomly ordered or duplicated, because order and duplication are intrinsic to semantics. For example, the statements “Foo exists” (or construction) and “Foo does not exist” (and destruction). If one considers random inconsistency endemical of the intended semantics, then one accepts this definition as general enough for the declarative property. In essence this definition is vacuous as a generalized definition because it attempts to make consistency orthogonal to semantics, i.e. to defy the fact that the universe of semantics is dynamically unbounded and can't be captured in a global coherence paradigm.
Requiring the commutative and idempotent properties for the (structural evaluation order of the) lower-level operational semantics converts operational semantics to a declarative localized modular semantic, e.g. pure functional programming (including recursion instead of imperative loops). Then the operational order of the implementation details do not impact (i.e. spread globally into) the consistency of the higher-level semantics. For example, the order of evaluation of (and theoretically also the duplication of) the spreadsheet formulas doesn't matter because the outputs are not copied to the inputs until after all outputs have been computed, i.e. analogous to pure functions.
C, Java, C++, C#, PHP, and JavaScript aren't particularly declarative. Copute's syntax and Python's syntax are more declaratively coupled to intended results, i.e. consistent syntactical semantics that eliminate the extraneous so one can readily comprehend code after they've forgotten it. Copute and Haskell enforce determinism of the operational semantics and encourage “don't repeat yourself” (DRY), because they only allow the pure functional paradigm.
2 Even where we can prove the semantics of a program, e.g. with the language Coq, this is limited to the semantics that are expressed in the typing, and typing can never capture all of the semantics of a program— not even for languages that are not Turing complete, e.g. with HTML+CSS it is possible to express inconsistent combinations which thus have undefined semantics.
3 Many explanations incorrectly claim that only imperative programming has syntactically ordered statements. I clarified this confusion between imperative and functional programming. For example, the order of HTML statements does not reduce the consistency of their meaning.
Edit: I posted the following comment to Robert Harper's blog:
in functional programming ... the range of variation of a variable is a type
Depending on how one distinguishes functional from imperative programming, your ‘assignable’ in an imperative program also may have a type placing a bound on its variability.
The only non-muddled definition I currently appreciate for functional programming is a) functions as first-class objects and types, b) preference for recursion over loops, and/or c) pure functions— i.e. those functions which do not impact the desired semantics of the program when memoized (thus perfectly pure functional programming doesn't exist in a general purpose denotational semantics due to impacts of operational semantics, e.g. memory allocation).
The idempotent property of a pure function means the function call on its variables can be substituted by its value, which is not generally the case for the arguments of an imperative procedure. Pure functions seem to be declarative w.r.t. to the uncomposed state transitions between the input and result types.
But the composition of pure functions does not maintain any such consistency, because it is possible to model a side-effect (global state) imperative process in a pure functional programming language, e.g. Haskell's IOMonad and moreover it is entirely impossible to prevent doing such in any Turing complete pure functional programming language.
As I wrote in 2012 which seems to the similar consensus of comments in your recent blog, that declarative programming is an attempt to capture the notion that the intended semantics are never opaque. Examples of opaque semantics are dependence on order, dependence on erasure of higher-level semantics at the operational semantics layer (e.g. casts are not conversions and reified generics limit higher-level semantics), and dependence on variable values which can not be checked (proved correct) by the programming language.
Thus I have concluded that only non-Turing complete languages can be declarative.
Thus one unambiguous and distinct attribute of a declarative language could be that its output can be proven to obey some enumerable set of generative rules. For example, for any specific HTML program (ignoring differences in the ways interpreters diverge) that is not scripted (i.e. is not Turing complete) then its output variability can be enumerable. Or more succinctly an HTML program is a pure function of its variability. Ditto a spreadsheet program is a pure function of its input variables.
So it seems to me that declarative languages are the antithesis of unbounded recursion, i.e. per Gödel's second incompleteness theorem self-referential theorems can't be proven.
Lesie Lamport wrote a fairytale about how Euclid might have worked around Gödel's incompleteness theorems applied to math proofs in the programming language context by to congruence between types and logic (Curry-Howard correspondence, etc).
This Works Flawless....
In terminal Run both commands next to each other
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
How about this?
var http = require('http'),
fs = require('fs'),
options;
options = {
host: 'www.google.com' ,
port: 80,
path: '/images/logos/ps_logo2.png'
}
var request = http.get(options, function(res){
//var imagedata = ''
//res.setEncoding('binary')
var chunks = [];
res.on('data', function(chunk){
//imagedata += chunk
chunks.push(chunk)
})
res.on('end', function(){
//fs.writeFile('logo.png', imagedata, 'binary', function(err){
var buffer = Buffer.concat(chunks)
fs.writeFile('logo.png', buffer, function(err){
if (err) throw err
console.log('File saved.')
})
})
With a recent nightly, you can do this:
let my_int = from_str::<int>(&*my_string);
What's happening here is that String
can now be dereferenced into a str
. However, the function wants an &str
, so we have to borrow again. For reference, I believe this particular pattern (&*
) is called "cross-borrowing".
Check your error log file and then use the tail command as:
tail -200f /var/log/redis_6379.log
or
tail -200f /var/log/redis.log
According to your error file name..
num1
and num2
are Long objects. You should be using equals()
to compare them. ==
comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.
if (num1.equals(num1))
{
//code
}
To get the convenient list of tables on the left panel below each database you have to click the tiny icon on the top right of the left panel. At least in MySQL Workbench 6.3 CE on Win7 this worked to get the full list of tables.
Sadly this icon not even has a mouseover title attribute, so it was a lucky guess that I found it.
//
can be considered an alias to math.floor() for divisions with return value of type float
. It operates as no-op
for divisions with return value of type int
.
import math
# let's examine `float` returns
# -------------------------------------
# divide
>>> 1.0 / 2
0.5
# divide and round down
>>> math.floor(1.0/2)
0.0
# divide and round down
>>> 1.0 // 2
0.0
# now let's examine `integer` returns
# -------------------------------------
>>> 1/2
0
>>> 1//2
0
str = str.replace(/[^\w\s]|_/g, "")
.replace(/\s+/g, " ");
Removes everything except alphanumeric characters and whitespace, then collapses multiple adjacent characters to single spaces.
Detailed explanation:
\w
is any digit, letter, or underscore.\s
is any whitespace.[^\w\s]
is anything that's not a digit, letter, whitespace, or underscore.[^\w\s]|_
is the same as #3 except with the underscores added back in.You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString()
value is automatically set as "[object Object]"
.
I'm not sure what jQuery api you're looking at, but you should only have to specify id
.
$('#thumb').removeAttr('id');
Do you mean why doesn't the language support multithreading or why don't JavaScript engines in browsers support multithreading?
The answer to the first question is that JavaScript in the browser is meant to be run in a sandbox and in a machine/OS-independent way, to add multithreading support would complicate the language and tie the language too closely to the OS.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
I had this issue because my website did not have a certificate bound to the SSL port. I thought I'd mention it because I didn't find this answer anywhere in the googleweb and it took me hours to figure it out. Nothing showed up in the event viewer, which was totally awesome for diagnosing it. Hope this saves someone else the pain.
you can filter the waypoints by passing the user to the form init
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(
choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
)
from your view while initiating the form pass the user
form = waypointForm(user)
in case of model form
class waypointForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ModelChoiceField(
queryset=Waypoint.objects.filter(user=user)
)
class Meta:
model = Waypoint
You have to deal with the auto-boxing of java.
Let's take the code
public class test { public static void main(String [ ] args) { int i = 3; Object o = i; return; } }You get the class test.class and javap -c test let's you inspect the generated bytecode.
Compiled from "test.java" public class test extends java.lang.Object{ public test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: returnAs you can see the java compiler addedpublic static void main(java.lang.String[]); Code: 0: iconst_3 1: istore_1 2: iload_1 3: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 6: astore_2 7: return
}
invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;to create a new Integer from your int and then stores that new Object in o via astore_2
You can also capitalize the first letter of the match using \I1
and \I2
etc instead of $1
and $2
.
I ran into an issue today with @Pumbaa80's code. I'm trying to apply JSON syntax highlighting to data that I'm rendering in a Mithril view, so I need to create DOM nodes for everything in the JSON.stringify
output.
I split the really long regex into its component parts as well.
render_json = (data) ->
# wraps JSON data in span elements so that syntax highlighting may be
# applied. Should be placed in a `whitespace: pre` context
if typeof(data) isnt 'string'
data = JSON.stringify(data, undefined, 2)
unicode = /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?/
keyword = /\b(true|false|null)\b/
whitespace = /\s+/
punctuation = /[,.}{\[\]]/
number = /-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/
syntax = '(' + [unicode, keyword, whitespace,
punctuation, number].map((r) -> r.source).join('|') + ')'
parser = new RegExp(syntax, 'g')
nodes = data.match(parser) ? []
select_class = (node) ->
if punctuation.test(node)
return 'punctuation'
if /^\s+$/.test(node)
return 'whitespace'
if /^\"/.test(node)
if /:$/.test(node)
return 'key'
return 'string'
if /true|false/.test(node)
return 'boolean'
if /null/.test(node)
return 'null'
return 'number'
return nodes.map (node) ->
cls = select_class(node)
return Mithril('span', {class: cls}, node)
Code in context on Github here
I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:
eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"
Click on Browse button and provide path.
Even though question is answered, thought to share in case somebody else is facing similar issue.
Cheers !
The parser is having trouble concatenating your string. Try this:
write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])
Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
Use the number_format()
function to change how a number is displayed. It will return a string
, the type of the original variable is unaffected.
I believe that Notepad++ has this feature.
Edit (for newer versions)
Install the "XML Tools" plugin (Menu Plugins, Plugin Manager)
Then run: Menu Plugins, Xml Tools, Pretty Print (XML only - with line breaks)
Original answer (for older versions of Notepad++)
Notepad++ menu: TextFX -> HTML Tidy -> Tidy: Reindent XML
This feature however wraps XMLs and that makes it look 'unclean'. To have no wrap,
C:\Program Files\Notepad++\plugins\Config\tidy\TIDYCFG.INI
, [Tidy: Reindent XML]
and add wrap:0
so that it looks like this: [Tidy: Reindent XML] input-xml: yes indent:yes wrap:0
I think the best way to do this as of 2018 is to use flexbox.
.text {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
align-items: flex-start;_x000D_
}_x000D_
/* same as original below */_x000D_
.text span {_x000D_
background:rgba(165, 220, 79, 0.8);_x000D_
display:inline-block;_x000D_
padding:7px 10px;_x000D_
color:white;_x000D_
}_x000D_
.fullscreen .large { font-size:80px }
_x000D_
<div class="fullscreen">_x000D_
<p class="text">_x000D_
<span class="medium">We</span> _x000D_
<span class="large">build</span> _x000D_
<span class="medium">the</span> _x000D_
<span class="large">Internet</span>_x000D_
</p>_x000D_
</div>
_x000D_
You don't have sufficient permissions to write to the root directory. See the leading slash on the filename?
NullPointerException
in some cases!
Without criteria.setProjection(Projections.distinct(Projections.property("id")))
all query goes well!
This solution is bad!
Another way is use SQLQuery. In my case following code works fine:
List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();
Distinction is done in data base! In opposite to:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
where distinction is done in memory, after load entities!
Perhaps replace
is what you are looking for:
> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1
Or, if you don't have x
(any specific reason why not?):
replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)
Many people are familiar with gsub
, so you can also try either of the following:
as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
After reading the comments, perhaps with
is an option:
with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))
This can be done with lodash _.tail
and _.dropRight
:
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
console.log(_.dropRight(_.tail(fruits)));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
You cannot cast an int to a char* to get a string. Try this:
std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();
You might want to start with scapy.
The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.
See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html
values timestampdiff (16, char(
timestamp(current timestamp + 1 year + 2 month - 3 day)-
timestamp(current timestamp)))
1
=
422
values timestampdiff (16, char(
timestamp('2012-03-08-00.00.00')-
timestamp('2011-12-08-00.00.00')))
1
=
90
---------- EDIT BY galador
SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'
EDIT
As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:
SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00
WHERE CHSTAT = '05';
Satisfies all your requirements if you use the trick told below
/^(\+\d{1,3}[- ]?)?\d{10}$/
^
start of line+
followed by \d+
followed by a
or -
which are optional.0
s do not follow.\d+
10 times.DEMO Added m
ultiline flag in demo to check for all cases
P.S. You really need to specify which language you use so as to use an if
condition something like below:
// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times
if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )
Use psycopg2-binary instead of psycopg2.
pip install psycopg2-binary
Or you will get the warning below:
UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi.
Reference: Psycopg 2.7.4 released | Psycopg
You want to become familiar with parseInt()
and toString()
.
And useful in your toolkit will be to look at a variable to find out what type it is—typeof
:
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
There are couple of way which can be used.
const stations = [
{call:'station one',frequency:'000'},
{call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)
Solution 1
<p>{callList.join(', ')}</p>
Solution 2
<ol>
{ callList && callList.map(item => <li>{item}</li>) }
</ol>
Of course there are other ways also available.
try :%s/\^M//
At least this worked for me.
I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.
The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument
You are trying to insert data that is larger than allowed for the column logo
.
Use following data types as per your need
TINYBLOB : maximum length of 255 bytes
BLOB : maximum length of 65,535 bytes
MEDIUMBLOB : maximum length of 16,777,215 bytes
LONGBLOB : maximum length of 4,294,967,295 bytes
Use LONGBLOB
to avoid this exception.
You could possibly use a LINQ query to do this:
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
Here is a simple filter pipe for array of objects that contain attributes with string values (ES6)
filter-array-pipe.js
import {Pipe} from 'angular2/core';
// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
Your component
myobjComponent.js
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';
@Component({
templateUrl: 'myobj.list.html',
providers: [HTTP_PROVIDERS],
pipes: [FilterArrayPipe]
})
export class MyObjList {
static get parameters() {
return [[Http]];
}
constructor(_http) {
_http.get('/api/myobj')
.map(res => res.json())
.subscribe(
data => this.myobjs = data,
err => this.logError(err))
);
}
resetQuery(){
this.query = '';
}
}
In your template
myobj.list.html
<input type="text" [(ngModel)]="query" placeholder="... filter" >
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>
It seems that GSon don't support JAXB. By using JAXB annotated class to create or process the JSON message, I can share the same class to create the Restful Web Service interface by using spring MVC.
Don't type python test.py
from inside the Python interpreter. Type it at the command prompt, like so:
You have to indent the docstring after the function definition there (line 3, 4):
def print_lol(the_list):
"""this doesn't works"""
print 'Ain't happening'
Indented:
def print_lol(the_list):
"""this works!"""
print 'Aaaand it's happening'
Or you can use #
to comment instead:
def print_lol(the_list):
#this works, too!
print 'Hohoho'
Also, you can see PEP 257 about docstrings.
Hope this helps!
Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.
The github repo will be created as a new project in android studio.
From mysql workbench run the following sql statements:
with the following sql statements check if the values were set:
SELECT @@global.time_zone, @@session.time_zone;
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;"
.
Instead of using valueOf(long)
and parse()
, you can directly use the BigInteger constructor that takes a string argument:
BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");
That should give you the desired value.
array_push — Push one or more elements onto the end of array
Take note of the words "one or more elements onto the end"
to do that using $arr[]
you would have to get the max size of the array
Here's a simple trap that prints the last argument of whatever failed to STDERR, reports the line it failed on, and exits the script with the line number as the exit code. Note these are not always great ideas, but this demonstrates some creative application you could build on.
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
I put that in a script with a loop to test it. I just check for a hit on some random numbers; you might use actual tests. If I need to bail, I call false (which triggers the trap) with the message I want to throw.
For elaborated functionality, have the trap call a processing function. You can always use a case statement on your arg ($_) if you need to do more cleanup, etc. Assign to a var for a little syntactic sugar -
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
throw=false
raise=false
while :
do x=$(( $RANDOM % 10 ))
case "$x" in
0) $throw "DIVISION BY ZERO" ;;
3) $raise "MAGIC NUMBER" ;;
*) echo got $x ;;
esac
done
Sample output:
# bash tst
got 2
got 8
DIVISION BY ZERO at 6
# echo $?
6
Obviously, you could
runTest1 "Test1 fails" # message not used if it succeeds
Lots of room for design improvement.
The draw backs include the fact that false
isn't pretty (thus the sugar), and other things tripping the trap might look a little stupid. Still, I like this method.
copy connection string to app.config
or web.config
file in the project which has set to "Set as StartUp
Project" and if in the case of using entity framework in data layer project - please install entity framework nuget in main project.
I created a Kotlin extension function that simplifies the operation for Kotlin developers based on @Jason Robinson's answer. I hope it helps.
fun Bitmap.fixRotation(uri: Uri): Bitmap? {
val ei = ExifInterface(uri.path)
val orientation: Int = ei.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage( 90f)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage( 180f)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage( 270f)
ExifInterface.ORIENTATION_NORMAL -> this
else -> this
}
}
fun Bitmap.rotateImage(angle: Float): Bitmap? {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(
this, 0, 0, width, height,
matrix, true
)
}
You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.
One way can be to circularly store the values in the buffer array. and calculate average this way.
int j = (int) (counter % size);
buffer[j] = mostrecentvalue;
avg = (avg * size - buffer[j - 1 == -1 ? size - 1 : j - 1] + buffer[j]) / size;
counter++;
// buffer[j - 1 == -1 ? size - 1 : j - 1] is the oldest value stored
The whole thing runs in a loop where most recent value is dynamic.
Does is need to be an array? If you use an ArrayList or one of the other objects available in C#, you won't have this limitation to content with. Hashtable, IDictionnary, IList, etc.. all allow a dynamic number of elements.
Whenever you are trying to return JSON response for API or else make sure you have proper headers and also make sure you return a valid JSON data.
Here is the sample script which helps you to return JSON response from PHP array or from JSON file.
PHP Script (Code):
<?php
// Set required headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
/**
* Example: First
*
* Get JSON data from JSON file and retun as JSON response
*/
// Get JSON data from JSON file
$json = file_get_contents('response.json');
// Output, response
echo $json;
/** =. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =. */
/**
* Example: Second
*
* Build JSON data from PHP array and retun as JSON response
*/
// Or build JSON data from array (PHP)
$json_var = [
'hashtag' => 'HealthMatters',
'id' => '072b3d65-9168-49fd-a1c1-a4700fc017e0',
'sentiment' => [
'negative' => 44,
'positive' => 56,
],
'total' => '3400',
'users' => [
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'rayalrumbel',
'text' => 'Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'mikedingdong',
'text' => 'Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'ScottMili',
'text' => 'Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
[
'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
'screen_name' => 'yogibawa',
'text' => 'Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.',
'timestamp' => '{{$timestamp}}',
],
],
];
// Output, response
echo json_encode($json_var);
JSON File (JSON DATA):
{
"hashtag": "HealthMatters",
"id": "072b3d65-9168-49fd-a1c1-a4700fc017e0",
"sentiment": {
"negative": 44,
"positive": 56
},
"total": "3400",
"users": [
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "rayalrumbel",
"text": "Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "mikedingdong",
"text": "Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "ScottMili",
"text": "Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
},
{
"profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg",
"screen_name": "yogibawa",
"text": "Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.",
"timestamp": "{{$timestamp}}"
}
]
}
JSON Screeshot:
You have to specify the folder where you are saving it and it has to exist, in other case it will throw an error.
var s = txt.CreateTextFile("c:\\11.txt", true);
mmm is very simple guys
for( int i = model.getRowCount() - 1; i >= 0; i-- )
{
model.removeRow(i);
}
A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)
One more to thing to think about when daemonizing in python:
If your are using python logging and you want to continue using it after daemonizing, make sure to call close()
on the handlers (particularly the file handlers).
If you don't do this the handler can still think it has files open, and your messages will simply disappear - in other words make sure the logger knows its files are closed!
This assumes when you daemonise you are closing ALL the open file descriptors indiscriminatingly - instead you could try closing all but the log files (but it's usually simpler to close all then reopen the ones you want).
As others have mentioned before,
There is no typedef mechanism in Java.
I also do not support "fake classes" in general, but there should not be a general strict rule of thumb here:
If your code for example uses over and over and over a "generic based type" for example:
Map<String, List<Integer>>
You should definitely consider having a subclass for that purpose.
Another approach one can consider, is for example to have in your code a deceleration like:
//@Alias Map<String, List<Integer>> NameToNumbers;
And then use in your code NameToNumbers and have a pre compiler task (ANT/Gradle/Maven) to process and generate relevant java code.
I know that to some of the readers of this answer this might sound strange, but this is how many frameworks implemented "annotations" prior to JDK 5, this is what project lombok is doing and other frameworks.
If you're using maven I would do something like this:
Being production your default profile:
<properties>
<activeProfile>production</activeProfile>
</properties>
And as an example of other profiles:
<profiles>
<!--Your default profile... selected if none specified-->
<profile>
<id>production</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<activeProfile>production</activeProfile>
</properties>
</profile>
<!--Profile 2-->
<profile>
<id>development</id>
<properties>
<activeProfile>development</activeProfile>
</properties>
</profile>
<!--Profile 3-->
<profile>
<id>otherprofile</id>
<properties>
<activeProfile>otherprofile</activeProfile>
</properties>
</profile>
<profiles>
In your application.properties you'll have to set:
spring.profiles.active=@activeProfile@
This works for me every time, hope it solves your problem.
Start your Local SQL Server Service
This will ensure they start up again if you restart your computer. Please check to ensure the state is "Running" for both services.
Login and authenticate with your Local SQL Server
[Your PC name]\SQLEXPRESS
Example: 8540P-KL\SQLEXPRESS or (localhost)\SQLEXPRESS
To find your PC name: Right click My Computer -> Properties -> Computer Name tab
Alternative: Login using windows authentication: Using the user name [Your Domain]/[Your User Name]
Setup User Account
Create a new Login acct: In SQL Mgmt Studio -> Expand your local Server -> Security -> Right click on Logins -> New Login
Set Password settings on New User Account: Uncheck Enforce password policy, password expiration and user must change pw(Since this is local) Default database -> Your Database
Grant roles to New User Account: User Mapping Page -> Map to your db and grant db_owner role Status Page -> Grant Permission to connect and Enable Login
Setup Access Permissions/Settings for User
Database Properties File for Spring Project
database.url=jdbc:jtds:sqlserver://[local PC Computer
name];instance=SQLEXPRESS;DatabaseName=[db name];
database.username=[Your user name] database.password=[Your password]
database.driverClassName=net.sourceforge.jtds.jdbc.Driver
If you want to view larger screen shots and better formatting of the answer with more details please view the blog article below: Setting up a Local Instance of SQL Server 2008 Blog Post:
There isn't one as far as I know of, one way however to do it is to create a dict for normal lookup by key and another dict for reverse lookup by value.
There's an example of such an implementation here:
http://code.activestate.com/recipes/415903-two-dict-classes-which-can-lookup-keys-by-value-an/
This does mean that looking up the keys for a value could result in multiple results which can be returned as a simple list.
Use the time package to work with time information in Go.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
Play example:
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
A too late answer :)
If you apply float to tr
elements, you can space between two rows with margin
attribute.
table tr{
float: left
width: 100%;
}
tr.classname {
margin-bottom:5px;
}
In addition to these great answers, in the context of an IISExpress dev environment, and in order to thwart the infamous "system.web/identity@impersonate" error, you can simply ensure the following setting is in place in your applicationhost.config file.
<configuration>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
</configuration>
This will allow you more flexibility during development and testing, though be sure you understand the implications of using this setting in a production environment before doing so.
Helpful Posts:
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
One tiny addition to JB Jansen's answer - in the main readdir()
loop I'd add this:
if (dir->d_type == DT_REG)
{
printf("%s\n", dir->d_name);
}
Just checking if it's really file, not (sym)link, directory, or whatever.
NOTE: more about struct dirent
in libc
documentation.
Use this command:
sudo chown -R $USER ~/.composer/
Brace expansion doesn't work, but *
, ?
and []
do. If you set shopt -s extglob
then you can also use extended pattern matching:
?()
- zero or one occurrences of pattern*()
- zero or more occurrences of pattern+()
- one or more occurrences of pattern@()
- one occurrence of pattern!()
- anything except the patternHere's an example:
shopt -s extglob
for arg in apple be cd meet o mississippi
do
# call functions based on arguments
case "$arg" in
a* ) foo;; # matches anything starting with "a"
b? ) bar;; # matches any two-character string starting with "b"
c[de] ) baz;; # matches "cd" or "ce"
me?(e)t ) qux;; # matches "met" or "meet"
@(a|e|i|o|u) ) fuzz;; # matches one vowel
m+(iss)?(ippi) ) fizz;; # matches "miss" or "mississippi" or others
* ) bazinga;; # catchall, matches anything not matched above
esac
done
As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.
To answer your specific questions:
std::fill_n(array, elementCount, 0);
Assuming array
is a normal array (e.g. int[]
)
Ctrl + P (Win, Linux), Cmd + P (Mac) – Quick open, Go to file
I'm pretty sure you'll have to loop through the list of databases and then list each table. You should be able to union them together.
A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.
A procedure is executed using the CALL query.
Open my sql command promt:
then enter mysql password
finally use:
ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password';
refer:https://stackoverflow.com/a/49228443/6097074
Thanks.
As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.
public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
{
return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
}
Try this
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$("#checkBoxes input").prop('checked', $(this).prop('checked'));
});
});
That should do it :)
You can simply create a controller funciton and pass your parameters with the $scope object.
$scope.Edit = function (modalParam) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: function($scope) {
$scope.modalParam = modalParam;
}
});
}
Eric B’s answer is OK if you want to preserve just one or maybe two columns from the existing row. If you want to preserve a lot of columns, it gets too cumbersome fast.
Here’s an approach that will scale well to any amount of columns on either side. To illustrate it I will assume the following schema:
CREATE TABLE page (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
title TEXT,
content TEXT,
author INTEGER NOT NULL REFERENCES user (id),
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Note in particular that name
is the natural key of the row – id
is used only for foreign keys, so the point is for SQLite to pick the ID value itself when inserting a new row. But when updating an existing row based on its name
, I want it to continue to have the old ID value (obviously!).
I achieve a true UPSERT
with the following construct:
WITH new (name, title, author) AS ( VALUES('about', 'About this site', 42) )
INSERT OR REPLACE INTO page (id, name, title, content, author)
SELECT old.id, new.name, new.title, old.content, new.author
FROM new LEFT JOIN page AS old ON new.name = old.name;
The exact form of this query can vary a bit. The key is the use of INSERT SELECT
with a left outer join, to join an existing row to the new values.
Here, if a row did not previously exist, old.id
will be NULL
and SQLite will then assign an ID automatically, but if there already was such a row, old.id
will have an actual value and this will be reused. Which is exactly what I wanted.
In fact this is very flexible. Note how the ts
column is completely missing on all sides – because it has a DEFAULT
value, SQLite will just do the right thing in any case, so I don’t have to take care of it myself.
You can also include a column on both the new
and old
sides and then use e.g. COALESCE(new.content, old.content)
in the outer SELECT
to say “insert the new content if there was any, otherwise keep the old content” – e.g. if you are using a fixed query and are binding the new values with placeholders.
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
You should drop the old table type and create a new one. However if it has any dependencies (any stored procedures using it) you won't be able to drop it. I've posted another answer on how to automate the process of temporary dropping all stored procedures, modifying the table table and then restoring the stored procedures.
This is how I was able to set the padding between the home icon and the title.
ImageView view = (ImageView)findViewById(android.R.id.home);
view.setPadding(left, top, right, bottom);
I couldn't find a way to customize this via the ActionBar xml styles though. That is, the following XML doesn't work:
<style name="ActionBar" parent="android:style/Widget.Holo.Light.ActionBar">
<item name="android:titleTextStyle">@style/ActionBarTitle</item>
<item name="android:icon">@drawable/ic_action_home</item>
</style>
<style name="ActionBarTitle" parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">
<item name="android:textSize">18sp</item>
<item name="android:paddingLeft">12dp</item> <!-- Can't get this padding to work :( -->
</style>
However, if you are looking to achieve this through xml, these two links might help you find a solution:
https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/styles.xml
(This is the actual layout used to display the home icon in an action bar) https://github.com/android/platform_frameworks_base/blob/master/core/res/res/layout/action_bar_home.xml
If you already pushed your changes, you will need to force your next push after resetting the HEAD.
git reset --hard HEAD^
git merge COMMIT_SHA1
git push --force
Warning: a hard reset will undo any uncommitted modifications in your working copy, while a force push will completely overwrite the state of the remote branch with the current state of the local branch.
Just in case, on Windows (using the Windows command line, not Bash) it's actually four ^^^^
instead of one, so it's
git reset --hard HEAD^^^^
The way I use is:
git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master
There are multiple ways to open a link in new tab in using Selenium WebDriver.
Code Block:
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class NewTab_blank_iterator {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://mail.google.com/");
String firstWindowHandle = driver.getWindowHandle();
System.out.println("First Window Handle is: "+firstWindowHandle);
// Opening an adjacent blank tab
((JavascriptExecutor)driver).executeScript("window.open('','_blank');");
new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allWindowHandles = driver.getWindowHandles();
// Using iterator
Iterator<String> itr = allWindowHandles.iterator();
while(itr.hasNext()) {
String nextWindow = itr.next();
if(!firstWindowHandle.equalsIgnoreCase(nextWindow)) {
driver.switchTo().window(nextWindow);
System.out.println("New Tab Window Handle is: "+nextWindow);
}
}
}
}
Console Output:
First Window Handle is: CDwindow-0D89767363ED691767000F01E6712D0B
New Tab Window Handle is: CDwindow-7232D2058514ED22344F129D30A0CCE7
Browser Snapshot:
Code Block:
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class NewTab_url_forLoop {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
WebDriver driver = new ChromeDriver(options);
String url1 = "https://mail.google.com/";
String url2 = "https://www.facebook.com/";
driver.get(url1);
String firstWindowHandle = driver.getWindowHandle();
System.out.println("First Window Handle is: "+firstWindowHandle);
// Opening Facebook in the adjacent TAB
((JavascriptExecutor)driver).executeScript("window.open('" + url2 +"');");
new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allWindowHandles = driver.getWindowHandles();
// Using iterator
Iterator<String> itr = allWindowHandles.iterator();
while(itr.hasNext()) {
String nextWindow = itr.next();
if(!firstWindowHandle.equalsIgnoreCase(nextWindow)) {
driver.switchTo().window(nextWindow);
System.out.println("New Tab Window Handle is: "+nextWindow);
}
}
}
}
Console Output:
First Window Handle is: CDwindow-01F5622275A2EA2C1ABE2F0CDEB3D09B
New Tab Window Handle is: CDwindow-9E3349B91FB2FA4D5B7D4A90D0E87BD3
Browser Snapshot:
Richard Cox has a good solution to this https://stackoverflow.com/a/5200280/1171321 I have used in the past. It is also worth noting the DPI must be 96 for this to work correctly. Several of the solutions on this page do not work at all.
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
I've recently made a page loader in vanilla .js
for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.
It automatically creates a <div>
tag prepended to the <body>
, with a <svg>
loader. If you want to customize the color you just have to update the t
variable at the beginning of the script.
var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})
You can see the full project and documentation on the GitHub
In your .htaccess file , if you are using apache you can try with
Rule for Error Page - 404ErrorDocument 404 http://www.domain.com/notFound.html
If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.
The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.
More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)
Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64
I made the mistake of adding a NewtonSoft .dll file for .Net 4.5.
My main project was 4.5, but when I added an extra project to my solution, it strangely added it as a .Net 2.0 project... and when I attempted to use NewtonSoft's 4.5 dll with this, I got this "Newtonsoft.Json couldn't be found" error.
The solution (of course) was to change this new project from .Net 2.0 to 4.5.
I don't think execute
git rm first_file.txt
is a good idea.
when git notice your files is unmerged, you should ensure you had committed it.
And then open the conflict file:
cat first_file.txt
fix the conflict
4.
git add file
git commit -m "fix conflict"
5.
git push
it should works for you.
In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.
click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown
etc
Here's a good guide: https://web.archive.org/web/20160301104014/http://gerrydevstory.com/2012/08/20/how-to-create-virtual-network-interface-on-mac-os-x/
Basically you select a network adapter in the Networks pane of system preferences, then click the gear to "Duplicate Service". After the service is duplicated, you manually assign an IP in one of the private address ranges. Then ping it to make sure ;)
the previous answers didn't work out for me well. I had persisting problems by setting the marker. So i changed the code slightly.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ANSI" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 1500px; height: 1000px;"></div>
<script type="text/javascript">
var locations = [
['Goettingen', 51.54128040000001, 9.915803500000038, 'http://www.google.de'],
['Kassel', 51.31271139999999, 9.479746100000057,0, 'http://www.stackoverflow.com'],
['Witzenhausen', 51.33996819999999, 9.855564299999969,0, 'www.http://developer.mozilla.org.de']
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(51.54376, 9.910419999999931),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
url: locations[i][4]
});
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
window.location.href = this.url;
}
})(marker, i));
}
</script>
</body>
</html>
This way worked out for me! You can create Google Maps routing links from your Datebase to to use it as an interactive routing map.
Although probably not the best method you could add:
#div1 {
...
font-size:0;
}
Set elevation: 3
and you should see the shadow in bottom of component without a 3rd party lib. At least in RN 0.57.4
The addition of a string literal with an std::string
yields another std::string
. system
expects a const char*
. You can use std::string::c_str()
for that:
string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());
The problem is that you define it inside the class, which
a) means the second argument is implicit (this
) and
b) it will not do what you want it do, namely extend std::ostream
.
You have to define it as a free function:
class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);
Also, we can assign the Value to the Control in Designer Class (i.e. FormName.Designer.cs).
DateTimePicker1.Value = DateTime.Now;
This way you always get Current Date...
No, template member functions cannot be virtual.
I made a generic component where I need a reference to the parent using it. Here's what I came up with:
In my component I made an @Input :
@Input()
parent: any;
Then In the parent using this component:
<app-super-component [parent]="this"> </app-super-component>
In the super component I can use any public thing coming from the parent:
Attributes:
parent.anyAttribute
Functions :
parent[myFunction](anyParameter)
and of course private stuff won't be accessible.
Pretty sure nobody answer your question to your exact terms, you want it for dynamic text
var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );
It takes a substring from the first comma, to the end
Scanner sc = new Scanner (System.in)
char c = sc.next().trim().charAt(0);
If you have trouble viewing the .env file or it is not showing up in the project just do this: ls -a
.
This allows to see the hidden files in Linux. You can also open the folder with Visual Studio Code and you will see the files and be able to modify them.
In windows
netstat -ano
will list all the protocols, ports and processes listening . Use
taskkill -pid "proces to kill" /f
to kill the process listening to the port. e.g
taskkill -pid 431 /f
Instead of going with equivalent, you can try "brew install wget" and use wget.
You need to have brew installed in your mac.
You can use something like ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60
too.
In my case, after having the same error (Cannot resolve symbol R) with android studio version 0.8.9, what I did was go to File->Project structure and changed the JDK location to oracle JDK which I manually installed. So in my case in linux instead of /usr/lib/jvm/java-7-oracle which was the preset one. I changed it to /home/phvz/App/jdk1.8.0_20 saved the settings and the R symbol issue was fixed immediately
I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.
This should give you a hint what goes wrong.
You need to add value: location
in your code to work it. Check this out.
items: _locations.map((String location) {
return new DropdownMenuItem<String>(
child: new Text(location),
value: location,
);
}).toList(),
Console example of MemoryCache, "How to save/get simple class objects"
Output after launching and pressing Any key except Esc :
Saving to cache!
Getting from cache!
Some1
Some2
class Some
{
public String text { get; set; }
public Some(String text)
{
this.text = text;
}
public override string ToString()
{
return text;
}
}
public static MemoryCache cache = new MemoryCache("cache");
public static string cache_name = "mycache";
static void Main(string[] args)
{
Some some1 = new Some("some1");
Some some2 = new Some("some2");
List<Some> list = new List<Some>();
list.Add(some1);
list.Add(some2);
do {
if (cache.Contains(cache_name))
{
Console.WriteLine("Getting from cache!");
List<Some> list_c = cache.Get(cache_name) as List<Some>;
foreach (Some s in list_c) Console.WriteLine(s);
}
else
{
Console.WriteLine("Saving to cache!");
cache.Set(cache_name, list, DateTime.Now.AddMinutes(10));
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
In order to match a digit, you can use [0-9]
.
So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9]
and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]
. I do this a lot for zip codes.
You could use former Instantiations product CodePro AnalytiX. This eclipse plugin provides you suchlike statistics in code metrics view. This is provided by Google free of charge.
I think you are after something like this; (Using row_number()
with CTE
and performing a FULL OUTER JOIN
)
;with t1 as (
select col1,col2, row_number() over (order by col1) rn
from table1
),
t2 as (
select col3,col4, row_number() over (order by col3) rn
from table2
)
select col1,col2,col3,col4
from t1 full outer join t2 on t1.rn = t2.rn
Tables and data :
create table table1 (col1 int, col2 int)
create table table2 (col3 int, col4 int)
insert into table1 values
(1,2),(3,4)
insert into table2 values
(10,11),(30,40),(50,60)
Results :
| COL1 | COL2 | COL3 | COL4 |
---------------------------------
| 1 | 2 | 10 | 11 |
| 3 | 4 | 30 | 40 |
| (null) | (null) | 50 | 60 |
When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3
Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int
dt = datetime(2018,11,3,10,2,5)
print (dt)
#print (dt.timestamp()) # unix representation ... not useful when converting to int
print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100 + dt.day)
print (int(dt.strftime("%Y%m%d")))
print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000 + dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))
To avoid that doing manually use below function
def datetime_to_int(dt):
return int(dt.strftime("%Y%m%d%H%M%S"))
SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();
//using SSH.Net
In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.
This would require a sort (O(n log n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL:
var maxObject = list.OrderByDescending(item => item.Height).First();
Note that this has the advantage of enumerating the list
sequence just once. While it might not matter if list
is a List<T>
that doesn't change in the meantime, it could matter for arbitrary IEnumerable<T>
objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own MaxObject
extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)):
static class EnumerableExtensions {
public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector)
where U : IComparable<U> {
if (source == null) throw new ArgumentNullException("source");
bool first = true;
T maxObj = default(T);
U maxKey = default(U);
foreach (var item in source) {
if (first) {
maxObj = item;
maxKey = selector(maxObj);
first = false;
} else {
U currentKey = selector(item);
if (currentKey.CompareTo(maxKey) > 0) {
maxKey = currentKey;
maxObj = item;
}
}
}
if (first) throw new InvalidOperationException("Sequence is empty.");
return maxObj;
}
}
and use it with:
var maxObject = list.MaxObject(item => item.Height);
Try:
to_dict = lambda **k: k
apple = 1
banana = 'f'
carrot = 3
to_dict(apple=apple, banana=banana, carrot=carrot)
#{'apple': 1, 'banana': 'f', 'carrot': 3}
I don't think Ansible provides this feature, which it should. Here's something that you can do:
hosts: "{{ variable_host | default('web') }}"
and you can pass variable_host
from either command-line or from a vars file, e.g.:
ansible-playbook server.yml --extra-vars "variable_host=newtarget(s)"
Shorter version that uses Lombok
import java.util.function.Consumer;
import java.util.function.Predicate;
import lombok.RequiredArgsConstructor;
/**
* Forks a Stream using a Predicate into postive and negative outcomes.
*/
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PROTECTED)
public class StreamForkerUtil<T> implements Consumer<T> {
Predicate<T> predicate;
Consumer<T> positiveConsumer;
Consumer<T> negativeConsumer;
@Override
public void accept(T t) {
(predicate.test(t) ? positiveConsumer : negativeConsumer).accept(t);
}
}
If not use hasOwnProperty then we have incorrect elements. For example:
[1,2,3].diff([1,2]); //Return ["3", "remove", "diff"] This is the wrong version
My version:
Array.prototype.diff = function(array2)
{
var a = [],
diff = [],
array1 = this || [];
for (var i = 0; i < array1.length; i++) {
a[array1[i]] = true;
}
for (var i = 0; i < array2.length; i++) {
if (a[array2[i]]) {
delete a[array2[i]];
} else {
a[array2[i]] = true;
}
}
for (var k in a) {
if (!a.hasOwnProperty(k)){
continue;
}
diff.push(k);
}
return diff;
}
Android Studio 3.1 has option to edit your customize virtual memory options.
You can go Android Studio > Help > Edit Custom VM Options
Then paste below settings code to studio64.exe.vmoptions file & Save it.
file location : "\Users\username\.AndroidStudio3.**\config\"
-Xms128m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops
sudo apt-get install php5-mcrypt
ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini
service php5-fpm restart
service nginx restart
The error means that R could not find the variable mentioned in the error message.
The easiest way to reproduce the error is to type the name of a variable that doesn't exist. (If you've defined x
already, use a different variable name.)
x
## Error: object 'x' not found
The more complex version of the error has the same cause: calling a function when x
does not exist.
mean(x)
## Error in mean(x) :
## error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found
Once the variable has been defined, the error will not occur.
x <- 1:5
x
## [1] 1 2 3 4 5
mean(x)
## [1] 3
You can check to see if a variable exists using ls
or exists
.
ls() # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.
Errors like this can occur when you are using non-standard evaluation. For example, when using subset
, the error will occur if a column name is not present in the data frame to subset.
d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found
The error can also occur if you use custom evaluation.
get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found
In the second case, the var
function cannot be found when R looks in the utils
package's environment because utils
is further down the search
list than stats
.
In more advanced use cases, you may wish to read:
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
Using ClassLoader.getSystemClassLoader()
Sample code :
Properties prop = new Properties();
InputStream input = null;
try {
input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
prop.load(input);
} catch (IOException io) {
io.printStackTrace();
}
A simple question should be followed by a short, simple and clear answer.
When we are getting a value of the property it fires its get{}
part.
When we are setting a value to the property it fires its set{}
part.
PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{}
part.
Example:
var A:Int = 0
var B:Int = 0
var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
B = newValue
}
}
//When we are getting a value of C it fires get{} part of C property
A = C
A //Now A = 1
//When we are setting a value to C it fires set{} part of C property
C = 2
B //Now B = 2
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of <
, the XML parser is implicitly looking for the tag name and the end tag >
. However, in your particular case, you were using <
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The content of elements must consist of well-formed character data or markup.
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The <
must be escaped as <
.
So, essentially, the
for (var i = 0; i < length; i++) {
must become
for (var i = 0; i < length; i++) {
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="functions.js" target="head" />
This way you don't need to worry about XML-special characters in your JS code. Additional advantage is that this gives the browser the opportunity to cache the JS file so that average response size is smaller.
I had a related situation, where I specifically needed to set the cursor position to the END of a contenteditable div. I didn't want to use a full fledged library like Rangy, and many solutions were far too heavyweight.
In the end, I came up with this simple jQuery function to set the carat position to the end of a contenteditable div:
$.fn.focusEnd = function() {
$(this).focus();
var tmp = $('<span />').appendTo($(this)),
node = tmp.get(0),
range = null,
sel = null;
if (document.selection) {
range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
range = document.createRange();
range.selectNode(node);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
tmp.remove();
return this;
}
The theory is simple: append a span to the end of the editable, select it, and then remove the span - leaving us with a cursor at the end of the div. You could adapt this solution to insert the span wherever you want, thus putting the cursor at a specific spot.
Usage is simple:
$('#editable').focusEnd();
That's it!
If you ought to spare memory, read char by char and realloc each time. Performance will die, but you'll spare this 10 bytes.
Another good tradeoff is to read in a function (using a local variable) then copying. So the big buffer will be function scoped.
Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:
Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
If Worksheets(1).Cells(i, 3) <> "" Then
call copValuesAndFormat(i,3,a,15)
call copValuesAndFormat(i,5,a,17)
call copValuesAndFormat(i,6,a,18)
call copValuesAndFormat(i,7,a,19)
call copValuesAndFormat(i,8,a,20)
call copValuesAndFormat(i,9,a,21)
a = a + 1
End If
Next i
end sub
sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
Worksheets(1).Cells(x1, y1).Copy
Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub
(I do not have Excel in current location so please excuse bugs as not tested)