Is this what you mean man: http://jsfiddle.net/LF75a/
You will have one function fire the next function and so on, i.e. add another function call and then add your functionONe
at the bottom of it.
Please lemme know if I missed anything, hope it fits the cause :)
or this: Call a function after previous function is complete
Code:
function hulk()
{
// do some stuff...
}
function simpsons()
{
// do some stuff...
hulk();
}
function thor()
{
// do some stuff...
simpsons();
}
If you did everything right, just give the permission home directory like:
sudo chmod o+x $HOME
then
sudo systemctl restart apache2
On iOS there is the switch UI component instead of a checkbox, look into the UISwitch
class.
The property on
(boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.
Notepad++ Add Word To Start Of Every Line
Follow this instruction to write anything at the start of every line with Notepad++
Open Notepad++,
Press Cntrl+H open the Find/Replace Dialog.
Now type ^ in the Find what textbox (Type ^ without any spaces)
Type anything(like in our example I am writing "John ") in the Replace with textbox (Write text one/more space for adding one/more space after your text in every line)
Select the Regular Expression option
Place your cursor in the first line of your file to ensure all lines are affected
Click Replace All button
Notepad++ Add Text To End Of Every Line
Follow this instruction to write anything at the end of every line with Notepad++
Open Notepad++,
Press Cntrl+H open the Find/Replace Dialog.
Now type $ in the Find what textbox (Type $ without any spaces)
Type anything(like in our example I am writing " John") in the Replace with textbox (Write one/more space text for adding one/more space before your text in every line)
Select the Regular Expression option
Place your cursor in the first line of your file to ensure all lines are affected
Click Replace All button
For all Notepadd++ Tutorials: VISIT:)
you can do this---
<input type="button" onClic="changebackColor">
function changebackColor(){
document.body.style.backgroundColor = "black";
document.getElementByID("divID").style.backgroundColor = "black";
window.setTimeout("yourFunction()",10000);
}
In my particular usecase, I needed to group by a property and then remove the grouping property.
That property was only added to the record for grouping purposes anyway and it wouldn't make sense for presentation to a user.
group (arr, key) {
let prop;
return arr.reduce(function(rv, x) {
prop = x[key];
delete x[key];
(rv[prop] = (rv[prop] || [])).push(x);
return rv;
}, {});
},
Credit to @caesar-bautista for the starting function in the top answer.
I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT
and DELETE
) which will be preceded by an OPTIONS
request, specifying the middleware in the $routeMiddleware
array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS
as well. This is because without an OPTIONS
route Laravel will internally respond to that method without the CORS headers.
So in short either define the middleware in the $middleware
array which runs globally for all requests or if you're doing it in $middlewareGroups
or $routeMiddleware
then also define a route handler for OPTIONS
. This can be done like this:
Route::match(['options', 'put'], '/route', function () {
// This will work with the middleware shown in the accepted answer
})->middleware('cors');
I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
private static $allowedOriginsWhitelist = [
'http://localhost:8000'
];
// All the headers must be a string
private static $allowedOrigin = '*';
private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';
private static $allowCredentials = 'true';
private static $allowedHeaders = '';
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $this->isCorsRequest($request))
{
return $next($request);
}
static::$allowedOrigin = $this->resolveAllowedOrigin($request);
static::$allowedHeaders = $this->resolveAllowedHeaders($request);
$headers = [
'Access-Control-Allow-Origin' => static::$allowedOrigin,
'Access-Control-Allow-Methods' => static::$allowedMethods,
'Access-Control-Allow-Headers' => static::$allowedHeaders,
'Access-Control-Allow-Credentials' => static::$allowCredentials,
];
// For preflighted requests
if ($request->getMethod() === 'OPTIONS')
{
return response('', 200)->withHeaders($headers);
}
$response = $next($request)->withHeaders($headers);
return $response;
}
/**
* Incoming request is a CORS request if the Origin
* header is set and Origin !== Host
*
* @param \Illuminate\Http\Request $request
*/
private function isCorsRequest($request)
{
$requestHasOrigin = $request->headers->has('Origin');
if ($requestHasOrigin)
{
$origin = $request->headers->get('Origin');
$host = $request->getSchemeAndHttpHost();
if ($origin !== $host)
{
return true;
}
}
return false;
}
/**
* Dynamic resolution of allowed origin since we can't
* pass multiple domains to the header. The appropriate
* domain is set in the Access-Control-Allow-Origin header
* only if it is present in the whitelist.
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedOrigin($request)
{
$allowedOrigin = static::$allowedOrigin;
// If origin is in our $allowedOriginsWhitelist
// then we send that in Access-Control-Allow-Origin
$origin = $request->headers->get('Origin');
if (in_array($origin, static::$allowedOriginsWhitelist))
{
$allowedOrigin = $origin;
}
return $allowedOrigin;
}
/**
* Take the incoming client request headers
* and return. Will be used to pass in Access-Control-Allow-Headers
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedHeaders($request)
{
$allowedHeaders = $request->headers->get('Access-Control-Request-Headers');
return $allowedHeaders;
}
}
Also written a blog post on this.
You can use rows
and cols
:
cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;
or size()
:
cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;
Stub of console in TypeScript:
if (!window.console) {
console = {
assert: () => { },
clear: () => { },
count: () => { },
debug: () => { },
dir: () => { },
dirxml: () => { },
error: () => { },
group: () => { },
groupCollapsed: () => { },
groupEnd: () => { },
info: () => { },
log: () => { },
msIsIndependentlyComposed: (e: Element) => false,
profile: () => { },
profileEnd: () => { },
select: () => { },
time: () => { },
timeEnd: () => { },
trace: () => { },
warn: () => { },
}
};
Another way to do it is to make an empty section right before the one you want the header on and put your header on that section. Because the section is empty the header will scroll immediately.
How about this?
List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.
Chrome now has a headless mode:
op = webdriver.ChromeOptions()
op.add_argument('--headless')
driver = webdriver.Chrome(options=op)
Using the excellent request
module:
var request = require('request');
request("http://stackoverflow.com", {method: 'HEAD'}, function (err, res, body){
console.log(res.headers);
});
You can change the method to GET
if you wish, but using HEAD
will save you from getting the entire response body if you only wish to look at the headers.
There are a few important informations missing from your question:
$ vim --version
?If your Vim was built with clipboard support, you are supposed to use the clipboard register like this, in normal mode:
gg"+yG
If your Vim doesn't have clipboard support, you can manage to copy text from Vim to your OS clipboard via other programs. This pretty much depends on your OS but you didn't say what it is so we can't really help.
However, if your Vim is crippled, the best thing to do is to install a proper build with clipboard support but I can't tell you how either because I don't know what OS you use.
edit
On debian based systems, the following command will install a proper Vim with clipboard, ruby, python… support.
$ sudo apt-get install vim-gnome
After trying all the solutions and none giving acceptable results (maybe because I was working on a device with default very large fonts), the following worked for me (COMPLEX_UNIT_DIP = Device Independent Pixels):
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
My Android Studio is 3.0, please follow the two steps below,hope this will help;)
It is SUBSTITUTE(B1," ","")
, not REPLACE(xx;xx;xx)
.
I used Joe's way to solve this issue :)
decimal argument = 123.456m;
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];
If you have a list view you can do this:
Define a select list:
@{
var Acciones = new SelectList(new[]
{
new SelectListItem { Text = "Modificar", Value =
Url.Action("Edit", "Countries")},
new SelectListItem { Text = "Detallar", Value =
Url.Action("Details", "Countries") },
new SelectListItem { Text = "Eliminar", Value =
Url.Action("Delete", "Countries") },
}, "Value", "Text");
}
Use the defined SelectList, creating a diferent id for each record (remember that id of each element must be unique in a view), and finally call a javascript function for onchange event (include parameters in example url and record key):
@Html.DropDownList("ddAcciones", Acciones, "Acciones", new { id =
item.CountryID, @onchange = "RealizarAccion(this.value ,id)" })
onchange function can be something as:
@section Scripts {
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
function RealizarAccion(accion, country)
{
var url = accion + '/' + country;
if (url != null && url != '') {
window.location.href = url ;
}
}
</script>
@Scripts.Render("~/bundles/jqueryval")
}
Since pandas v0.13 you can also use get_values
:
df.index.get_values()
If you are using SQL Server 2005 or greater, depending on the size of the data in the Notes field, you may want to consider casting to nvarchar(max) instead of casting to a specific length which could result in string truncation.
Select Cast(notes as nvarchar(max)) + 'SomeText' From NotesTable a
And if you need authorized user in templates (e.g. JSP) use
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>
together with
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring-security.version}</version>
</dependency>
Linux dotnet core doesn't support namedpipes!
Try TcpListener if you deploy to Linux
This NamedPipe Client/Server code round trips a byte to a server.
DotNet Core 2.0 Server ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
var server = new NamedPipeServerStream("A", PipeDirection.InOut);
server.WaitForConnection();
for (int i =0; i < 10000; i++)
{
var b = new byte[1];
server.Read(b, 0, 1);
Console.WriteLine("Read Byte:" + b[0]);
server.Write(b, 0, 1);
}
}
}
}
DotNet Core 2.0 Client ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Client
{
class Program
{
public static int threadcounter = 1;
public static NamedPipeClientStream client;
static void Main(string[] args)
{
client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
client.Connect();
var t1 = new System.Threading.Thread(StartSend);
var t2 = new System.Threading.Thread(StartSend);
t1.Start();
t2.Start();
}
public static void StartSend()
{
int thisThread = threadcounter;
threadcounter++;
StartReadingAsync(client);
for (int i = 0; i < 10000; i++)
{
var buf = new byte[1];
buf[0] = (byte)i;
client.WriteAsync(buf, 0, 1);
Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
}
}
public static async Task StartReadingAsync(NamedPipeClientStream pipe)
{
var bufferLength = 1;
byte[] pBuffer = new byte[bufferLength];
await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
{
Console.WriteLine($@"read data {pBuffer[0]}");
await StartReadingAsync(pipe); // read the next data <--
});
}
}
}
USE THIS FOR RIGHT TO LEFT SLIDING :
HTML:
<div class="nav ">
<ul>
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">SERVICES</a></li>
<li><a href="#">CONTACT</a></li>
</ul>
</div>
CSS:
/*nav*/
.nav{
position: fixed;
right:0;
top: 70px;
width: 250px;
height: calc(100vh - 70px);
background-color: #333;
transform: translateX(100%);
transition: transform 0.3s ease-in-out;
}
.nav-view{
transform: translateX(0);
}
.nav ul{
margin: 0;
padding: 0;
}
.nav ul li{
margin: 0;
padding: 0;
list-style-type: none;
}
.nav ul li a{
color: #fff;
display: block;
padding: 10px;
border-bottom: solid 1px rgba(255,255,255,0.4);
text-decoration: none;
}
JS:
$(document).ready(function(){
$('a#click-a').click(function(){
$('.nav').toggleClass('nav-view');
});
});
You can use: zip -u file.zip path/file_to_update
In bash scripts, I found that escaping double quotes around the value was necessary for values that could be null or contained characters that require escaping (like hyphens).
In this example, columnA's value could be null or contain hyphens.:
sqlite3 $db_name "insert into foo values (\"$columnA\", $columnB)";
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
There is no way to do this in single query. You have to search the document in first query:
If document exists:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Else
db.bar.update( {user_id : 123456 } ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
No need to add condition {$ne : "my_item_two" }
.
Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
There is also Scanner
. You can use it just like the BufferedReader
:
Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// process the line
}
scanner.close();
I think that this is a bit cleaner approach that both of the suggested ones.
In short, its because of recycling the views and using them again!
how can you avoid that :
1.In onBindViewHolder
check whether you should check or uncheck boxes.
don't forget to put both if and else
if (...)
holder.cbSelect.setChecked(true);
else
holder.cbSelect.setChecked(false);
myItems
array ! so whenever a new view is shown, it read the newest statue of the object.This might be the case where you could benefit from using the WriteCData method.
public override void WriteCData(string text)
Member of System.Xml.XmlTextWriter
Summary:
Writes out a <![CDATA[...]]> block containing the specified text.
Parameters:
text: Text to place inside the CDATA block.
A simple example would look like the following:
writer.WriteStartElement("name");
writer.WriteCData("<unsafe characters>");
writer.WriteFullEndElement();
The result looks like:
<name><![CDATA[<unsafe characters>]]></name>
When reading the node values the XMLReader automatically strips out the CData part of the innertext so you don't have to worry about it. The only catch is that you have to store the data as an innerText value to an XML node. In other words, you can't insert CData content into an attribute value.
The -L
merely gives the path where to find the .a
or .so
file. What you're looking for is to add -lmine
to the LIBS
variable.
Make that -static -lmine
to force it to pick the static library (in case both static and dynamic library exist).
Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L
you can also specifically tell it to link libfoo.a
by giving -l:libfoo.a
. Note that in this case the name includes the conventional lib
-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.
yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'
I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.
From the documentation of String.split(String regex)
:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
So you will have to use the two argument version String.split(String regex, int limit)
with a negative value:
String[] split = data.split("\\|",-1);
Doc:
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
This will not leave out any empty elements, including the trailing ones.
For future readers who found this question while trying to save high resolution images from matplotlib as I am, I have tried some of the answers above and elsewhere, and summed them up here.
Best result: plt.savefig('filename.pdf')
and then converting this pdf to a png on the command line so you can use it in powerpoint:
pdftoppm -png -r 300 filename.pdf filename
OR simply opening the pdf and cropping to the image you need in adobe, saving as a png and importing the picture to powerpoint
Less successful test #1: plt.savefig('filename.png', dpi=300)
This does save the image at a bit higher than the normal resolution, but it isn't high enough for publication or some presentations. Using a dpi value of up to 2000 still produced blurry images when viewed close up.
Less successful test #2: plt.savefig('filename.pdf')
This cannot be opened in Microsoft Office Professional Plus 2016 (so no powerpoint), same with Google Slides.
Less successful test #3: plt.savefig('filename.svg')
This also cannot be opened in powerpoint or Google Slides, with the same issue as above.
Less successful test #4: plt.savefig('filename.pdf')
and then converting to png on the command line:
convert -density 300 filename.pdf filename.png
but this is still too blurry when viewed close up.
Less successful test #5: plt.savefig('filename.pdf')
and opening in GIMP, and exporting as a high quality png (increased the file size from ~100 KB to ~75 MB)
Less successful test #6: plt.savefig('filename.pdf')
and then converting to jpeg on the command line:
pdfimages -j filename.pdf filename
This did not produce any errors but did not produce an output on Ubuntu even after changing around several parameters.
The meaning of final in java is: -applied to a variable means that the respective variable once initialized can no longer be modified
private final double numer = 12;
If you try to modify this value, you will get an error.
-applied to a method means that the respective method can't be override
public final void displayMsg()
{
System.out.println("I'm in Base class - displayMsg()");
}
But final method can be inherited because final keyword restricts the redefinition of the method.
-applied to a class means that the respective class can't be extended.
class Base
{
public void displayMsg()
{
System.out.println("I'm in Base class - displayMsg()");
}
}
The meaning of finally is :
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
in this exemple even if the try-catch is executed or not, what is inside of finally will always be executed. The meaning of finalize:
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
before calling the Garbage Collector.
I have different solution:
SELECT AUTO_INCREMENT - 1 as CurrentId FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'tablename'
I have created a util service for my angular application. It have two function which use very often.
For example you have object.
First getting value from object recursively without throwing undefined error.
{prop: { nestedProp1: {nestedProp2: somevalue}}}; get nestedProp2 2 without undefined checks.
Second filter array on basis
[{prop: { nestedProp1: {nestedProp2: somevalue1}}}, {prop: { nestedProp1: {nestedProp2: somevalue2}}}];
Find object from array with nestedProp2=somevalue2
app.service('UtilService', function(httpService) {
this.mapStringKeyVal = function(map, field) {
var lastIdentifiedVal = null;
var parentVal = map;
field.split('.').forEach(function(val){
if(parentVal[val]){
lastIdentifiedVal = parentVal[val];
parentVal = parentVal[val];
}
});
return lastIdentifiedVal;
}
this.arrayPropFilter = function(array, field,value) {
var lastIdentifiedVal = null;
var mapStringKeyVal = this.mapStringKeyVal;
array.forEach(function(arrayItem){
var valueFound = mapStringKeyVal(arrayItem,field);
if(!lastIdentifiedVal && valueFound && valueFound==value){
lastIdentifiedVal = arrayItem;
}
});
return lastIdentifiedVal;
}});
For solution for current question. inject UtilService and call,
UtilService.arrayPropFilter(purposeArray,'purpose','daily');
Or more advanced
UtilService.arrayPropFilter(purposeArray,'purpose.nestedProp1.nestedProp2','daily');
The consequence of this is that you may need a rather insane-looking query, e. g.,
SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID] AS lngRecordID
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName] AS vcrSourceWorkbookName
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName] AS vcrImportFileName
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime] AS dtmLastWriteTime
,[dbo].[tblTimeSheetExportFiles].[lngNRecords] AS lngNRecords
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk] AS lngSizeOnDisk
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity] AS lngLastIdentity
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
,MIN ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodFirstWorkDate
,MAX ( [tblTimeRecords].[dtmActivity_Date] ) AS dtmPeriodLastWorkDate
,SUM ( [tblTimeRecords].[decMan_Hours_Actual] ) AS decHoursWorked
,SUM ( [tblTimeRecords].[decAdjusted_Hours] ) AS decHoursBilled
FROM [dbo].[tblTimeSheetExportFiles]
LEFT JOIN [dbo].[tblTimeRecords]
ON [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
GROUP BY [dbo].[tblTimeSheetExportFiles].[lngRecordID]
,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]
Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.
Programmatically, you could use:
textView.setTextAppearance(android.R.style.TextAppearance_Large);
if you are trying to add a general note to the overall object (query or table etc..)
Access 2016 go to navigation pane, highlight object, right click, select object / table properties, add a note in the description window i.e. inventory "table last last updated 05/31/17"
I found that this worked
content: "\f2d7" !important;
font-family: FontAwesome !important;
It didn't seem to work without the !important for me.
Here's a tutorial on how to change social icons with Unicodes https://www.youtube.com/watch?v=-jgDs2agkE0&feature=youtu.be
Thought I would chip in here with when I have found ON
to be more useful than USING
. It is when OUTER
joins are introduced into queries.
ON
benefits from allowing the results set of the table that a query is OUTER
joining onto to be restricted while maintaining the OUTER
join. Attempting to restrict the results set through specifying a WHERE
clause will, effectively, change the OUTER
join into an INNER
join.
Granted this may be a relative corner case. Worth putting out there though.....
For example:
CREATE TABLE country (
countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(50) not null,
UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;
insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");
CREATE TABLE city (
cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
countryId int(10) unsigned not null,
city varchar(50) not null,
hasAirport boolean not null default true,
UNIQUE KEY cityUIdx1 (countryId,city),
CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;
insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);
-- Gah. Left outer join is now effectively an inner join
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
;
-- Hooray! I can see Monaco again thanks to
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
;
As of Feb 2018, fetch()
can be cancelled with the code below on Chrome (read Using Readable Streams to enable Firefox support). No error is thrown for catch()
to pick up, and this is a temporary solution until AbortController
is fully adopted.
fetch('YOUR_CUSTOM_URL')
.then(response => {
if (!response.body) {
console.warn("ReadableStream is not yet supported in this browser. See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream")
return response;
}
// get reference to ReadableStream so we can cancel/abort this fetch request.
const responseReader = response.body.getReader();
startAbortSimulation(responseReader);
// Return a new Response object that implements a custom reader.
return new Response(new ReadableStream(new ReadableStreamConfig(responseReader)));
})
.then(response => response.blob())
.then(data => console.log('Download ended. Bytes downloaded:', data.size))
.catch(error => console.error('Error during fetch()', error))
// Here's an example of how to abort request once fetch() starts
function startAbortSimulation(responseReader) {
// abort fetch() after 50ms
setTimeout(function() {
console.log('aborting fetch()...');
responseReader.cancel()
.then(function() {
console.log('fetch() aborted');
})
},50)
}
// ReadableStream constructor requires custom implementation of start() method
function ReadableStreamConfig(reader) {
return {
start(controller) {
read();
function read() {
reader.read().then(({done,value}) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
read();
})
}
}
}
}
If you know the number of levels in nested arrays you can simply do nested loops. Like so:
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}
if you do not know the depth of array you need to use recursion. See example below:
// Multi-dementional Source Array
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(
7,
8,
array("four", 9, 10)
))
);
// Output array
displayArrayRecursively($tmpArray);
/**
* Recursive function to display members of array with indentation
*
* @param array $arr Array to process
* @param string $indent indentation string
*/
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
//
displayArrayRecursively($value, $indent . '--');
} else {
// Output
echo "$indent $value \n";
}
}
}
}
The code below with display only nested array with values for your specific case (3rd level only)
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(7, 8, 9))
);
// Scan through outer loop
foreach ($tmpArray as $inner) {
// Check type
if (is_array($inner)) {
// Scan through inner loop
foreach ($inner[1] as $value) {
echo "$value \n";
}
}
}
You might like to consider ADO - a worksheet or range can be used as a table.
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName
''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns, note also that you will need a different connection
''string for >=2007
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
rs.Open "Select * from [Sheet1$]", cn, adOpenStatic, adLockOptimistic
If Not rs.EOF Then
rs.MoveFirst
rs.Save "C:\Docs\Table1.xml", adPersistXML
End If
rs.Close
cn.Close
Here is a better implementation of an "every 10th item" list comprehension, that does not use the list contents as part of the membership test:
>>> l = range(165)
>>> [ item for i,item in enumerate(l) if i%10==0 ]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
>>> l = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> [ item for i,item in enumerate(l) if i%10==0 ]
['A', 'K', 'U']
But this is still far slower than just using list slicing.
If you don't have ReSharper installed and still want to use the shortcut Shift
+Alt
+L
to move focus to the current file in Solution Explorer in Visual Studio 2013 then please follow these steps:
In the Show commands containing box type "solutionexplorer" and then in the list below look for the SyncWithActiveDocument command:
Click in textbox under "Press short keys" label and press: Shift
+Alt
+L
and click the Assign button and you are done:
To verify open any file in Visual Studio and press the shortcut keys Shift
+Alt
+L
and you'll see the file in the solution explorer. Enjoy!
For Ubuntu 18.04 installnasm
. Open the terminal and type:
sudo apt install as31 nasm
nasm docs
For compiling and running:
nasm -f elf64 example.asm # assemble the program
ld -s -o example example.o # link the object file nasm produced into an executable file
./example # example is an executable file
I tried all of the above suggestions, which did not work for me, but I found how to fix the error in my case.
The following steps made the project compile succesfully:
In project explorer, right-click on project, select “properties” In the tree on the right, go to Java build path. Select the tab “libraries”. Click “Add library”. Select JRE system library. Click next. Select radio button Alternate JRE. Click “installed JRE’s”. Select the JRE with the right version. Click Appy and close. In the next screen, click finish. In the properties window, click Apply and close. In the project explorer, right-click your pom.xml and select run as > maven build In the goal textbox, write “install”. Click Run.
This made the project build succesfully in my case.
KILL ALL SELECT QUERIES
select concat('KILL ',id,';')
from information_schema.processlist
where user='root'
and INFO like 'SELECT%' into outfile '/tmp/a.txt';
source /tmp/a.txt;
This has worked for me in the past and it will even expand environment variables in the file if it can.
for /F "delims=" %%a in (LogName.txt) do (
echo %%a>>MyDestination.txt
)
string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);
I'd use bootstrap and set the html as:
<div class="row">
<div class="col-md-4">
<img src="img/logo.png" alt="logo" />
</div>
<div class="col-md-8">
<h1>My website name</h1>
</div>
</div>
It must be at least 64 bits. Other than that it's implementation defined.
Strictly speaking, unsigned long long
isn't standard in C++ until the C++0x standard. unsigned long long
is a 'simple-type-specifier' for the type unsigned long long int
(so they're synonyms).
The long long
set of types is also in C99 and was a common extension to C++ compilers even before being standardized.
another bit of code here:
refer: https://github.com/stvnthomas/CodeIgniter-Multi-Upload
If you're using mariadb, you have to modify the mariadb.cnf file located in /etc/mysql/conf.d/.
I supposed the stuff is the same for any other my-sql based solutions.
Extending the int class and overriding __lt__ is one of the ways.
import queue
class MyInt(int):
def __lt__(self, other):
return self > other
def main():
q = queue.PriorityQueue()
q.put(MyInt(10))
q.put(MyInt(5))
q.put(MyInt(1))
while not q.empty():
print (q.get())
if __name__ == "__main__":
main()
It's a "pointer to member" - the following code illustrates its use:
#include <iostream>
using namespace std;
class Car
{
public:
int speed;
};
int main()
{
int Car::*pSpeed = &Car::speed;
Car c1;
c1.speed = 1; // direct access
cout << "speed is " << c1.speed << endl;
c1.*pSpeed = 2; // access via pointer to member
cout << "speed is " << c1.speed << endl;
return 0;
}
As to why you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I've never had to use them in my own code.
Edit: I can't think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try - an Apply function that would do some pre &post processing before applying a user-selected member function to an object:
void Apply( SomeClass * c, void (SomeClass::*func)() ) {
// do hefty pre-call processing
(c->*func)(); // call user specified function
// do hefty post-call processing
}
The parentheses around c->*func
are necessary because the ->*
operator has lower precedence than the function call operator.
You can do:
<form name="loginform" novalidate ng-submit="loginform.$valid && login.submit()">
No need for controller checks.
I have solved it this way.
Go to your project file let's say project/name/bin and delete everything within the bin folder. (this will then give you another error which you can solve this way)
then in your visual studio right click project's References folder, to open NuGet Package Manager.
Go to browse and install "DotNetCompilerPlatform".
You can also remove dead
containers with this command
docker rm $(docker ps --all -q -f status=dead)
But, I'm really not sure why & how the dead
containers are created. This error seems related https://github.com/typesafehub/mesos-spark-integration-tests/issues/34 whenever i get dead
containers
[Update] With Docker 1.13 update, we can easily remove both unwanted containers, dangling images
$ docker system df #will show used space, similar to the unix tool df
$ docker system prune # will remove all unused data.
You could use alias python="/usr/bin/python2.7"
:
bash-3.2$ alias
bash-3.2$ python
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
bash-3.2$ alias python="/usr/bin/python3.3"
bash-3.2$ python
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.
This caused the app pool to give up and reply with the exception noted in the question.
Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).
If it suits anyone, here are some brief guidelines for adding environment variables permanently.
vi ~/.bash_profile
Add the variables to the file:
export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11
Immediately apply all changes:
source ~/.bash_profile
Two remarks
do 4 steps sequential:
git submodule foreach git reset --hard HEAD
git submodule update
git submodule foreach "git checkout master; git pull"
git submodule foreach git clean -f
As well as the more general memory management techniques given in the answers above, I always try to reduce the size of my objects as far as possible. For example, I work with very large but very sparse matrices, in other words matrices where most values are zero. Using the 'Matrix' package (capitalisation important) I was able to reduce my average object sizes from ~2GB to ~200MB as simply as:
my.matrix <- Matrix(my.matrix)
The Matrix package includes data formats that can be used exactly like a regular matrix (no need to change your other code) but are able to store sparse data much more efficiently, whether loaded into memory or saved to disk.
Additionally, the raw files I receive are in 'long' format where each data point has variables x, y, z, i
. Much more efficient to transform the data into an x * y * z
dimension array with only variable i
.
Know your data and use a bit of common sense.
If you are using anaconda to go into python environment you should have build up different environment for different python version
The following scripts may help you build up a new environment(running in anaconda prompt)
conda create -n py27 python=2.7 #for version 2.7
activate py27
conda create -n py36 python=3.6 #for version 3.6
activate py36
you may leave the environment back to your global env by typing
deactivate py27
or
deactivate py36
and then you can either switch to different environment using your anaconda UI with @Francisco Camargo 's answer
or you can stick to anaconda prompt using @Dan 's answer
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.
the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".
the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!
but did anyone think to "localhost" on any apache server for example www.apachefriends.org?
you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".
<?php
for($i=1;$i<50000;$i++){
print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>
<?php
?>
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause
Now if you pay attention closely ...
the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!
here i got :
c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software: Apache/2.4.33
Server Hostname: localhost
Server Port: 80
Document Path: /bench/void.php
Document Length: 0 bytes
Concurrency Level: 1
Time taken for tests: 11.219 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 2150000 bytes
HTML transferred: 0 bytes
Requests per second: 891.34 [#/sec] (mean)
Time per request: 1.122 [ms] (mean)
Time per request: 1.122 [ms] (mean, across all concurrent requests)
Transfer rate: 187.15 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 0 1 0.9 1 17
Waiting: 0 1 0.9 1 17
Total: 0 1 0.9 1 17
Percentage of the requests served within a certain time (ms)
50% 1
66% 1
75% 1
80% 1
90% 1
95% 2
98% 2
99% 3
100% 17 (longest request)
c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software: Apache/2.4.33
Server Hostname: localhost
Server Port: 80
Document Path: /bench/bench.php
Document Length: 1799964 bytes
Concurrency Level: 1
Time taken for tests: 177.006 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 18001600000 bytes
HTML transferred: 17999640000 bytes
Requests per second: 56.50 [#/sec] (mean)
Time per request: 17.701 [ms] (mean)
Time per request: 17.701 [ms] (mean, across all concurrent requests)
Transfer rate: 99317.00 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 12 17 3.2 17 90
Waiting: 0 1 1.1 1 26
Total: 13 18 3.2 18 90
Percentage of the requests served within a certain time (ms)
50% 18
66% 19
75% 19
80% 20
90% 21
95% 22
98% 23
99% 26
100% 90 (longest request)
c:\xampp\htdocs\bench>pause
Press any key to continue . . .
90-17= 73 the result i expect !
It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.
A string is a series of characters followed by a string terminator ('\0'
). An empty string (""
) consists of no characters followed by a single string terminator character - i.e. one character in total.
So I would try the following:
string[1] = ""
Note that this behaviour is not the emulated by strlen
, which does not count the terminator as part of the string length.
I think this code may be help you:
string str = char.ConvertFromUtf32(65)
Yes, it's possible, the syntax is curl [protocol://]<host>[:port]
, for example:
curl example.com:1234
If you're using Bash, you can also use pseudo-device /dev
files to open a TCP connection, e.g.:
exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.
See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).
111 means connection refused, which in turn means that your mysqld only listens to the localhost
interface.
To alter it you may want to look at the bind-address
value in the mysqld
section of your my.cnf
file.
I think you should $_POST[][], i tried it and it work :)), tks
Been looking into this for a while and not got any satisfactory answers, however...
1) ANSI escape sequences do work in a terminal on Linux
2) if you can tolerate a limited set of colo(u)rs try this:
print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")
In idle "hello" and "goodbye" are in blue and "error" is in red.
Not fantastic, but good enough for now, and easy!
You can also use serializeArray function to do the same.
Create a table with column as type json
CREATE TABLE friends ( id serial primary key, data jsonb);
Now let's insert json data
INSERT INTO friends(data) VALUES ('{"name": "Arya", "work": ["Improvements", "Office"], "available": true}');
INSERT INTO friends(data) VALUES ('{"name": "Tim Cook", "work": ["Cook", "ceo", "Play"], "uses": ["baseball", "laptop"], "available": false}');
Now let's make some queries to fetch data
select data->'name' from friends;
select data->'name' as name, data->'work' as work from friends;
You might have noticed that the results comes with inverted comma( " ) and brackets ([ ])
name | work
------------+----------------------------
"Arya" | ["Improvements", "Office"]
"Tim Cook" | ["Cook", "ceo", "Play"]
(2 rows)
Now to retrieve only the values just use ->>
select data->>'name' as name, data->'work'->>0 as work from friends;
select data->>'name' as name, data->'work'->>0 as work from friends where data->>'name'='Arya';
For a function type prop you can use the following code:
AddAddressComponent.defaultProps = {
callBackHandler: () => {}
};
AddAddressComponent.propTypes = {
callBackHandler: PropTypes.func,
};
A very easy way is to use jQuery and SimpleModal plugin. Then when I need to show my "loading" gif on submit, I do:
$('*').css('cursor','wait');
$.modal("<table style='white-space: nowrap'><tr><td style='white-space: nowrap'><b>Please wait...</b></td><td><img alt='Please wait' src='loader.gif' /></td></tr></table>", {escClose:false} );
Please explain your problem. You say:
But this involves adding character " to the string.
What problem is that? You can't type string foo = "Foo"bar"";
, because that'll invoke a compile error. As for the adding part, in string size terms that is not true:
@"""".Length == "\"".Length == 1
Actionbarsherlock has the support library in it. This probably causes a conflict if the support library is also in your main project.
Remove android-support-v4.jar
from your project's libs directory.
Also Remove android-support-v4.jar
from your second library and then try again.
Jar Mismatch Found 2 versions of android-support-v4.jar in the dependency list
If you are getting the user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
If you are not, you'll have to convert it to int
and catch a NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}
The most popular bootstrap date picker is currently: https://github.com/eternicode/bootstrap-datepicker (thanks to @dentarg for digging it up)
A simple instantiation only requires:
HTML
<input class="datepicker">
Javascript
$('.datepicker').datepicker();
See a simple example here https://jsfiddle.net/k6qsm5no/1/ or the full docs here http://bootstrap-datepicker.readthedocs.org/en/latest/
Assuming that you meant to state 'Class Diagram' instead of 'Project Hierarchy', I've used the following Eclipse plug-ins to generate Class Diagrams at various points in my professional career:
Obligatory links
The listed tools will not generate class diagrams from source code, or atleast when I used them quite a few years back. You can use them to handcraft class diagrams though.
Related questions on StackOverflow
Except for ObjectAid and a few other mentions, most of the Eclipse plug-ins mentioned in the listed questions may no longer be available, or would work only against older versions of Eclipse.
You are correct about the action used in Intent but it's not the only thing you have to do. You'll also have to add
startActivityForResult(intent, YOUR_REQUEST_CODE);
To get it all done and retrieve the actual picture you could check the following thread.
Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.
button = $('.status-button a', whatever);
if(button.hasClass('close')) {
button.delay(10000).queue(function() {
$(this).click().dequeue();
});
}
The most effective way to do it without repeating your code is use of HAVING instead of WHERE
SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
HAVING daysdiff > 120
I am using 0.56RC secureTextEntry={true} Along with password={true} then only its working as mentioned by @NicholasByDesign
Think your should look around: datetime.astimezone()
http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
Also see pytz module - it's quite easy to use -- as example:
eastern = timezone('US/Eastern')
Example:
from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal
utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00
I had an issue with centering a popup window in the external monitor and window.screenX and window.screenY were negative values (-1920, -1200) respectively. I have tried all the above of the suggested solutions and they worked well in primary monitors. I wanted to leave
Here is what worked for me:
function createPopupWindow(url) {
var height = screen.height;
var width = screen.width;
var left, top, win;
if (width > 1050) {
width = width - 200;
} else {
width = 850;
}
if (height > 850) {
height = height - 150;
} else {
height = 700;
}
if (window.screenX < 0) {
left = (window.screenX - width) / 2;
} else {
left = (screen.width - width) / 2;
}
if (window.screenY < 0) {
top = (window.screenY + height) / 4;
} else {
top = (screen.height - height) / 4;
}
win=window.open( url,"myTarget", "width="+width+", height="+height+",left="+left+",top="+top+"menubar=no, status=no, location=no, resizable=yes, scrollbars=yes");
if (win.focus) {
win.focus();
}
}
May be it's not the same for Sql Srver but for people using oracle and eclipslink it's working for me
ex: a procedure that have one IN param (type CHAR) and two OUT params (NUMBER & VARCHAR)
in the persistence.xml declare the persistence-unit :
<persistence-unit name="presistanceNameOfProc" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/DataSourceName</jta-data-source>
<mapping-file>META-INF/eclipselink-orm.xml</mapping-file>
<properties>
<property name="eclipselink.logging.level" value="FINEST"/>
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.weaving" value="static"/>
<property name="eclipselink.ddl.table-creation-suffix" value="JPA_STORED_PROC" />
</properties>
</persistence-unit>
and declare the structure of the proc in the eclipselink-orm.xml
<?xml version="1.0" encoding="UTF-8"?><entity-mappings version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd">
<named-stored-procedure-query name="PERSIST_PROC_NAME" procedure-name="name_of_proc" returns-result-set="false">
<parameter direction="IN" name="in_param_char" query-parameter="in_param_char" type="Character"/>
<parameter direction="OUT" name="out_param_int" query-parameter="out_param_int" type="Integer"/>
<parameter direction="OUT" name="out_param_varchar" query-parameter="out_param_varchar" type="String"/>
</named-stored-procedure-query>
in the code you just have to call your proc like this :
try {
final Query query = this.entityManager
.createNamedQuery("PERSIST_PROC_NAME");
query.setParameter("in_param_char", 'V');
resultQuery = (Object[]) query.getSingleResult();
} catch (final Exception ex) {
LOGGER.log(ex);
throw new TechnicalException(ex);
}
to get the two output params :
Integer myInt = (Integer) resultQuery[0];
String myStr = (String) resultQuery[1];
Use a Timer to handle the message and automatic cancellation. When the Task completes, call Dispose on the timers so that they will never fire. Here is an example; change taskDelay to 500, 1500, or 2500 to see the different cases:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private static Task CreateTaskWithTimeout(
int xDelay, int yDelay, int taskDelay)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Factory.StartNew(() =>
{
// Do some work, but fail if cancellation was requested
token.WaitHandle.WaitOne(taskDelay);
token.ThrowIfCancellationRequested();
Console.WriteLine("Task complete");
});
var messageTimer = new Timer(state =>
{
// Display message at first timeout
Console.WriteLine("X milliseconds elapsed");
}, null, xDelay, -1);
var cancelTimer = new Timer(state =>
{
// Display message and cancel task at second timeout
Console.WriteLine("Y milliseconds elapsed");
cts.Cancel();
}
, null, yDelay, -1);
task.ContinueWith(t =>
{
// Dispose the timers when the task completes
// This will prevent the message from being displayed
// if the task completes before the timeout
messageTimer.Dispose();
cancelTimer.Dispose();
});
return task;
}
static void Main(string[] args)
{
var task = CreateTaskWithTimeout(1000, 2000, 2500);
// The task has been started and will display a message after
// one timeout and then cancel itself after the second
// You can add continuations to the task
// or wait for the result as needed
try
{
task.Wait();
Console.WriteLine("Done waiting for task");
}
catch (AggregateException ex)
{
Console.WriteLine("Error waiting for task:");
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine(e);
}
}
}
}
}
Also, the Async CTP provides a TaskEx.Delay method that will wrap the timers in tasks for you. This can give you more control to do things like set the TaskScheduler for the continuation when the Timer fires.
private static Task CreateTaskWithTimeout(
int xDelay, int yDelay, int taskDelay)
{
var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Factory.StartNew(() =>
{
// Do some work, but fail if cancellation was requested
token.WaitHandle.WaitOne(taskDelay);
token.ThrowIfCancellationRequested();
Console.WriteLine("Task complete");
});
var timerCts = new CancellationTokenSource();
var messageTask = TaskEx.Delay(xDelay, timerCts.Token);
messageTask.ContinueWith(t =>
{
// Display message at first timeout
Console.WriteLine("X milliseconds elapsed");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
var cancelTask = TaskEx.Delay(yDelay, timerCts.Token);
cancelTask.ContinueWith(t =>
{
// Display message and cancel task at second timeout
Console.WriteLine("Y milliseconds elapsed");
cts.Cancel();
}, TaskContinuationOptions.OnlyOnRanToCompletion);
task.ContinueWith(t =>
{
timerCts.Cancel();
});
return task;
}
Here's an example that let's you set the color of the background. If you don't want to use float, then you might need to set the width and height manually. But even that really depends on the surrounding CSS/HTML.
<style>
#color {
background-color: red;
float: left;
}#opacity {
opacity : 0.4;
filter: alpha(opacity=40);
}
</style>
<div id="color">
<div id="opacity">
<img src="image.jpg" />
</div>
</div>
If it's a matter of just opening PDF to send some keys to it then why not try this
Sub Sample()
ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub
I am assuming that you have some pdf reader installed.
I had also the ADT Bundle that had the HTTP as update url. Changing it to HTTPS solved the problem for me.
Two and a half years late is better than never, right?
int System.in.read()
reads the next byte of data from the input stream. But I am sure you already knew that, because it is trivial to look up. So, what you are probably asking is:
Why is it declared to return an int
when the documentation says that it reads a byte
?
and why does it appear to return garbage? (I type '9'
, but it returns 57
.)
It returns an int
because besides all the possible values of a byte, it also needs to be able to return an extra value to indicate end-of-stream. So, it has to return a type which can express more values than a byte
can.
Note: They could have made it a short
, but they opted for int
instead, possibly as a tip of the hat of historical significance to C, whose getc()
function also returns an int
, but more importantly because short
is a bit cumbersome to work with, (the language offers no means of specifying a short
literal, so you have to specify an int
literal and cast it to short
,) plus on certain architectures int
has better performance than short
.
It appears to return garbage because when you view a character as an integer, what you are looking at is the ASCII(*) value of that character. So, a '9' appears as a 57. But if you cast it to a character, you get '9', so all is well.
Think of it this way: if you typed the character '9' it is nonsensical to expect System.in.read()
to return the number 9, because then what number would you expect it to return if you had typed an 'a'
? Obviously, characters must be mapped to numbers. ASCII(*) is a system of mapping characters to numbers. And in this system, character '9' maps to number 57, not number 9.
(*) Not necessarily ASCII; it may be some other encoding, like UTF-16; but in the vast majority of encodings, and certainly in all popular encodings, the first 127 values are the same as ASCII. And this includes all english alphanumeric characters and popular symbols.
robotex tools which are free will let you do this but they make you enter the ip of the domain first:
The git solution for such scenarios is setting SKIP-WORKTREE BIT. Run only the following command:
git update-index --skip-worktree .classpath .gitignore
It is used when you want git to ignore changes of files that are already managed by git and exist on the index. This is a common use case for config files.
Running git rm --cached
doesn't work for the scenario mentioned in the question. If I simplify the question, it says:
How to have
.classpath
and.project
on the repo while each one can change it locally and git ignores this change?
As I commented under the accepted answer, the drawback of git rm --cached
is that it causes a change in the index, so you need to commit the change and then push it to the remote repository. As a result, .classpath
and .project
won't be available on the repo while the PO wants them to be there so anyone that clones the repo for the first time, they can use it.
Based on git documentaion:
Skip-worktree bit can be defined in one (long) sentence: When reading an entry, if it is marked as skip-worktree, then Git pretends its working directory version is up to date and read the index version instead. Although this bit looks similar to assume-unchanged bit, its goal is different from assume-unchanged bit’s. Skip-worktree also takes precedence over assume-unchanged bit when both are set.
More details is available here.
For the same solution I was looking for Angularjs directive with ng-Model
.
Here is the code that resolve the problem.
myApp.directive('zipcodeformatter', function () {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function (v) {
if (v) {
console.log('value changed, new value is: ' + v + ' ' + v.length);
if (v.length > 5) {
var newzip = v.replace("-", '');
var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
element.val(str);
} else {
element.val(v);
}
}
});
}
};
});
HTML DOM
<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">
My Result is:
92108-2223
When you define a as unicode, the chars a and á are equal. Otherwise á counts as two chars. Try len(a) and len(au). In addition to that, you may need to have the encoding when you work with other environments. For example if you use md5, you get different values for a and ua
Be careful while working with android contact list.
Reading contact list in above methods work on most android devices except HTC One and Sony Xperia. It wasted my six weeks trying to figure out what is wrong!
Most tutorials available online are almost similar - first read "ALL" contacts, then show in Listview
with ArrayAdapter
. This is not memory efficient solution. Instead of looking for solutions on other websites first, have a look at developer.android.com. If any solution is not available on developer.android.com you should look somewhere else.
The solution is to use CursorAdapter
instead of ArrayAdapter
for retrieving contact list. Using ArrayAdapter
would work on most devices, but it's not efficient. The CursorAdapter
retrieves only a portion of contact list at run time while the ListView
is being scrolled.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
// Gets the ListView from the View list of the parent activity
mContactsList =
(ListView) getActivity().findViewById(R.layout.contact_list_view);
// Gets a CursorAdapter
mCursorAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.contact_list_item,
null,
FROM_COLUMNS, TO_IDS,
0);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
}
Retrieving a List of Contacts: Retrieving a List of Contacts
The trick is to show/dismiss the dialog within AsyncTask during onPreExecute/onPostExecute as usual, though in case of orientation-change create/show a new instance of the dialog in the activity and pass its reference to the task.
public class MainActivity extends Activity {
private Button mButton;
private MyTask mTask = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyTask task = (MyTask) getLastNonConfigurationInstance();
if(task != null){
mTask = task;
mTask.mContext = this;
mTask.mDialog = ProgressDialog.show(this, "", "", true);
}
mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mTask = new MyTask(MainActivity.this);
mTask.execute();
}
});
}
@Override
public Object onRetainNonConfigurationInstance() {
String str = "null";
if(mTask != null){
str = mTask.toString();
mTask.mDialog.dismiss();
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
return mTask;
}
private class MyTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog mDialog;
private MainActivity mContext;
public MyTask(MainActivity context){
super();
mContext = context;
}
protected void onPreExecute() {
mDialog = ProgressDialog.show(MainActivity.this, "", "", true);
}
protected void onPostExecute(Void result) {
mContext.mTask = null;
mDialog.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
SystemClock.sleep(5000);
return null;
}
}
}
You have to change delimiter before using triggers, stored procedures and so on.
delimiter //
create procedure ProG()
begin
SELECT * FROM hs_hr_employee_leave_quota;
end;//
delimiter ;
Step by step solution:
Change directory to directory of the keytool file location. Change directory by using command cd <directory path>
. (Note: if any directory name has space then add \ between the two words. Example cd /Applications/Android\ Studio.app//Contents/jre/jdk/Contents/Home/bin/
)
To find the location of your keytool, you go to android studio..open your project. And go to
File>project Structure>SDK location..and find JDK location.
Run the keytool by this command:
keytool -list -v –keystore <your jks file path>
(Note: if any directory name has space then add \ between the two words. example
keytool -list -v -keystore /Users/username/Desktop/tasmiah\ mobile/v3/jordanos.jks
)
Command prompt you to key in the password.. so key in your password.. then you get the result
Making use of JavaScripts short-circuit evaluation. If el.shouldBeProcessed
returns true, doSomeLengthyOperation
elementsCollection.forEach( el =>
el.shouldBeProcessed && doSomeLengthyOperation()
);
You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().
http://www.php.net/manual/en/reflectionclass.getdoccomment.php
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;
// or with parent element:
$foo = simplexml_load_string(
'<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;
You might have better luck with LIBXML_NOCDATA
:
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
, null
, LIBXML_NOCDATA
);
git rebase -i
allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.
# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`
# switch to a new branch pointing at the first commit
git checkout -b new-root root
# make any edits and then commit them with:
git commit --amend
# check out the previous branch (i.e. master)
git checkout @{-1}
# replace old root with amended version
git rebase --onto new-root root
# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue
# delete the branch "new-root"
git branch -d new-root
# delete the tag "root"
git tag -d root
UPDATE 2 (2020-03-16)
The newer Android Studio version changed the location of this button. Now if you want to see the layout design preview you will need to press one of the buttons at the top right of your xml. The button that looks like an image icon will open the design dashboard, while the button next to it will open the split view where the design is placed next to the XML code:
ORIGINAL (2013-05-21)
You should have a Design
button next to the Text
button under the xml text editor:
Or you can use the Preview
button in the upper right corner to add a preview window next to the XML code:
UPDATE:
If you dont have it, then do this: View
-> Tool Windows
-> Preview
Here I am sharing code that can load image in form of bitmap from and save that image on sdcard gallery in app name folder. You should follow these steps
private Bitmap loadBitmap(String url) {
try {
InputStream in = new java.net.URL(url).openStream();
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
void saveMyImage(String appName, String imageUrl, String imageName) {
Bitmap bmImg = loadBitmap(imageUrl);
File filename;
try {
String path1 = android.os.Environment.getExternalStorageDirectory()
.toString();
File file = new File(path1 + "/" + appName);
if (!file.exists())
file.mkdirs();
filename = new File(file.getAbsolutePath() + "/" + imageName
+ ".jpg");
FileOutputStream out = new FileOutputStream(filename);
bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
ContentValues image = new ContentValues();
image.put(Images.Media.TITLE, appName);
image.put(Images.Media.DISPLAY_NAME, imageName);
image.put(Images.Media.DESCRIPTION, "App Image");
image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
image.put(Images.Media.MIME_TYPE, "image/jpg");
image.put(Images.Media.ORIENTATION, 0);
File parent = filename.getParentFile();
image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
.toLowerCase().hashCode());
image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
.toLowerCase());
image.put(Images.Media.SIZE, filename.length());
image.put(Images.Media.DATA, filename.getAbsolutePath());
Uri result = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
Toast.makeText(getApplicationContext(),
"File is Saved in " + filename, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
This was just asked a couple of days ago (but I cannot find it):
>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]
It might be better to use set
s from the beginning, depending on the context. Then you can use set operations like other answers show.
However, converting lists to sets and back only for these operations is slower than list comprehension.
There is another way.
Given that you write your own Index
class and a static method that returns an Iterable
over instances of this class you can
for (Index<String> each: With.index(stringArray)) {
each.value;
each.index;
...
}
Where the implementation of With.index
is something like
class With {
public static <T> Iterable<Index<T>> index(final T[] array) {
return new Iterable<Index<T>>() {
public Iterator<Index<T>> iterator() {
return new Iterator<Index<T>>() {
index = 0;
public boolean hasNext() { return index < array.size }
public Index<T> next() { return new Index(array[index], index++); }
...
}
}
}
}
}
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
JavaScript is now evolving and growing it has now good and best even efficient way to check it
Here are some easy ways to check if object has a particular property:
hasOwnProperty()
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
in
const hero = {
name: 'Batman'
};
'name' in hero; // => true
'realName' in hero; // => false
undefined
keywordconst hero = {
name: 'Batman'
};
hero.name; // => 'Batman'
hero.realName; // => undefined
// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)
For more information, check here.
You want the mod operator.
The expression a Mod b is equivalent to the following formula:
a - (b * (a \ b))
Edited to add:
There are some special cases you may have to consider, because Excel is using floating point math (and returns a float
), which the VBA function returns an integer. Because of this, using mod
with floating-point numbers may require extra attention:
Excel's results may not correspond exactly with what you would predict; this is covered briefly here (see topmost answer) and at great length here.
As @André points out in the comments, negative numbers may round in the opposite direction from what you expect. The Fix()
function he suggests is explained here (MSDN).
Try this character set:
[ \t]
This does only match a space or a tabulator.
When dealing with a database record, I like to initialize all empty values with 0, using the migration helper:
add_column :products, :price, :integer, default: 0
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
The following lines will do the trick:
ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True
Edit: The .Calculate()
method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the .CalculateFull()
method, but it may work.
The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.
The equivalent of DateTime.Now
in Joda Time is:
DateTime dt = new DateTime();
Update
As noted in the comments, the latest versions of Joda Time have a DateTime.now()
method, so:
DateTime dt = DateTime.now();
I've had the same problem twice already and the easiest and most concise solution that I found is located here (in MSDN Blogs -> Games for Windows and the DirectX SDK). However, just in case that page goes down, here's the method:
Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:
MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
Install the DirectX SDK (June 2010)
Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB 2565063 with a security fix.
Note: This issue does not affect earlier version of the DirectX SDK which deploy the VS 2005 / VS 2008 CRT REDIST and do not deploy the VS 2010 CRT REDIST. This issue does not affect the DirectX End-User Runtime web or stand-alone installer as those packages do not deploy any version of the VC++ CRT.
File Checksum Integrity Verifier: This of course assumes you actually have an uncorrupted copy of the DirectX SDK setup package. The best way to validate this it to run
fciv -sha1 DXSDK_Jun10.exe
and verify you get
8fe98c00fde0f524760bb9021f438bd7d9304a69 dxsdk_jun10.exe
You have to edit the eclipse.ini file to have an entry similar to this:
C:\Java\JDK\1.5\bin\javaw.exe (your location of java executable)
-vmargs
-Xms64m (based on you memory requirements)
-Xmx1028m
Also remember that in eclipse.ini, anything meant for Eclipse should be before the -vmargs
line and anything for JVM should be after the -vmargs
line.
Just use the following code in your javaScript:
if(new Date(hireDate).getTime() > new Date().getTime())
{
//Date greater than today's date
}
Change the condition according to your requirement.Here is one link for comparision compare in java script
make sure you have added this dependency in your pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
It's a unicode character. In this case \u003C
and \u003E
mean :
U+003C < Less-than sign
U+003E > Greater-than sign
See a list here
As of today (2015, Aug., 1st), Apache2
in Debian Jessie
, you need to edit:
root@host:/etc/apache2/mods-enabled$ vi dir.conf
And change the order of that line, bringing index.php to the first position:
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)
Edited to show a possibility not mentioned here, because my original answer was far from related to the OP's question.
preg_match(); Is possible to use. However, in most applications it will be much more heavy to use than other answers here.
if (preg_match("/true/i", "true PHP is a web scripting language of choice.")) {
echo "<br><br>Returned true";
} else {
echo "<br><br>Returned False";
}
/(?:true)|(?:1)/i
Can also be used if needed in certain situations. It will not return correctly when it evaluates a string containing both "false" and "1".
I have had a difficulty with the EF when the connection the server is stopped or paused, and I raised the same question. So for completeness to the above answers here is the code.
/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
Eclipse will give this error if you don't have call to super class constructor as a first statement in subclass constructor.
Binding refers to the link between method call and method definition.
This picture clearly shows what is binding.
In this picture, “a1.methodOne()” call is binding to corresponding methodOne() definition and “a1.methodTwo()” call is binding to corresponding methodTwo() definition.
For every method call there should be proper method definition. This is a rule in java. If compiler does not see the proper method definition for every method call, it throws error.
Now, come to static binding and dynamic binding in java.
Static Binding In Java :
Static binding is a binding which happens during compilation. It is also called early binding because binding happens before a program actually runs
.
Static binding can be demonstrated like in the below picture.
In this picture, ‘a1’ is a reference variable of type Class A pointing to object of class A. ‘a2’ is also reference variable of type class A but pointing to object of Class B.
During compilation, while binding, compiler does not check the type of object to which a particular reference variable is pointing. It just checks the type of reference variable through which a method is called and checks whether there exist a method definition for it in that type.
For example, for “a1.method()” method call in the above picture, compiler checks whether there exist method definition for method() in Class A. Because ‘a1' is Class A type. Similarly, for “a2.method()” method call, it checks whether there exist method definition for method() in Class A. Because ‘a2' is also Class A type. It does not check to which object, ‘a1’ and ‘a2’ are pointing. This type of binding is called static binding.
Dynamic Binding In Java :
Dynamic binding is a binding which happens during run time. It is also called late binding because binding happens when program actually is running.
During run time actual objects are used for binding. For example, for “a1.method()” call in the above picture, method() of actual object to which ‘a1’ is pointing will be called. For “a2.method()” call, method() of actual object to which ‘a2’ is pointing will be called. This type of binding is called dynamic binding.
The dynamic binding of above example can be demonstrated like below.
JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.
As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s)
then you lose the ability to recover dictionaries).
A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:
from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle
class PythonObjectEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
return JSONEncoder.default(self, obj)
return {'_python_object': pickle.dumps(obj)}
def as_python_object(dct):
if '_python_object' in dct:
return pickle.loads(str(dct['_python_object']))
return dct
Here is a sample session showing that it can handle lists, dicts, and sets:
>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]
>>> j = dumps(data, cls=PythonObjectEncoder)
>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]
Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.
Does "pure HTML/CSS" exclude the use of tables? Because they will easily do what you want:
<table>
<tr>
<td valign="top"><img src="myImage.jpg" alt="" /></td>
<td valign="middle">This is my text!</td>
</tr>
</table>
Flame me all you like, but that works (and works in old, janky browsers).
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
A data.table
approach
library(data.table)
DT <- data.table(myvec)
DT[, .(number_of_distinct_orders = length(unique(order_no))), by = name]
data.table
v >= 1.9.5 has a built in uniqueN
function now
DT[, .(number_of_distinct_orders = uniqueN(order_no)), by = name]
Something we've starting doing at work is the ActiveSupport Ordered Hash
Which allows you to define your configuration cleanly inside the environment files e.g.
config.service = ActiveSupport::OrderedOptions.new
config.service.api_key = ENV['SERVICE_API_KEY']
config.service.shared_secret = ENV['SERVICE_SHARED_SECRET']
You have more going on than you said. I ran the following expanded test from your example:
public class test {
public static void main(String[] args) {
Object[][] someArray = new Object[5][];
someArray[0] = new Object[10];
someArray[1] = null;
someArray[2] = new Object[1];
someArray[3] = null;
someArray[4] = new Object[5];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i] != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
}
}
}
and got the expected output:
$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null
Are you possibly trying to check the lengths of someArray[index]?
A tad late, but here goes.
How about http://wiki.apache.org/tomcat/UsingPhp if you just want to run the real php on tomcat.
Concerning running tomcat on port 80 there's always jsvc, just google jsvc + tomcat.
If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years
" demo , and hit view source:
$("#restricting").datepicker({
yearRange: "-20:+0", // this is the option you're looking for
showOn: "both",
buttonImage: "templates/images/calendar.gif",
buttonImageOnly: true
});
You'll want to do the same (obviously changing -20
to -100
or something).
Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.
This exception is because your JDK/Java version need to be updated/installed.
Note: The below answer is out of date since the Chrome disk cache format has changed.
Joachim Metz provides some documentation of the Chrome cache file format with references to further information.
For my use case, I only needed a list of cached URLs and their respective timestamps. I wrote a Python script to get these by parsing the data_* files under C:\Users\me\AppData\Local\Google\Chrome\User Data\Default\Cache\
:
import datetime
with open('data_1', 'rb') as datafile:
data = datafile.read()
for ptr in range(len(data)):
fourBytes = data[ptr : ptr + 4]
if fourBytes == b'http':
# Found the string 'http'. Hopefully this is a Cache Entry
endUrl = data.index(b'\x00', ptr)
urlBytes = data[ptr : endUrl]
try:
url = urlBytes.decode('utf-8')
except:
continue
# Extract the corresponding timestamp
try:
timeBytes = data[ptr - 72 : ptr - 64]
timeInt = int.from_bytes(timeBytes, byteorder='little')
secondsSince1601 = timeInt / 1000000
jan1601 = datetime.datetime(1601, 1, 1, 0, 0, 0)
timeStamp = jan1601 + datetime.timedelta(seconds=secondsSince1601)
except:
continue
print('{} {}'.format(str(timeStamp)[:19], url))
Declare extern int x;
in file.h.
And define int x;
only in one cpp file.cpp.
Try to use Catalano Framework.
Keypoints:
The Catalano Framework is a framework for scientific computing for Java and Android. The project started as an initial port of the many features of the AForge.NET and Accord.NET frameworks for .NET, but is steadily growing with more advanced features which are now being shared between those projects.
Example:
FastBitmap fb = new FastBitmap(bitmap);
Grayscale g = new Grayscale();
g.applyInPlace(fb);
Threshold t = new Threshold(120);
t.applyInPlace(fb);
bitmap = fb.toBitmap();
//Show the result
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
If you want to make an empty data frame and add contents in a loop, the following may help:
# Number of students in class
student.count <- 36
# Gather data about the students
student.age <- sample(14:17, size = student.count, replace = TRUE)
student.gender <- sample(c('male', 'female'), size = student.count, replace = TRUE)
student.marks <- sample(46:97, size = student.count, replace = TRUE)
# Create empty data frame
student.data <- data.frame()
# Populate the data frame using a for loop
for (i in 1 : student.count) {
# Get the row data
age <- student.age[i]
gender <- student.gender[i]
marks <- student.marks[i]
# Populate the row
new.row <- data.frame(age = age, gender = gender, marks = marks)
# Add the row
student.data <- rbind(student.data, new.row)
}
# Print the data frame
student.data
Hope it helps :)
In addition to Jesse Glick answer, if you want to pass string parameter then use:
build job: 'your-job-name',
parameters: [
string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
]
All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.
Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row
For i = 2 To lastA
compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
If IsError(compare) Then
Range("A" & i).Interior.ColorIndex = 3
End If
Next i
End Sub
You can use a ternary operator
echo false ? 'true' : 'false';
Create a new php.ini file with your desired settings and upload it to public_html folder of your Godaddy Hosting Account.
By default, Godaddy doesn't allow to edit it's existing php.ini file. However, you can always upload your own copy of your php.ini file with your own settings.
Below is an example of a simple php.ini file with some custom values:
max_execution_time 600
memory_limit 128M
post_max_size 32M
upload_max_filesize 32M
Next to the maybe useful, but maybe too symptomatic answers, here is one which tries to help to find the cause of the problem.
Maven is a command-line java tool. That means, it is not a standalone binary, it is a collection of java .jar
s, interpreted by a jvm (java.exe
on windows, java
on linux).
The mvn
command, is a script. On windows, it is a script called mvn.cmd
and on linux, it is a shell script. Thus, if you write: mvn install
, what will happen:
/bin/sh
or cmd.exe
) is called for the actual invoking scriptThe problem is with (2). Fortunately, this script is simply, very simple. For a java programmer it shouldn't be a big trouble to debug a script around 20 lines, even if it is a little bit alien language.
On linux, you can debug shellscripts giving the -x
flag to your shell interpreter (which is most probably bash
). On windows, you have to find some other way to debug a cmd.exe
script. So, instead of mvn install
, give the command bash -x mvn install
.
The result be like:
+ '[' -z '' ']'
+ '[' -f /etc/mavenrc ']'
+ '[' -f /home/picsa/.mavenrc ']'
+ cygwin=true
+ darwin=false
...not so many things...
+ MAVEN_PROJECTBASEDIR='C:\peter\bin'
+ export MAVEN_PROJECTBASEDIR
+ MAVEN_CMD_LINE_ARGS=' '
+ export MAVEN_CMD_LINE_ARGS
+ exec '/cygdrive/c/Program Files/Java/jdk1.8.0_66/bin/java' -classpath 'C:\peter/boot/plexus-classworlds-*.jar' '-Dclassworlds.conf=C:\peter/bin/m2.conf' '-Dmaven.home=C:\peter' '-Dmaven.multiModuleProjectDirectory=C:\peter\bin' org.codehaus.plexus.classworlds.launcher.Launcher
Fehler: Hauptklasse org.codehaus.plexus.classworlds.launcher.Launcher konnte nicht gefunden oder geladen werden
At the end, you can easily test, which environment variable gone bad, and you can very easily fix your script (or set it what is needed).
Use PHP_EOL
which outputs \r\n
or \n
depending on the OS.
in mysql if you take VARCHAR
then change it to TEXT
bcoz its size is 65,535
and if you can already take TEXT
the change it with LONGTEXT
only if u need more then 65,535
.
total size of LONGTEXT
is 4,294,967,295
characters
- Each time you append or do any modification with it, it creates a new String
object.
- So use append()
method of StringBuilder
(If thread safety is not important), else use StringBuffer
(If thread safety is important.), that will be efficient way to do it.
Try git rm -r --cached .idea
in your terminal. It disables the change tracking.
You can delete the index by Kibana Console:
To get all index:
GET /_cat/indices?v
To delete a specific index:
DELETE /INDEX_NAME_TO_DELETE
Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)
Below is the function to change the URL without reloading the page. It is only supported for HTML5.
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = {Page: page, Url: url};
history.pushState(obj, obj.Page, obj.Url);
} else {
window.location.href = "homePage";
// alert("Browser does not support HTML5.");
}
}
ChangeUrl('Page1', 'homePage');
The export default {...}
construction is just a shortcut for something like this:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { foo(); bar() }
}
export default funcs
It must become obvious now that there are no foo
, bar
or baz
functions in the module's scope. But there is an object named funcs
(though in reality it has no name) that contains these functions as its properties and which will become the module's default export.
So, to fix your code, re-write it without using the shortcut and refer to foo
and bar
as properties of funcs
:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { funcs.foo(); funcs.bar() } // here is the fix
}
export default funcs
Another option is to use this
keyword to refer to funcs
object without having to declare it explicitly, as @pawel has pointed out.
Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:
function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }
export default {foo, bar, baz}
And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:
// util.js
export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }
export default {foo, bar, baz}
// a.js, using default export
import util from './util'
util.foo()
// b.js, using named exports
import {bar} from './util'
bar()
Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util'
to get all named exports in one object.
You can try this as well, it is easy to implement
TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
Change the text to which standard time you want to change.
Use TimeZone
feature of C# to implement.
From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):
1.10 Empty Operator -
empty A
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false
So, considering the interfaces, it works on Collection
and Map
only. In your case, I think Collection
is the best option. Or, if it's a Javabean-like object, then Map
. Either way, under the covers, the isEmpty()
method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException
.
I think the solutions aren't correct 100% I would use ceil instead of floor, round will work but it isn't the right operation.
function dateDiff(str1, str2){
var diff = Date.parse(str2) - Date.parse(str1);
return isNaN(diff) ? NaN : {
diff: diff,
ms: Math.ceil(diff % 1000),
s: Math.ceil(diff / 1000 % 60),
m: Math.ceil(diff / 60000 % 60),
h: Math.ceil(diff / 3600000 % 24),
d: Math.ceil(diff / 86400000)
};
}
Yes it is wise to use a version control system for your project. Anyway, focusing on your installation warning issue you can try to launch npm install command starting from your root project folder instead of outside of it, so the installation steps will only update the existing package-lock.json file instead of creating a new one. Hope this helps.
Spent a while on this issue, and the PATH switch wasn't helping. My problem was the Homebrew/node/npm bug found here - https://github.com/npm/npm/issues/3794
If you've already installed node using Homebrew, try ****Note per comments that this might not be safe. It worked for me but could have unintended consequences. It also appears that latest version of Homebrew properly installs npm. So likely I would try brew update
, brew doctor
, brew upgrade node
etc before trying****:
npm update -gf
Or, if you want to install node with Homebrew and have npm work, use:
brew install node --without-npm
curl -L https://npmjs.org/install.sh | sh
#include <stdio.h>
int main(void) {
printf("size of int: %d", (int)sizeof(int));
return 0;
}
This returns 4, but it's probably machine dependant.
Followed the steps.
DevKit
to path C:\Ruby193\DevKit
cd C:\Ruby192\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
Then I wrote the command
gem install rails -r -y
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
Yes, you should always call base class __init__
explicitly as a good coding practice. Forgetting to do this can cause subtle issues or run time errors. This is true even if __init__
doesn't take any parameters. This is unlike other languages where compiler would implicitly call base class constructor for you. Python doesn't do that!
The main reason for always calling base class _init__
is that base class may typically create member variable and initialize them to defaults. So if you don't call base class init, none of that code would be executed and you would end up with base class that has no member variables.
Example:
class Base:
def __init__(self):
print('base init')
class Derived1(Base):
def __init__(self):
print('derived1 init')
class Derived2(Base):
def __init__(self):
super(Derived2, self).__init__()
print('derived2 init')
print('Creating Derived1...')
d1 = Derived1()
print('Creating Derived2...')
d2 = Derived2()
This prints..
Creating Derived1...
derived1 init
Creating Derived2...
base init
derived2 init
So in the end it is largely a question about how smart the python implementation is or is not, particularly in the case of the inner function not being a closure but simply an in function needed helper only.
In clean understandable design having functions only where they are needed and not exposed elsewhere is good design whether they be embedded in a module, a class as a method, or inside another function or method. When done well they really improve the clarity of the code.
And when the inner function is a closure that can also help with clarity quite a bit even if that function is not returned out of the containing function for use elsewhere.
So I would say generally do use them but be aware of the possible performance hit when you actually are concerned about performance and only remove them if you do actual profiling that shows they best be removed.
Do not do premature optimization of just using "inner functions BAD" throughout all python code you write. Please.
As others have mentioned, the simplest way to preseed a list is with NoneType
objects.
That being said, you should understand the way Python lists actually work before deciding this is necessary.
In the CPython implementation of a list, the underlying array is always created with overhead room, in progressively larger sizes ( 4, 8, 16, 25, 35, 46, 58, 72, 88, 106, 126, 148, 173, 201, 233, 269, 309, 354, 405, 462, 526, 598, 679, 771, 874, 990, 1120, etc)
, so that resizing the list does not happen nearly so often.
Because of this behavior, most list.append()
functions are O(1)
complexity for appends, only having increased complexity when crossing one of these boundaries, at which point the complexity will be O(n)
. This behavior is what leads to the minimal increase in execution time in S.Lott's answer.
Source: Python list implementation
Please try this code.....
DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();
Basically, you have three options:
EXPOSE
nor -p
EXPOSE
EXPOSE
and -p
1) If you specify neither EXPOSE
nor -p
, the service in the container will only be accessible from inside the container itself.
2) If you EXPOSE
a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.
3) If you EXPOSE
and -p
a port, the service in the container is accessible from anywhere, even outside Docker.
The reason why both are separated is IMHO because:
The documentation explicitly states:
The
EXPOSE
instruction exposes ports for use within links.
It also points you to how to link containers, which basically is the inter-container communication I talked about.
PS: If you do -p
, but do not EXPOSE
, Docker does an implicit EXPOSE
. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p
includes EXPOSE
. That's why I didn't list it above as a fourth case.
Adding to the answer by ThaBadDawg, use these handy functions (thanks to a wiser collegue of mine) to get from 36 length string back to a byte array of 16.
DELIMITER $$
CREATE FUNCTION `GuidToBinary`(
$Data VARCHAR(36)
) RETURNS binary(16)
DETERMINISTIC
NO SQL
BEGIN
DECLARE $Result BINARY(16) DEFAULT NULL;
IF $Data IS NOT NULL THEN
SET $Data = REPLACE($Data,'-','');
SET $Result =
CONCAT( UNHEX(SUBSTRING($Data,7,2)), UNHEX(SUBSTRING($Data,5,2)),
UNHEX(SUBSTRING($Data,3,2)), UNHEX(SUBSTRING($Data,1,2)),
UNHEX(SUBSTRING($Data,11,2)),UNHEX(SUBSTRING($Data,9,2)),
UNHEX(SUBSTRING($Data,15,2)),UNHEX(SUBSTRING($Data,13,2)),
UNHEX(SUBSTRING($Data,17,16)));
END IF;
RETURN $Result;
END
$$
CREATE FUNCTION `ToGuid`(
$Data BINARY(16)
) RETURNS char(36) CHARSET utf8
DETERMINISTIC
NO SQL
BEGIN
DECLARE $Result CHAR(36) DEFAULT NULL;
IF $Data IS NOT NULL THEN
SET $Result =
CONCAT(
HEX(SUBSTRING($Data,4,1)), HEX(SUBSTRING($Data,3,1)),
HEX(SUBSTRING($Data,2,1)), HEX(SUBSTRING($Data,1,1)), '-',
HEX(SUBSTRING($Data,6,1)), HEX(SUBSTRING($Data,5,1)), '-',
HEX(SUBSTRING($Data,8,1)), HEX(SUBSTRING($Data,7,1)), '-',
HEX(SUBSTRING($Data,9,2)), '-', HEX(SUBSTRING($Data,11,6)));
END IF;
RETURN $Result;
END
$$
CHAR(16)
is actually a BINARY(16)
, choose your preferred flavour
To follow the code better, take the example given the digit-ordered GUID below. (Illegal characters are used for illustrative purposes - each place a unique character.) The functions will transform the byte ordering to achieve a bit order for superior index clustering. The reordered guid is shown below the example.
12345678-9ABC-DEFG-HIJK-LMNOPQRSTUVW
78563412-BC9A-FGDE-HIJK-LMNOPQRSTUVW
Dashes removed:
123456789ABCDEFGHIJKLMNOPQRSTUVW
78563412BC9AFGDEHIJKLMNOPQRSTUVW
The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.
One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.
String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);
However, I would not suggest the above method. You should really be using a List<String>
. Lists allow you to add and remove items from any index. That would look similar to the following:
List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item
Apache commons to the rescue again.
assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));
Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2)
doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.
Swift: Ui Button create programmatically
let myButton = UIButton()
myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
myButton.titleLabel!.text = "Button Label"
myButton.titleLabel!.textColor = UIColor.redColor()
myButton.titleLabel!.textAlignment = .Center
self.view.addSubview(myButton)
Using @Adrian tips, I found a solution:
I'm using GROUP BY and COUNT. I tried to use DISTINCT with ORDER BY but I'm getting error message: "not a SELECTed expression"
select id from
(
SELECT id FROM a -- returns 1,4,2,3
UNION ALL -- changed to ALL
SELECT id FROM b -- returns 2,1
)
GROUP BY id ORDER BY count(id);
Thanks Adrian and this blog.
Here is my solution. @Maxim Shoustin's solution has some issue with sorting. I also wrap the whole thing to a directive. The only dependency is UI.Bootstrap.pagination, which did a great job on pagination.
Here is the plunker
Here is the github source code.
When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:
9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned
, then modular arithmetic takes place.
Now look at the following operations storing the result as an unsigned int
:
unsigned int five = 5, seven = 7;
unsigned int a = five - seven; // a = (-2 % 2^32) = 4294967294
int one = 1, six = 6;
unsigned int b = one - six; // b = (-5 % 2^32) = 4294967291
When you want to make sure that the result is signed
, then stored it into signed
variable or cast it to signed
. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs()
function defined in stdlib.h
:
int c = five - seven; // c = -2
int d = abs(five - seven); // d = 2
Be very careful, especially while writing conditions, because:
if (abs(five - seven) < seven) // = if (2 < 7)
// ...
if (five - seven < -1) // = if (-2 < -1)
// ...
if (one - six < 1) // = if (-5 < 1)
// ...
if ((int)(five - seven) < 1) // = if (-2 < 1)
// ...
but
if (five - seven < 1) // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
// ...
if (one - six < five) // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
// ...
Agree with some guys above and Lipert's opinion. In my case, it's quite often to do like this:
ICollection<int> A;
var B = new List<int> {1,2,3,4,5};
B.ForEach(A.Add);
To have an extension method for such operation a bit redundant in my view.
Typically, you'd use the NODE_ENV
variable to take special actions when you develop, test and debug your code. For example to produce detailed logging and debug output which you don't want in production. Express itself behaves differently depending on whether NODE_ENV
is set to production
or not. You can see this if you put these lines in an Express app, and then make a HTTP GET request to /error
:
app.get('/error', function(req, res) {
if ('production' !== app.get('env')) {
console.log("Forcing an error!");
}
throw new Error('TestError');
});
app.use(function (req, res, next) {
res.status(501).send("Error!")
})
Note that the latter app.use()
must be last, after all other method handlers!
If you set NODE_ENV
to production
before you start your server, and then send a GET /error
request to it, you should not see the text Forcing an error!
in the console, and the response should not contain a stack trace in the HTML body (which origins from Express).
If, instead, you set NODE_ENV
to something else before starting your server, the opposite should happen.
In Linux, set the environment variable NODE_ENV like this:
export NODE_ENV='value'
I think the best library is : https://github.com/chrisbanes/Android-PullToRefresh.
Works with:
ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager
With numpy :
im = Image.open('image.gif')
im_matrix = np.array(im)
print(im_matrix[0][0])
Give RGB vector of the pixel in position (0,0)
1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.
2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.
One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install
, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.
This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.
So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.
What if you wanna update? Then in your dev environment run: composer update
, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.
3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.
You could use a "variable" inside the output filename, for example:
/tmp/FetchBlock-${current_date}.txt
current_date:
Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.
Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)
I deleted the project without removing content. I then created a new Java project from an existing resource. Pointing at my SVN checkout root folder. This worked for me. Although, Chris' way would have been much quicker. That's good to note for future. Thanks!
Collections.emptyList
is immutable so there is a difference between the two versions so you have to consider users of the returned value.
Returning new ArrayList<Foo>
always creates a new instance of the object so it has a very slight extra cost associated with it which may give you a reason to use Collections.emptyList
. I like using emptyList
just because it's more readable.
You don't need jQuery for this, as simple javascript will suffice:
alert(document.domain);
See it in action:
console.log("Output;"); _x000D_
console.log(location.hostname);_x000D_
console.log(document.domain);_x000D_
alert(window.location.hostname)_x000D_
_x000D_
console.log("document.URL : "+document.URL);_x000D_
console.log("document.location.href : "+document.location.href);_x000D_
console.log("document.location.origin : "+document.location.origin);_x000D_
console.log("document.location.hostname : "+document.location.hostname);_x000D_
console.log("document.location.host : "+document.location.host);_x000D_
console.log("document.location.pathname : "+document.location.pathname);
_x000D_
For further domain-related values, check out the properties of window.location
online. You may find that location.host
is a better option, as its content could differ from document.domain
. For instance, the url http://192.168.1.80:8080
will have only the ipaddress in document.domain
, but both the ipaddress and port number in location.host
.
You're mixing different format functions.
The old-style %
formatting uses %
codes for formatting:
'It will cost $%d dollars.' % 95
The new-style {}
formatting uses {}
codes and the .format
method
'It will cost ${0} dollars.'.format(95)
Note that with old-style formatting, you have to specify multiple arguments using a tuple:
'%d days and %d nights' % (40, 40)
In your case, since you're using {}
format specifiers, use .format
:
"'{0}' is longer than '{1}'".format(name1, name2)