You will need to use different IP addresses. The server, whether Apache or IIS, grabs the traffic based on the IP and Port, which ever they are bound to listen to. Once it starts listening, then it uses the headers, such as the server name to filter and determine what site is being accessed. You can't do it will simply changing the server name in the request
net stop <your service> && net start <your service>
No net restart
, unfortunately.
Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.
This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.
Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.
Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks
Another approach with powershell:
@echo off
for /f %%t in ('powershell "(get-date).tofiletime()"') do set mst=%%t
rem some commands
powershell ((get-date).tofiletime() - %mst%)
this will print the execution time in milliseconds.
I forgot to add the "Password=xxx;" in the connection string in my case.
I don't think it can. When a service is "stopped", it gets totally unloaded.
Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.
Try this solution from http://social.technet.microsoft.com/Forums/en/w7itprosecurity/thread/e1ef04fa-6aea-47fe-9392-45929239bd68
Microsoft Support found the problem for us. Our domain accounts were locking when a Windows 7 computer was started. The Windows 7 computer had a hidden old password from that domain account. There are passwords that can be stored in the SYSTEM context that can't be seen in the normal Credential Manager view.
Download
PsExec.exe
from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx and copy it toC:\Windows\System32
.From a command prompt run:
psexec -i -s -d cmd.exe
From the new DOS window run:
rundll32 keymgr.dll,KRShowKeyMgr
Remove any items that appear in the list of Stored User Names and Passwords. Restart the computer.
Assuming that it's a TCP (rather than UDP) port that you're trying to use:
On the server itself, use netstat -an
to check to see which ports are listening.
From outside, just use telnet host port
(or telnet host:port
on Unix systems) to see if the connection is refused, accepted, or timeouts.
On that latter test, then in general:
On Windows 7 or Windows Vista the default option 'telnet' is not recognized as an internal or external command, operable program or batch file. To solve this, just enable it: Click *Start** → Control Panel → Programs → Turn Windows Features on or off. In the list, scroll down and select Telnet Client and click OK.
By wrapping your comparisons in {}
in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }
. Since the -and
operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true }
which is always true.
Instead of using {}
, use parentheses ()
.
Also you want to use -eq
instead of -match
since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls'
).
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public |
Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}
A better option is to filter the extensions at the Get-ChildItem
command.
Invoke-Command -computername SERVERNAME {
Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk |
Where-Object {$_.creationtime -ge "06/01/2014"}
}
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
You can call net start "service name"
on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.
Give hibernate.connection.url
as "jdbc:oracle:thin:@127.0.0.1:1521:xe"
then you can solve above issue. Because oracle's default SID is "xe" so we should give like this. When I gave like this data has been inserted into DB without any SQL exceptions, it's my real time experience.
The "Usort" function is your answer.
http://php.net/usort
A bit late, but I couldn't find the way I implemented it, this version needs closure, php>=5.3, but could be altered not to:
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
$order = array('name', 'dob', 'address');
$keys= array_flip($order);
uksort($customer, function($a, $b)use($keys){
return $keys[$a] - $keys[$b];
});
print_r($customer);
Of course 'dontSortMe' needs to be sorted out, and may appear first in the example
with a specific dir:
cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx
in VS 2017 I cleaned the solution and rebuilt it and that fixed it
Use the CSS property border on the <td>
s following the <tr>
s you do not want to have the border.
In my example I made a class noBorder
that I gave to one <tr>
. Then I use a simple selector tr.noBorder td
to make the border go away for all the <td>
s that are inside of <tr>
s with the noBorder
class by assigning border: 0
.
Note that you do not need to provide the unit (i.e. px
) if you set something to 0
as it does not matter anyway. Zero is just zero.
table, tr, td {_x000D_
border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
border: 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>A1</td>_x000D_
<td>B1</td>_x000D_
<td>C1</td>_x000D_
</tr>_x000D_
<tr class="noBorder">_x000D_
<td>A2</td>_x000D_
<td>B2</td>_x000D_
<td>C2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Here's the output as an image:
For Oracle 11g, I was able to change the column attribute as follows:
ALTER TABLE tablename MODIFY columnname datatype NOT NULL;
Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
That can't be done with a for
-loop, unless you use the Reflection API. However, you can use Arrays.asList
instead to accomplish the same:
List<Answer> answers = Arrays.asList(answer1, answer2, answer3);
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
How about the following function, which returns either +H:MM:SS or +H:MM:SS.sss
public static String formatInterval(final long interval, boolean millisecs )
{
final long hr = TimeUnit.MILLISECONDS.toHours(interval);
final long min = TimeUnit.MILLISECONDS.toMinutes(interval) %60;
final long sec = TimeUnit.MILLISECONDS.toSeconds(interval) %60;
final long ms = TimeUnit.MILLISECONDS.toMillis(interval) %1000;
if( millisecs ) {
return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms);
} else {
return String.format("%02d:%02d:%02d", hr, min, sec );
}
}
I also had added on or extended additional columns into my AspNetUsers table. When I wanted to simply view this data I found many examples like the code above with "Extensions" etc... This really amazed me that you had to write all those lines of code just to get a couple values from the current users.
It turns out that you can query the AspNetUsers table like any other table:
ApplicationDbContext db = new ApplicationDbContext();
var user = db.Users.Where(x => x.UserName == User.Identity.Name).FirstOrDefault();
You might find useful mosaic
plot from statsmodels. Which can also give statistical highlighting for the variances.
from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);
But beware of the 0 sized cell - they will cause problems with labels.
See this answer for details
Put the Text in a Center:
Container(
height: 45,
color: Colors.black,
child: Center(
child: Text(
'test',
style: TextStyle(color: Colors.white),
),
),
);
A more generalised example - if looking for parts of a word OR specific words in a string:
df = pd.DataFrame([('cat andhat', 1000.0), ('hat', 2000000.0), ('the small dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
Specific parts of sentence or word:
searchfor = '.*cat.*hat.*|.*the.*dog.*'
Creat column showing the affected rows (can always filter out as necessary)
df["TrueFalse"]=df['col1'].str.contains(searchfor, regex=True)
col1 col2 TrueFalse
0 cat andhat 1000.0 True
1 hat 2000000.0 False
2 the small dog 1000.0 True
3 fog 330000.0 False
4 pet 3 30000.0 False
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
Use Session.Contents.Count
:
if (Session.Contents.Count == 0)
{
Response.Write(".NET session has Expired");
Response.End();
}
else
{
InitializeControls();
}
The code above assumes that you have at least one session variable created when the user first visits your site. If you don't have one then you are most likely not using a database for your app. For your case you can just manually assign a session variable using the example below.
protected void Page_Load(object sender, EventArgs e)
{
Session["user_id"] = 1;
}
Best of luck to you!
A simple way is to put tabindex="-1" in the field(s) you don't want to be tabbed to. Eg
<input type="text" tabindex="-1" name="f1">
pattern="[a-z0-9._%+-]{1,40}[@]{1}[a-z]{1,10}[.]{1}[a-z]{3}"
<input type="email" class="form-control" id="driver_email" placeholder="Enter Driver Email" name="driver_email" pattern="[a-z0-9._%+-]{1,40}[@]{1}[a-z]{1,10}[.]{1}[a-z]{3}" required="">
If problem persists after setting permissions right for the
storage
andbootstrap/cache
folders, first confirm by turning off selinux with the command
setenforce 0
If this works after the above command, this should allow writing, but you've turned off added security server-wide. That's bad. Turn SELinux back.
setenforce 1
Then finally use SELinux to allow writing of the file by using this command
chcon -R -t httpd_sys_rw_content_t storage
And you're good to go!This link helped a lot!
This worked for me
<script data-main="your-script.js" src="require.js"></script>
Notes!
Use require(['moudle-name'])
in your-script.js
,
not require('moudle-name')
Use const {ipcRenderer} = require(['electron'])
,
not const {ipcRenderer} = require('electron')
Actually the default value of byte is 0.
I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:
var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
Also worth mentioning -- if you were forced to use an older Java version prior to 1.5, and you are trying to use Collections, you won't be able to parameterize the collection with a type such as Double
.
You'll have to manually "box" to the class Double
when adding new items, and "unbox" to the primitive double
by parsing and casting, doing something like this:
LinkedList lameOldList = new LinkedList();
lameOldList.add( new Double(1.2) );
lameOldList.add( new Double(3.4) );
lameOldList.add( new Double(5.6) );
double total = 0.0;
for (int i = 0, len = lameOldList.size(); i < len; i++) {
total += Double.valueOf( (Double)lameOldList.get(i) );
}
The old-school list will contain only type Object
and so has to be cast to Double
.
Also, you won't be able to iterate through the list with an enhanced-for-loop in early Java versions -- only with a for-loop.
Combining two byte[]
using iTextSharp up to version 5.x:
internal static MemoryStream mergePdfs(byte[] pdf1, byte[] pdf2)
{
MemoryStream outStream = new MemoryStream();
using (Document document = new Document())
using (PdfCopy copy = new PdfCopy(document, outStream))
{
document.Open();
copy.AddDocument(new PdfReader(pdf1));
copy.AddDocument(new PdfReader(pdf2));
}
return outStream;
}
Instead of the byte[]
's it's possible to pass also Stream
's
Give Xml Visualizer a try. Haven't tried the latest version yet, but I can't work without the previous one in Visual Studio 2003.
on top of displaying DataSet hierarchically, there are also a lot of other handy features such as filtering and selecting the RowState which you want to view.
To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length
.
double sum = 0.0;
int length = 0;
for( double number : numbers ) {
sum += number;
length++;
}
return sum/length;
Variance is calculated similarly. Standard deviation is simply the square root of the variance:
double stddev = Math.sqrt( variance );
FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:
pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg
I have thesame issue before but i solved it easily by just following this steps:
*connect your android phone in a debugging mode (to enable debugging mode goto settings scroll down About Phone scroll down tap seven times Build Number and it will automatically enable developer option turn on developer options and check USB debugging)
download Universal ADB Driver Installer
*choose Adb Driver Installer (Universal)
*install it *it will automatically detect your android device(any kind of brand) *chose the device and install
For Windows 10 / Windows Server 2016 use the following command:
dism /online /enable-feature /featurename:IIS-ASPNET45 /all
The suggested answers with aspnet_regiis
doesn't work on Windows 10 (Creators Update and later) or Windows Server 2016:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.0).
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.0).
Interestingly, the "Turn Windows Features On/Off" dialog didn't allow me to untick .NET nor ASP.NET 4.6, and only the above DISM command worked. Not sure whether the featurename is correct, but it worked for me.
You could use linq to xml.
var xmlStr = File.ReadAllText("fileName.xml");
var str = XElement.Parse(xmlStr);
var result = str.Elements("word").
Where(x => x.Element("category").Value.Equals("verb")).ToList();
Console.WriteLine(result);
Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat
is a bit confusing. I was trying to use r'?.*'
as a pattern, and thought it was complaining for some strange reason about the *
, but the problem is actually that ?
is a way of saying "repeat zero or one times". So I needed to say r'\?.*'
to match a literal ?
In case you need short unique IDs as your filename, try shortuuid
, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.
>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22
compared to
>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
This goes back and forth to and from the \uXXXX format.
class Program {
static void Main( string[] args ) {
string unicodeString = "This function contains a unicode character pi (\u03a0)";
Console.WriteLine( unicodeString );
string encoded = EncodeNonAsciiCharacters(unicodeString);
Console.WriteLine( encoded );
string decoded = DecodeEncodedNonAsciiCharacters( encoded );
Console.WriteLine( decoded );
}
static string EncodeNonAsciiCharacters( string value ) {
StringBuilder sb = new StringBuilder();
foreach( char c in value ) {
if( c > 127 ) {
// This character is too big for ASCII
string encodedValue = "\\u" + ((int) c).ToString( "x4" );
sb.Append( encodedValue );
}
else {
sb.Append( c );
}
}
return sb.ToString();
}
static string DecodeEncodedNonAsciiCharacters( string value ) {
return Regex.Replace(
value,
@"\\u(?<Value>[a-zA-Z0-9]{4})",
m => {
return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString();
} );
}
}
Outputs:
This function contains a unicode character pi (p)
This function contains a unicode character pi (\u03a0)
This function contains a unicode character pi (p)
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
Here's a tip if you're using cmake. From: http://public.kitware.com/pipermail/cmake/2013-January/053117.html
I'm copying the tip so it's all on this page:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(subst
${CMAKE_SOURCE_DIR}/,,$(abspath $<))\"'")
If you're using GNU make, I see no reason you couldn't extend this to your own makefiles. For example, you might have a line like this:
CXX_FLAGS+=-D__FILENAME__='\"$(subst $(SOURCE_PREFIX)/,,$(abspath $<))\"'"
where $(SOURCE_PREFIX)
is the prefix that you want to remove.
Then use __FILENAME__
in place of __FILE__
.
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.
an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).
In case the host
part is omitted it defaults to the wildcard symbol %
, allowing all hosts.
CREATE USER 'service-api';
GRANT ALL PRIVILEGES ON the_db.* TO 'service-api' IDENTIFIED BY 'the_password'
SELECT * FROM mysql.user;
SHOW GRANTS FOR 'service-api'
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
_x000D_
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
You can use alexw's solution with the Artisan. Run following commands in the command line.
php artisan tinker
DB::connection()->getPdo();
If connection is OK, you should see
CONNECTION_STATUS: "Connection OK; waiting to send.",
near the end of the response.
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
try the following (in RowDataBound method of GridView):
protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
// this will only change the rows backgound not the column header
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
}
}
Best and the simple way of doing is :
Just use the default way from Sequelize
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw : true // <----------- Magic is here
}).success(function (sensors) {
console.log(sensors);
});
Note : [options.raw] : Return raw result. See sequelize.query for more information.
For the nested result/if we have include model , In latest version of sequlize ,
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
include : [
{ model : someModel }
]
raw : true , // <----------- Magic is here
nest : true // <----------- Magic is here
}).success(function (sensors) {
console.log(sensors);
});
You can use HostingEnvironment.MapPath in any context where System.Web
objects like HttpContext.Current
are not available (e.g also from a static method).
var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");
See also What is the difference between Server.MapPath and HostingEnvironment.MapPath?
Wrap it in an unused function:
.f = function() {
## unwanted code here:
}
This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties
:
org.apache.catalina.webresources.Cache.level = SEVERE
This filters out the “Unable to add the resource” logs, which are at level WARNING.
In my view a WARNING
is not necessarily an error that needs to be addressed, but rather can be ignored if desired.
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return
True
if string starts with theprefix
, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
If your Router is like this
<Route exact path="/category/:id" component={ProductList}/>
You will get that id like this
this.props.match.params.id
If you encode the & in your URL to %26 it works correctly. Just tested and verified.
You can use the JSON stringify
method.
JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'
There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.
If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.
You can also do it using netrw
The explore command opens up netrw in the directory of the open file
:E
Move the cursor over the file you want to rename:
R
Type in the new name, press enter, press y.
@Cermbo's answer is not related to this question. In their answer, Laravel will give you all Events
if each Event
has 'participants'
with IdUser
of 1
.
But if you want to get all Events
with all 'participants'
provided that all 'participants'
have a IdUser
of 1, then you should do something like this :
Event::with(["participants" => function($q){
$q->where('participants.IdUser', '=', 1);
}])
N.B:
in where
use your table name, not Model name.
Assuming this is a personal certificate created by windows on the system you copied your project from, you can use the certificate manager on the system where the project is now and import the certificate. Start the certificate manager (certmgr) and select the personal certificates then right click below the list of existing certificates and select import from the tasks. Use the browse to find the .pfx in the project (the .pfx from the previous system that you copied over with the project). It should be in the sub-directory with the same name as the project directory. I am familiar with C# and VS, so if that is not your environment maybe the .pfx will be elsewhere or maybe this suggestion does not apply. After the import you should get a status message. If you succeeded, the compile certificate error should be gone.
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
$users = User::all();
$associates = Associate::all();
$userAndAssociate = $users->merge($associates);
I made this into a bash shell script. Usage: keep NUM DIR
where NUM is the number of files to keep and DIR is the directory to scrub.
#!/bin/bash
# Keep last N files by date.
# Usage: keep NUMBER DIRECTORY
echo ""
if [ $# -lt 2 ]; then
echo "Usage: $0 NUMFILES DIR"
echo "Keep last N newest files."
exit 1
fi
if [ ! -e $2 ]; then
echo "ERROR: directory '$1' does not exist"
exit 1
fi
if [ ! -d $2 ]; then
echo "ERROR: '$1' is not a directory"
exit 1
fi
pushd $2 > /dev/null
ls -tp | grep -v '/' | tail -n +"$1" | xargs -I {} rm -- {}
popd > /dev/null
echo "Done. Kept $1 most recent files in $2."
ls $2|wc -l
Updates an old config with new/changed/removed options.
var theString = "TEST";
char[] myChar = theString.ToCharArray();
I tested this in the C# interactive window of Visual Studio 2019 and got:
char[4] { 'T', 'E', 'S', 'T' }
I had some what similar requirement - to find first day of the month
but based on year end month
selected by user in their profile page.
Problem statement - find all the txns
done by the user in his/her financial year. Financial year
is determined using year end
month value where month
can be any valid month - 1 for Jan
, 2 for Feb
, 3 for Mar
,....12 for Dec
.
For some clients financial year end
s on March
and some observe it on December
.
Scenarios - (Today is `08 Aug, 2018`)
1. If `financial year` ends on `July` then query should return `01 Aug 2018`.
2. If `financial year` ends on `December` then query should return `01 January 2018`.
3. If `financial year` ends on `March` then query should return `01 April 2018`.
4. If `financial year` ends on `September` then query should return `01 October 2017`.
And, finally below is the query. -
select @date := (case when ? >= month(now())
then date_format((subdate(subdate(now(), interval (12 - ? + month(now()) - 1) month), interval day(now()) - 2 day)) ,'%Y-%m-01')
else date_format((subdate(now(), interval month(now()) - ? - 1 month)), '%Y-%m-01') end)
where ?
is year end
month (values from 1 to 12).
There are a lot of ways to do so, for example:
in case you have not pushed the commit publicly yet:
git reset HEAD~1 --soft
That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See git reset man
In case you did push publicly (on a branch called 'master'):
git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) )
revert commit normally and push
git checkout master
git revert a8172f36 #hash of the commit you want to destroy
# this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history)
git push origin master
now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit
option:
git revert --no-commit 86b48ba (hash of the revert commit).
I've crafted a small example: https://github.com/Isantipov/git-revert/commits/master
In addition to romkyns's great answer.. here is some relevant documentation/examples.
DOM Elements have a native .click()
method.
The
HTMLElement.click()
method simulates a mouse click on an element.When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an
<a>
element to initiate navigation as if a real mouse-click had been received. (mdn reference)
Relevant W3 documentation.
A few examples..
You can access a specific DOM element from a jQuery object: (example)
$('a')[0].click();
You can use the .get()
method to retrieve a DOM element from a jQuery object: (example)
$('a').get(0).click();
As expected, you can select the DOM element and call the .click()
method. (example)
document.querySelector('a').click();
It's worth pointing out that jQuery is not required to trigger a native .click()
event.
Does it have to be String.Format
?
This looks like a job for String.Padleft
myString=myString.PadLeft(3, '0');
Or, if you are converting direct from an int:
myInt.toString("D3");
The problem is that the keys provided in the loop do not refer to the index of the file.
for (var i in this.files) {
console.log(i);
}
The output of the above code is:
0
length
item
But what was expected was:
0
1
2
etc...
Then the error occurs when the browser tries to execute, for example:
window.URL.createObjectURL(this.files["length"])
I suggest implementation based on the following code:
var files = this.files;
for (var i = 0; i < files.length; i++) {
var file = files[i],
src = (window.URL || window.webkitURL).createObjectURL(file);
...
}
I hope this can help someone.
Greetings!
This should answer that question, and then some.
The second line, if (obj.GetType() == typeof(ClassA)) {}
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)
Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.
I found this to be an issue when joining but you might find this blog useful in understanding how Joins work in the back. How Joins Work..
[Edited] @Shree Thank you for pointing that out. On the paragraph of Merge Join. It mentions on how joins work...
Like hash join, merge join consists of two steps. First, both tables of the join are sorted on the join attribute. This can be done with just two passes through each table via an external merge sort. Finally, the result tuples are generated as the next ordered element is pulled from each table and the join attributes are compared
.
First of definition. For me unmanaged resource means some class, which implements IDisposable interface or something created with usage of calls to dll. GC doesn't know how to deal with such objects. If class has for example only value types, then I don't consider this class as class with unmanaged resources. For my code I follow next practices:
public class SomeClass : IDisposable
{
/// <summary>
/// As usually I don't care was object disposed or not
/// </summary>
public void SomeMethod()
{
if (_disposed)
throw new ObjectDisposedException("SomeClass instance been disposed");
}
public void Dispose()
{
Dispose(true);
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)//we are in the first call
{
}
_disposed = true;
}
}
I make a sample for you , and I hope this is helpful...
static void Main(string[] args)
{
var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };
DataTable table = new DataTable();
foreach (var col in cols)
table.Columns.Add(col);
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
foreach (var col in cols)
{
var results = from p in table.AsEnumerable()
select p[col];
Console.WriteLine("*************************");
foreach (var result in results)
{
Console.WriteLine(result);
}
}
Console.ReadLine();
}
div {
text-align : center;
}
button {
width: 50%;
margin: 1rem auto;
}
_x000D_
<div style="width:100%; height:100%; border: 1px solid">
<button type="button">hello</button>
</div>
_x000D_
This is what I mostly do.
I think bootstrap also uses this in "mx-auto".
(base) C:\WINDOWS\system32>conda install C:\Users\Todd\Downloads\opencv3-3.1.0-py35_0.tar.bz2
I ran this command from anaconda terminal after I downloaded the version from https://anaconda.org/menpo/opencv3/files
This is the only way I could get cv2 to work and I tried everything for two days.
Note: This was for Bootstrap 2 (relevant when the question was asked).
You can accomplish this by using row-fluid
to make a fluid (percentage) based row inside an existing block
.
<div class="row">
<div class="span5">span5</div>
<div class="span3">span3</div>
<div class="span2">
<div class="row-fluid">
<div class="span12">span2</div>
<div class="span12">span2</div>
</div>
</div>
<div class="span2">span2</div>
</div>
<div class="row">
<div class="span6">
<div class="row-fluid">
<div class="span12">span6</div>
<div class="span12">span6</div>
</div>
</div>
<div class="span6">span6</div>
</div>
Here's a JSFiddle example.
I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid
after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):
.row-fluid [class*="span"] {
margin-left: 0;
}
For those that might end up here looking for the opposite conversion (from XMLGregorianCalendar
to Date
):
XMLGregorianCalendar xcal = <assume this is initialized>;
java.util.Date dt = xcal.toGregorianCalendar().getTime();
If gives "permission denied" on adb shell -> su...
Some ROMs are running adbd daemon in secure mode (adbd has no root access and su command does not even show permission ask dialog on the device). In this case you will get "permission denied" when you try cmd -> adb shell -> su. The solution I've found is one app from the famous modder Chainfire called Adbd Insecure.
You can use a variable to count places in the array, so when ever you add a new element, you put it in the right place. For example:
int a = 0;
int arr[5] = { };
arr[a] = 6;
a++;
To loop through JSON Object : In Angluar's (6.0.0+), now they provide the pipe keyvalue
:
<div *ngFor="let item of object| keyvalue">
{{ item.key }} - {{ item.value }}
</div>
To just display JSON
{{ object | json }}
Yes, you can access it through GET
and POST
(trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.
If xamp already installed on your computer user these settings
Changing the IDENTITY
property is really a metadata only change. But to update the metadata directly requires starting the instance in single user mode and messing around with some columns in sys.syscolpars
and is undocumented/unsupported and not something I would recommend or will give any additional details about.
For people coming across this answer on SQL Server 2012+ by far the easiest way of achieving this result of an auto incrementing column would be to create a SEQUENCE
object and set the next value for seq
as the column default.
Alternatively, or for previous versions (from 2005 onwards), the workaround posted on this connect item shows a completely supported way of doing this without any need for size of data operations using ALTER TABLE...SWITCH
. Also blogged about on MSDN here. Though the code to achieve this is not very simple and there are restrictions - such as the table being changed can't be the target of a foreign key constraint.
identity
column.CREATE TABLE dbo.tblFoo
(
bar INT PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)
INSERT INTO dbo.tblFoo (bar)
SELECT TOP (10000) ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM master..spt_values v1, master..spt_values v2
identity
column (more or less instant).BEGIN TRY;
BEGIN TRANSACTION;
/*Using DBCC CHECKIDENT('dbo.tblFoo') is slow so use dynamic SQL to
set the correct seed in the table definition instead*/
DECLARE @TableScript nvarchar(max)
SELECT @TableScript =
'
CREATE TABLE dbo.Destination(
bar INT IDENTITY(' +
CAST(ISNULL(MAX(bar),0)+1 AS VARCHAR) + ',1) PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)
ALTER TABLE dbo.tblFoo SWITCH TO dbo.Destination;
'
FROM dbo.tblFoo
WITH (TABLOCKX,HOLDLOCK)
EXEC(@TableScript)
DROP TABLE dbo.tblFoo;
EXECUTE sp_rename N'dbo.Destination', N'tblFoo', 'OBJECT';
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
PRINT ERROR_MESSAGE();
END CATCH;
INSERT INTO dbo.tblFoo (filler,filler2)
OUTPUT inserted.*
VALUES ('foo','bar')
bar filler filler2
----------- --------- ---------
10001 foo bar
DROP TABLE dbo.tblFoo
Ah-ha! The Lodash Changelog says it all...
"Removed _.pluck
in favor of _.map
with iteratee shorthand"
var objects = [{ 'a': 1 }, { 'a': 2 }];
// in 3.10.1
_.pluck(objects, 'a'); // ? [1, 2]
_.map(objects, 'a'); // ? [1, 2]
// in 4.0.0
_.map(objects, 'a'); // ? [1, 2]
I've posted longer answer here: https://stackoverflow.com/a/20877657/207661
TL;DR: You need only one line of code that runs in document ready event:
$(document.body).tooltip({ selector: "[title]" });
Other more complicated code suggested in other answers don't seem necessary (I've tested this with Bootstrap 3.0).
If that version you need to obtain is either a branch or a tag then:
git clone -b branch_or_tag_name repo_address_or_path
You can read more about the generic concept of "loose coupling".
In short, it's a description of a relationship between two classes, where each class knows the very least about the other and each class could potentially continue to work just fine whether the other is present or not and without dependency on the particular implementation of the other class.
This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList
of HashMap<String, String>
by one object in the list, that being the timestamp.
I have these objects:
ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
The map objects are as follows:
Map<String, Object> map = new HashMap<>();
// of course this is the actual formatted date below in the timestamp
map.put("timestamp", "MM/dd/yyyy HH:mm:ss");
map.put("item1", "my text goes here");
map.put("item2", "my text goes here");
That mapping is what I use to load all my objects into the array list, using the alList.add(map)
function, within a loop.
Now, I created my own comparator:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class DateSorter implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstDateString = ((HashMap<String, String>) firstObjToCompare).get("timestamp");
String secondDateString = ((HashMap<String, String>) secondObjToCompare).get("timestamp");
if (secondDateString == null || firstDateString == null) {
return 0;
}
// Convert to Dates
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime firstDate = dtf.parseDateTime(firstDateString);
DateTime secondDate = dtf.parseDateTime(secondDateString);
if (firstDate.isAfter(secondDate)) return -1;
else if (firstDate.isBefore(secondDate)) return 1;
else return 0;
}
}
I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.
Collections.sort(alList, new DateSorter());
This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.
This should not stop you from having the gui translate it back to dollars/euros.
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
I've DONE it through this short and easy recipe:
Auto-sign commits on macOS (Globally and with different IDEs):
Get your signingkey
in this way.
brew install gnupg gnupg2 pinentry-mac
git config --global user.signingkey <YOUR_SIGNING_KEY>
git config --global commit.gpgsign true
git config --global gpg.program gpg
Put the following in gpg.conf
file (edit file with nano ~/.gnupg/gpg.conf
command):
no-tty
Put the following in gpg-agent.conf
file (edit file with nano ~/.gnupg/gpg-agent.conf
command):
pinentry-program /usr/local/bin/pinentry-mac
Update:
You might need to execute killall gpg-agent
command after editing the configurations file, gpg.conf
, according to the comments. As the self-explanatory command says, this command will terminate the GPG (Gnu Privacy Guard) agent.
Update:
It seems there's a new API to check just that. See another answer in this page: https://stackoverflow.com/a/36653034/435605
Original post:
Use errorCode.equals("NoSuchKey")
try {
AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
String bucketName = getBucketName();
s3.createBucket(bucketName);
S3Object object = s3.getObject(bucketName, getKey());
} catch (AmazonServiceException e) {
String errorCode = e.getErrorCode();
if (!errorCode.equals("NoSuchKey")) {
throw e;
}
Logger.getLogger(getClass()).debug("No such key!!!", e);
}
Note about the exception: I know exceptions should not be used for flow control. The problem is that Amazon didn't provide any api to check this flow - just documentation about the exception.
For all python users:
Simply go to your destination folder in the terminal.
cd projectFoder
then start HTTP server For Python3+:
python -m http.server 8000
Serving HTTP on :: port 8000 (http://[::]:8000/) ...
go to your link: http://0.0.0.0:8000/
Enjoy :)
Import file1
inside file2
:
To import all variables from file1 without flooding file2's namespace, use:
import file1
#now use file1.x1, file2.x2, ... to access those variables
To import all variables from file1 to file2's namespace( not recommended):
from file1 import *
#now use x1, x2..
From the docs:
While it is valid to use
from module import *
at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.
Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
If you're willing to use a library such as jQuery, you could simply do this:
console.log($('<p>test</p>').text());
foreach($array as $key=>$value) {
// do stuff
}
$key
is the index of each $array
element
You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same
Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);
makes the toast, but doesnt show it.
You have to do Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
This is a simple approach if you don't have much code changes:
1. git stash
2. git stash apply
3. remove the files/code you don't want to commit
4. commit the remaining files/code you do want
Then if you want the code you removed (bits you didn't commit) in a separate commit or another branch, then while still on this branch do:
5. git stash apply
6. git stash
With step 5 as you already applied the stash and committed the code you did want in step 4, the diff and untracked in the newly applied stash is just the code you removed in step 3 before you committed in step 4.
As such step 6 is a stash of the code you didn't [want to] commit, as you probably don't really want to lose those changes right? So the new stash from step 6 can now be committed to this or any other branch by doing git stash apply on the correct branch and committing.
Obviously this presumes you do the steps in one flow, if you stash at any other point in these steps you'll need to note the stash ref for each step above (rather than just basic stash and apply the most recent stash).
You could create your own class of type Quiz and then deserialize with strong type:
Example:
quizresult = JsonConvert.DeserializeObject<Quiz>(args.Message,
new JsonSerializerSettings
{
Error = delegate(object sender1, ErrorEventArgs args1)
{
errors.Add(args1.ErrorContext.Error.Message);
args1.ErrorContext.Handled = true;
}
});
And you could also apply a schema validation.
On unix systems, you can use the following command to determine where git is installed:
whereis git
If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.
I think you can try with:
rsync -azvu -e ssh user@host1:/directory/ user@host2:/directory2/
(and I assume you are on host0 and you want to copy from host1 to host2 directly)
If the above does not work, you could try:
ssh user@host1 "/usr/bin/rsync -azvu -e ssh /directory/ user@host2:/directory2/"
in the this, it would work, if you already have setup passwordless SSH login from host1 to host2
this work for me
toolbar.setPadding(0,0,0,0);
toolbar.setContentInsetsAbsolute(0,0);
I had the same problem with a freshly installed copy of Chrome.
If nothing works, and your Use a proxy server your LAN
setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.
The easiest solution is to create 3 divs
. One that will contain the other 2, the one with transparent background and the one with content. Make the first div's position relative and set the one with transparent background to negative z-index
, then adjust the position of the content to fit over the transparent background. This way you won't have issues with absolute positioning.
df.filter($"state" like "T%%")
for pattern matching
df.filter($"state" === "TX")
or df.filter("state = 'TX'")
for equality
I had the similar issue. The problem was in the passwords: the Keystore and private key used different passwords. (KeyStore explorer was used)
After creating Keystore with the same password as private key had the issue was resolved.
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
The correct syntax is:
data: {status: status, name: name},
As specified here: http://api.jquery.com/jQuery.ajax/
So if that doesn't work, I would alert those variables to make sure they have values.
Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:
TypeError: 'numpy.float64' object cannot be interpreted as an integer
or
TypeError: 'numpy.float64' object is not iterable
The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:
def MinMax(x, mini=0, maxi=1)
return max(min(x,mini), maxi)
The solution was avoid numpy
or math
:
def MinMax(x, mini=0, maxi=1)
x = [x_aux if x_aux > mini else mini for x_aux in x]
x = [x_aux if x_aux < maxi else maxi for x_aux in x]
return max(min(x,mini), maxi)
Then, everything calm again. It was like one library possessed max
and min
!
You test k = M
instead of k == M
.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))
While not directly related to the question, if you hop onto this question looking to disable something other than the typical input elements button, input, textarea
, the syntax won't work.
To disable a div or a span, use setAttribute
document.querySelector('#somedivorspan').setAttribute('disabled', true);
P.S: Gotcha, only call this if you intend to disable. A bug in chrome Version 83 causes this to always disable even when the second parameter is false.
If you are using grunt to build your application, it's possible that during build the paths change. In this case you need to modify your grunt file like this:
copy: {
main: {
files: [{
src: ['fonts/**'],
dest: 'dist/fonts/',
filter: 'isFile',
expand: true,
flatten: true
}, {
src: ['bower_components/font-awesome/fonts/**'],
dest: 'dist/css/',
filter: 'isFile',
expand: true,
flatten: false
}]
}
},
You can try more system indeppended method: system("pause");
Private Sub CommandButton1_Click()
Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption
Me.Hide
Run "filename"
End Sub
Private Sub MUN_Change()
Dim r As Integer
r = 2
While Range("m" & CStr(r)).Value <> ""
If Range("m" & CStr(r)).Value = MUN.Text Then
Label5.Caption = Range("n" & CStr(r)).Value
End If
r = r + 1
Wend
End Sub
Private Sub PROV_Change()
If PROV.Text = "LAGUNA" Then
MUN.Text = ""
MUN.RowSource = "Menu!M26:M56"
ElseIf PROV.Text = "CAVITE" Then
MUN.Text = ""
MUN.RowSource = "Menu!M2:M25"
ElseIf PROV.Text = "QUEZON" Then
MUN.Text = ""
MUN.RowSource = "Menu!M57:M97"
End If
End Sub
I like using (open source and gui friendly) Quantum GIS to convert the shapefile to kml.
Google Maps API supports only a subset of the KML standard. One limitation is file size.
To reduce your file size, you can Quantum GIS's "simplify geometries" function. This "smooths" polygons.
Then you can select your layer and do a "save as kml" on it.
If you need to process a bunch of files, the process can be batched with Quantum GIS's ogr2ogr command from osgeo4w shell.
Finally, I recommend zipping your kml (with your favorite compression program) for reduced file size and saving it as kmz.
You can try Microsoft's Face API. It can detect and identify people. learn more about face API here.
Fixed positioning is supposed to define everything in relation to the viewport, so position:fixed
is always going to do that. Try using position:relative
on the child div instead.
(I realize you might need the fixed positioning for other reasons, but if so - you can't really make the width match it's parent with out JS without inherit
)
I don't know why but i just renamed my source file COLARR.C to colarr.c and the error vanished! probably you need this
sudo apt-get install g++
I found this really helpful answer here.
rsync -r -v --progress -e ssh user@remote-system:/address/to/remote/file /home/user/
Not only you can pass there the password, but also it will show the progress bar when copying. Really awesome.
Sometimes a BEFORE
trigger can be replaced with an AFTER
one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF
trigger one, as @marc_s has suggested in his comment.
Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE
trigger and an INSTEAD OF
one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF
trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE
trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.
But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW
. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.
So, it's really two things to solve then:
replace the BEFORE
functionality;
replace the FOR EACH ROW
functionality.
My attempt at solving these is below:
CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @new_super TABLE (
super_id int
);
INSERT INTO super (subtype_discriminator)
OUTPUT INSERTED.super_id INTO @new_super (super_id)
SELECT 'SUB1' FROM INSERTED;
INSERT INTO sub (super_id)
SELECT super_id FROM @new_super;
END;
This is how the above works:
The same number of rows as being inserted into sub1
is first added to super
. The generated super_id
values are stored in a temporary storage (a table variable called @new_super
).
The newly inserted super_id
s are now inserted into sub1
.
Nothing too difficult really, but the above will only work if you have no other columns in sub1
than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.
The problem is to assign the new super_id
s to every inserted row individually. One way to implement the mapping could be like below:
CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @new_super TABLE (
rownum int IDENTITY (1, 1),
super_id int
);
INSERT INTO super (subtype_discriminator)
OUTPUT INSERTED.super_id INTO @new_super (super_id)
SELECT 'SUB1' FROM INSERTED;
WITH enumerated AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
FROM inserted
)
INSERT INTO sub1 (super_id, other columns)
SELECT n.super_id, i.other columns
FROM enumerated AS i
INNER JOIN @new_super AS n
ON i.rownum = n.rownum;
END;
As you can see, an IDENTIY(1,1)
column is added to @new_user
, so the temporarily inserted super_id
values will additionally be enumerated starting from 1. To provide the mapping between the new super_id
s and the new data rows, the ROW_NUMBER
function is used to enumerate the INSERTED
rows as well. As a result, every row in the INSERTED
set can now be linked to a single super_id
and thus complemented to a full data row to be inserted into sub1
.
Note that the order in which the new super_id
s are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super
rows generated are identical save for the IDs. So, all you need here is just to take one new super_id
per new sub1
row.
If, however, the logic of inserting into super
is more complex and for some reason you need to remember precisely which new super_id
has been generated for which new sub
row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:
You can run a batch file that calls your program, check out the discussion here for how to do it: http://www.pcworld.com/article/115628/windows_tips_make_windows_start_and_stop_the_way_you_want.html
(from google search: windows schedule task run at shut down)
//Simple example code:
foreach (var item in YourCheckedListBox.CheckedItems)
{List<string>.Add(item);}
None of the above solutions resolved this error for me. I had to set the following in web.config:
system.servicemodel > bindings > webHttpBinding > binding:
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
I would like to take this opportunity to CURSE Microsoft once again for creating such a huge mess with the .NET Framework and making developer lives so miserable for so long!
$('div.ui-datepicker').css({ fontSize: '12px' });
work if we call it after
$("#DueDate").datepicker();
In the end I went with eAccelerator - the speed boost, the smaller memory footprint and the fact that is was very easy to install swayed me. It also has a nice web-based front end to clear the cache and provide some stats.
The fact that its not maintained anymore is not an issue for me - it works, and that's all I care about. In the future, if it breaks PHP6 (or whatever), then I'll re-evaluate my decision and probably go with APC simply because its been adopted by the PHP developers (so should be even easier to install)
According to official docs:
This may help if you want the HTTP headers that the server responded with. All header names are lower cased and can be accessed using the bracket notation. Example: response.headers['content-type']
will give something like: headers: {},
let osVersion = NSProcessInfo.processInfo().operatingSystemVersion
let versionString = osVersion.majorVersion.description + "." + osVersion.minorVersion.description + "." + osVersion.patchVersion.description
print(versionString)
One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?
Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...
<div id="checkboxes">
<input type="checkbox" /> Some label<br />
<input type="checkbox" /> Some other label<br />
</div>
<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
Based on this markup your jquery could bind to the click
event of the button and manipulate the DOM.
$('#addCheckbox').click(function() {
var text = $('#newCheckText').val();
$('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});
I've created a library with a custom view to solve this issue, and it should be very simple to use. See https://github.com/Comcast/DahDit for more. You can add dashed lines like this:
<com.xfinity.dahdit.DashedLine
android:layout_width="250dp"
android:layout_height="wrap_content"
app:dashHeight="4dp"
app:dashLength="8dp"
app:minimumDashGap="3dp"
app:layout_constraintRight_toRightOf="parent"
android:id="@+id/horizontal_dashes"/>
This worked for me
yum install mysql
It will install mysql client and then
pip install mysqlclient
Since you return to the client just String
and its content type == 'text/plain'
, there is no any chance for default converters to determine how to convert String
response to the FFSampleResponseHttp
object.
The simple way to fix it:
expected-response-type
from <int-http:outbound-gateway>
replyChannel1
<json-to-object-transformer>
Otherwise you should write your own HttpMessageConverter
to convert the String to the appropriate object.
To make it work with MappingJackson2HttpMessageConverter
(one of default converters) and your expected-response-type
, you should send your reply with content type = 'application/json'
.
If there is a need, just add <header-enricher>
after your <service-activator>
and before sending a reply to the <int-http:inbound-gateway>
.
So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.
UPDATE
OK. Since you changed your server to return FfSampleResponseHttp
object as HTTP response, not String, just add contentType = 'application/json'
header before sending the response for the HTTP and MappingJackson2HttpMessageConverter
will do the stuff for you - your object will be converted to JSON and with correct contentType
header.
From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"
and MappingJackson2HttpMessageConverter
should do the stuff for you again.
Of course you should remove <json-to-object-transformer>
from you message flow after <int-http:outbound-gateway>
.
The following assumes that your hours and minutes are stored as ints in variables named hh
and mm
respectively.
if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) &&
(hh < END_HOUR || (hh == END_HOUR && mm <= END_MINUTE))) {
...
}
1) PostgreSQL DESCRIBE TABLE using psql
In psql command line tool, \d table_name or \d+ table_name to find the information on columns of a table
2) PostgreSQL DESCRIBE TABLE using information_schema
SELECT statement to query the column_names,datatype,character maximum length of the columns table in the information_schema database;
SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where table_name = 'tablename';
For more information https://www.postgresqltutorial.com/postgresql-describe-table/
You can use .is()
.
if( $('#leftmenu').is(':empty') ) {
// ...
Or you could just test the length
property to see if one was found.
if( $('#leftmenu:empty').length ) {
// ...
Keep in mind that empty means no white space either. If there's a chance that there will be white space, then you can use $.trim()
and check for the length of the content.
if( !$.trim( $('#leftmenu').html() ).length ) {
// ...
If your bound property is DateTime, then all you need is
Binding={Property, StringFormat=d}
There's the global attribute called hidden
. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
stuff hidden by default_x000D_
</div>
_x000D_
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
I found the problem, here's the script of the slow and fast versions of the stored procedure:
dbo.ViewOpener__RenamedForCruachan__Slow.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
dbo.ViewOpener__RenamedForCruachan__Fast.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:
Slow: SET ANSI_NULLS OFF
Fast: SET ANSI_NULLS ON
This answer also could be made to make sense, since the view does have a join clause that says:
(table.column IS NOT NULL)
So there is some NULL
s involved.
The explanation is further proved by returning to Query Analizer, and running
SET ANSI_NULLS OFF
.
DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'
.
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
And the query is slow.
So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off
, rather than ANSI_NULLS on
, which is QA's default.
Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS
option in the stored procedure dialog:
Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....
See http://www.w3schools.com/tags/att_input_accept.asp:
The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage
The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).
Note: The accept attribute can only be used with
<input type="file">
.Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.
Syntax
<input accept="audio/*|video/*|image/*|MIME_type" />
Tip: To specify more than one value, separate the values with a comma (e.g.
<input accept="audio/*,video/*,image/*" />
.
It's worth noting that your code does insert a space
h2::after {
content: " ";
}
However, it's immediately removed.
From Anonymous inline boxes,
White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.
And from The 'white-space' processing model,
If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
So if you don't want the space to be removed, set white-space
to pre
or pre-wrap
.
h2 {_x000D_
text-decoration: underline;_x000D_
}_x000D_
h2.space::after {_x000D_
content: " ";_x000D_
white-space: pre;_x000D_
}
_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>
_x000D_
Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.
The C5 Generic Collections Library classes all support the AddRange
method. C5 has a much more robust interface that actually exposes all of the features of its underlying implementations and is interface-compatible with the System.Collections.Generic
ICollection
and IList
interfaces, meaning that C5
's collections can be easily substituted as the underlying implementation.
CREATE SCHEMA is a synonym for CREATE DATABASE. CREATE DATABASE Syntax
Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:
#include <iostream>
#include <unordered_map>
class Hashtable {
std::unordered_map<const void *, const void *> htmap;
public:
void put(const void *key, const void *value) {
htmap[key] = value;
}
const void *get(const void *key) {
return htmap[key];
}
};
int main() {
Hashtable ht;
ht.put("Bob", "Dylan");
int one = 1;
ht.put("one", &one);
std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}
Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
A more readable variant using an extension.
extension Dictionary {
func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
var mutableCopy = self
for (key, value) in dict {
// If both dictionaries have a value for same key, the value of the other dictionary is used.
mutableCopy[key] = value
}
return mutableCopy
}
}
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
Edit: As in a comment rightly requested here some more information. Use the include
tag
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/yourlayout" />
to include the layout you want to reuse.
Check this link out...
Uninstalling the application would be enough to avoid this problem.
INSTALL_FAILED_UPDATE_INCOMPATIBLE
but sometimes even uninstalling the message is raised again, it occurs in Android OS 5.0 +, so this is the solution:
Go to Settings
> Apps
and you will find your app with the message:
We have to uninstall manually for all users!, then we can install our compiled application with no problems.
Remove the old application and install again.
Use Android Debug Bridge command:
adb uninstall [PACKAGE NAME]
ping -n 11 -w 1000 127.0.0.1 > nul
Update
Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.
If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)
$value = (float) $xml->code[0]->lat;
Also, (int)
for integer number:
$value = (int) $xml->code[0]->distance;
Swift 3 & 4:
You can create a extension on DispatchQueue and add function delay which uses DispatchQueue asyncAfter function internally
extension DispatchQueue {
static func delay(_ delay: DispatchTimeInterval, closure: @escaping () -> ()) {
let timeInterval = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: timeInterval, execute: closure)
}
}
use:
DispatchQueue.delay(.seconds(1)) {
print("This is after delay")
}
THe easiest way to do so is:
function findChild(idOfElement, idOfChild){
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
or better readable:
findChild = (idOfElement, idOfChild) => {
let element = document.getElementById(idOfElement);
return element.querySelector(`[id=${idOfChild}]`);
}
The acepted Answer is very detailed and correct in most of the cases.
I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.
To solve it, i made this PHP function:
function load_utf8_file($filePath)
{
$response = null;
try
{
if (file_exists($filePath)) {
$text = file_get_contents($filePath);
$response = preg_replace("/^\xEF\xBB\xBF/", '', $text);
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
}
finally{ }
return $response;
}
Then i use it like this to load a JSON file and get a value from it:
$str = load_utf8_file('appconfig.json');
$json = json_decode($str, true);
//print_r($json);
echo $json['prod']['deploy']['hostname'];
This might work for you (GNU sed):
sed -ri '/\s+$/s///' file
This looks for whitespace at the end of the line and and if present removes it.
I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.
That would lead to the reduced table definition:
CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);
Other have hit this one on the head:
main(int argc, char **argv)
give you direct access to the command line (after it has been mangled and tokenized by the shell)getopt()
and getopt_long()
but as you've seen the code to use them is a bit wordy, and quite idomatic. I generally push it out of view with something like:
typedef
struct options_struct {
int some_flag;
int other_flage;
char *use_file;
} opt_t;
/* Parses the command line and fills the options structure,
* returns non-zero on error */
int parse_options(opt_t *opts, int argc, char **argv);
Then first thing in main:
int main(int argc, char **argv){
opt_t opts;
if (parse_options(&opts,argc,argv)){
...
}
...
}
Or you could use one of the solutions suggested in Argument-parsing helpers for C/UNIX.
Without a look at your exact JSON output, it's hard to give you some working code. This tutorial is very useful, but you could use something along the lines of:
JSONObject jsonObj = new JSONObject("yourJsonString");
Then you can retrieve from this json object using:
String value = jsonObj.getString("yourKey");
library(stringi)
group <- c('12357e', '12575e', '12575e', ' 197e18', 'e18947')
pattern <- "e"
replacement <- ""
group <- str_replace(group, pattern, replacement)
group
[1] "12357" "12575" "12575" " 19718" "18947"
Read this doc which will explain to you what to do.
https://devcenter.heroku.com/articles/buildpacks
Setting a buildpack on an application
You can change the buildpack used by an application by setting the buildpack value.
When the application is next pushed, the new buildpack will be used.$ heroku buildpacks:set heroku/php
Buildpack set. Next release on random-app-1234 will use heroku/php.
Rungit push heroku master
to create a new release using this buildpack.
This is whay its not working for you since you did not set it up.
... When the application is next pushed, the new buildpack will be used.
You may also specify a buildpack during app creation
:
$ heroku create myapp --buildpack heroku/python
I've used enumeration to handle this problem.
storage = ''
for num, value in enumerate(result, start=0):
content = value
if 'A' == content:
storage = result[num + 1]
I've used num as Index here, when it finds the correct value it adds up one to the current index of actual list. Which allows me to maneuver to the next index.
I hope this helps your purpose.
To answer the exact question of finding a free port (which is what I needed in my unit tests) in dotnet core 3.1 I came up this
public static int GetAvailablePort(IPAddress ip) {
TcpListener l = new TcpListener(ip, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
Log.Info($"Available port found: {port}");
return port;
}
note: based the comment by @user207421 about port zero I searched and found this and slightly modified it.
Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.
http://api.jquery.com/load/ This is a simple solution if you don't need any POST data.
async function FileToString (file) {
try {
let res = await file.raw.text();
console.log(res);
} catch (err) {
throw err;
}
}
Use the RIGHT function... e.g.
DECLARE @testnum TINYINT
SET @testnum = 3
PRINT RIGHT('00' + CONVERT(VARCHAR(2), @testnum), 2)
With Graphical User Interface (GUI) in Xcode, you can do the following:
- Go to "
Attribute Inspector
" and setLines
value to0
. By default, it is set to1
.- The Label text can be written in multi-line by hitting
option + return
.
- Now, go to "
Size Inspector
" and set thewidth
,height
,X
&Y
position
of the Label.
That's all.
(I) Super Key – An attribute or a combination of attribute that is used to identify the records uniquely is known as Super Key. A table can have many Super Keys.
E.g. of Super Key
So on as any combination which can identify the records uniquely will be a Super Key.
(II) Candidate Key – It can be defined as minimal Super Key or irreducible Super Key. In other words an attribute or a combination of attribute that identifies the record uniquely but none of its proper subsets can identify the records uniquely.
E.g. of Candidate Key
For above table we have only two Candidate Keys (i.e. Irreducible Super Key) used to identify the records from the table uniquely. ID Key can identify the record uniquely and similarly combination of Name and Address can identify the record uniquely, but neither Name nor Address can be used to identify the records uniquely as it might be possible that we have two employees with similar name or two employees from the same house.
(III) Primary Key – A Candidate Key that is used by the database designer for unique identification of each row in a table is known as Primary Key. A Primary Key can consist of one or more attributes of a table.
E.g. of Primary Key - Database designer can use one of the Candidate Key as a Primary Key. In this case we have “ID” and “Name, Address” as Candidate Key, we will consider “ID” Key as a Primary Key as the other key is the combination of more than one attribute.
(IV) Foreign Key – A foreign key is an attribute or combination of attribute in one base table that points to the candidate key (generally it is the primary key) of another table. The purpose of the foreign key is to ensure referential integrity of the data i.e. only values that are supposed to appear in the database are permitted.
E.g. of Foreign Key – Let consider we have another table i.e. Department Table with Attributes “Department_ID”, “Department_Name”, “Manager_ID”, ”Location_ID” with Department_ID as an Primary Key. Now the Department_ID attribute of Employee Table (dependent or child table) can be defined as the Foreign Key as it can reference to the Department_ID attribute of the Departments table (the referenced or parent table), a Foreign Key value must match an existing value in the parent table or be NULL.
(V) Composite Key – If we use multiple attributes to create a Primary Key then that Primary Key is called Composite Key (also called a Compound Key or Concatenated Key).
E.g. of Composite Key, if we have used “Name, Address” as a Primary Key then it will be our Composite Key.
(VI) Alternate Key – Alternate Key can be any of the Candidate Keys except for the Primary Key.
E.g. of Alternate Key is “Name, Address” as it is the only other Candidate Key which is not a Primary Key.
(VII) Secondary Key – The attributes that are not even the Super Key but can be still used for identification of records (not unique) are known as Secondary Key.
E.g. of Secondary Key can be Name, Address, Salary, Department_ID etc. as they can identify the records but they might not be unique.
This issue may also occur if you have multiple versions of the same support library android-support-v4.jar
. If your project is using other library projects that contain different-2 versions of the support library. To resolve the issue keep the same version of support library at each place.
The nuget commandline tool does not come with the vsix file, it's a separate download
The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(
There is a simpler solution to this. What you describe is the natural behavior of the &
operator and can thus be done primatively:
> c(1,1,NA) & c(1,0,NA) & c(1,NA,NA)
[1] TRUE FALSE NA
If all are 1, then 1 is returned. If any are 0, then 0. If all are NA, then NA.
In your case, the code would be:
DF$Den<-DF$Denial1 & DF$Denial2 & DF$Denial3
In order for this to work, you will need to stop working in character
and use numeric
or logical
types.
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
If you are using Talend MDM Server, the login is: login: admin password: talend
See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server
This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.
AES Algorithm:
public static class CryptographyProvider
{
public static string EncryptString(string plainText, out string Key)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
using (Aes _aesAlg = Aes.Create())
{
Key = Convert.ToBase64String(_aesAlg.Key);
ICryptoTransform _encryptor = _aesAlg.CreateEncryptor(_aesAlg.Key, _aesAlg.IV);
using (MemoryStream _memoryStream = new MemoryStream())
{
_memoryStream.Write(_aesAlg.IV, 0, 16);
using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, _encryptor, CryptoStreamMode.Write))
{
using (StreamWriter _streamWriter = new StreamWriter(_cryptoStream))
{
_streamWriter.Write(plainText);
}
return Convert.ToBase64String(_memoryStream.ToArray());
}
}
}
}
public static string DecryptString(string cipherText, string Key)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(Key))
throw new ArgumentNullException("Key");
string plaintext = null;
byte[] _initialVector = new byte[16];
byte[] _Key = Convert.FromBase64String(Key);
byte[] _cipherTextBytesArray = Convert.FromBase64String(cipherText);
byte[] _originalString = new byte[_cipherTextBytesArray.Length - 16];
Array.Copy(_cipherTextBytesArray, 0, _initialVector, 0, _initialVector.Length);
Array.Copy(_cipherTextBytesArray, 16, _originalString, 0, _cipherTextBytesArray.Length - 16);
using (Aes _aesAlg = Aes.Create())
{
_aesAlg.Key = _Key;
_aesAlg.IV = _initialVector;
ICryptoTransform decryptor = _aesAlg.CreateDecryptor(_aesAlg.Key, _aesAlg.IV);
using (MemoryStream _memoryStream = new MemoryStream(_originalString))
{
using (CryptoStream _cryptoStream = new CryptoStream(_memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader _streamReader = new StreamReader(_cryptoStream))
{
plaintext = _streamReader.ReadToEnd();
}
}
}
}
return plaintext;
}
}
No need to convert. You can apply conditions on Enums inside a switch. Like so,
public enum Operator
{
PLUS,
MINUS,
MULTIPLY,
DIVIDE
}
public double Calculate(int left, int right, Operator op)
{
switch (op)
{
case Operator.PLUS: return left + right;
case Operator.MINUS: return left - right;
case Operator.MULTIPLY: return left * right;
case Operator.DIVIDE: return left / right;
default: return 0.0;
}
}
Then, call it like this:
Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));
Finally you are getting a char
array
with alphabet. Why did you do so hard way using a loop
?
It is just
char[] alphabet=new char[]{'a','b',.........,'z'}
Watcher with the deep option didn't work for me.
Instead, I use updated() lifecycle hook which gets executed everytime the component's data changes. Just use it like you do with mounted().
mounted() {
/* to be executed when mounted */
},
updated() {
console.log(this.$route)
}
For your reference, visit the documentation.
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
No you are not required to close anything BUT the connection. Per JDBC specs closing any higher object will automatically close lower objects. Closing Connection
will close any Statement
s that connection has created. Closing any Statement
will close all ResultSet
s that were created by that Statement
. Doesn't matter if Connection
is poolable or not. Even poolable connection has to clean before returning to the pool.
Of course you might have long nested loops on the Connection
creating lots of statements, then closing them is appropriate. I almost never close ResultSet
though, seems excessive when closing Statement
or Connection
WILL close them.
A very fast implementation of the Sieve of Atkin is Dan Bernstein's primegen. This sieve is more efficient than the Sieve of Eratosthenes. His page has some benchmark information.
Thanks to Hallgrim, here is the code I ended up with:
ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(),
IntPtr.Zero,
System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(width, height));
I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.If you want to ensure only that class will match then use getClass() ==
. If you want to match subclasses then instanceof
is needed.
Also, instanceof will not match against a null but is safe to compare against a null. So you don't have to null check it.
if ( ! (obj instanceof MyClass) ) { return false; }
Just to document:
The callback argument previousRoute
is having a property called $route
which is much similar to the $route
service.
Unfortunately currentRoute
argument, is not having much information about the current route.
To overcome this i have tried some thing like this.
$routeProvider.
when('/', {
controller:...,
templateUrl:'...',
routeName:"Home"
}).
when('/menu', {
controller:...,
templateUrl:'...',
routeName:"Site Menu"
})
Please note that in the above routes config a custom property called routeName
is added.
app.run(function($rootScope, $route){
//Bind the `$routeChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.
$rootScope.$on('$routeChangeSuccess', function(currentRoute, previousRoute) {
//This will give the custom property that we have defined while configuring the routes.
console.log($route.current.routeName)
})
})
An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.
A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.
Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.
Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.
Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try
-catch
inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:
bool thread_done = false;
void *thread_function(void *arg)
{
void *res = nullptr;
try
{
res = real_thread_function(arg);
}
catch (...)
{
}
thread_done = true;
return res;
}
The webdriver
will wait for a page to load by default via .get()
method.
As you may be looking for some specific element as @user227215 said, you should use WebDriverWait
to wait for an element located in your page:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
try:
myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
print "Page is ready!"
except TimeoutException:
print "Loading took too much time!"
I have used it for checking alerts. You can use any other type methods to find the locator.
EDIT 1:
I should mention that the webdriver
will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url')
, your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver
does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions
.
You can use the below:
public class HashmapKeyExist {
public static void main(String[] args) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("1", "Bala");
hmap.put("2", "Test");
Boolean cantain = hmap.containsValue("Bala");
if(hmap.containsKey("2") && hmap.containsValue("Test"))
{
System.out.println("Yes");
}
if(cantain == true)
{
System.out.println("Yes");
}
Set setkeys = hmap.keySet();
Iterator it = setkeys.iterator();
while(it.hasNext())
{
String key = (String) it.next();
if (hmap.get(key).equals("Bala"))
{
System.out.println(key);
}
}
}
}
You have two possibilities (for an IPv4 address) :
varchar(15)
, if your want to store the IP address as a string
192.128.0.15
for instanceinteger
(4 bytes), if you convert the IP address to an integer
3229614095
for the IP I used before
The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).
About those manipulations, see the ip2long()
and long2ip()
functions, on the PHP-side, or inet_aton()
and inet_ntoa()
on the MySQL-side.
I really suggest you to use the Glide library. It's among the most efficient way to generate and display a video thumbnail for a local video file.
Just add this line to your gradle file :
compile 'com.github.bumptech.glide:glide:3.7.0'
And it will become as simple as :
String filePath = "/storage/emulated/0/Pictures/example_video.mp4";
Glide
.with( context )
.load( Uri.fromFile( new File( filePath ) ) )
.into( imageViewGifAsBitmap );
You can find more informations here : https://futurestud.io/blog/glide-displaying-gifs-and-videos
Cheers !
If your textView
is allowed to grow as tall as the content, then
textView.isScrollEnabled = false
should just work with autolayout.
If you want to remain the textView
to be scrollable, you need to add an optional height constraint,
internal lazy var textViewHeightConstraint: NSLayoutConstraint = {
let constraint = self.textView.heightAnchor.constraint(equalToConstant: 0)
constraint.priority = .defaultHigh
return constraint
}()
public override func layoutSubviews() {
super.layoutSubviews()
// Assuming there is width constraint setup on the textView.
let targetSize = CGSize(width: textView.frame.width, height: CGFloat(MAXFLOAT))
textViewHeightConstraint.constant = textView.sizeThatFits(targetSize).height
}
The reason to override layoutSubviews()
is to make sure the textView is laid out properly horizontally so we can rely on the width to calculate the height.
Since the height constraint is set to a lower priority, if it runs out space vertically the actual height of the textView
will be less than the contentSize
. And the textView will be scrollable.
a = 0.000006;
b = 6;
c = a/b;
textbox.Text = c.ToString("0.000000");
As you requested:
textbox.Text = c.ToString("0.######");
This will only display out to the 6th decimal place if there are 6 decimals to display.
ArrayAdapter uses a TextView to display each item within it. Behind the scenes, it uses the toString()
method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is:
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.
For your use, I would suggest that you use the constructor:
ArrayAdapter(Context context, int resource, T[] objects).
In your case, this would be:
ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)
and it should be fine. This will bind each string to the default TextView display - plain and simple white background.
So to answer your question, you do not have to use the textViewResourceId.
A more public way is by calling get_form in Admin classes. It also works for non-database fields too. For example here i have a field called '_terminal_list' on the form that can be used in special cases for choosing several terminal items from get_list(request), then filtering based on request.user:
class ChangeKeyValueForm(forms.ModelForm):
_terminal_list = forms.ModelMultipleChoiceField(
queryset=Terminal.objects.all() )
class Meta:
model = ChangeKeyValue
fields = ['_terminal_list', 'param_path', 'param_value', 'scheduled_time', ]
class ChangeKeyValueAdmin(admin.ModelAdmin):
form = ChangeKeyValueForm
list_display = ('terminal','task_list', 'plugin','last_update_time')
list_per_page =16
def get_form(self, request, obj = None, **kwargs):
form = super(ChangeKeyValueAdmin, self).get_form(request, **kwargs)
qs, filterargs = Terminal.get_list(request)
form.base_fields['_terminal_list'].queryset = qs
return form
By close, do you mean you want the current instance of the console app to close, or do you want the application process, to terminate? Missed that all important exit code:
Environment.Exit(0);
Or to close the current instance of the form:
this.Close();
Useful link.
I would suggest to kill the port number. It worked for me
netstat -ano | findstr :yourPortNumber taskkill /PID typeyourPIDhere /F
That would be:
b.rstrip('\n')
If you want to strip space from each and every line, you might consider instead:
a.read().splitlines()
This will give you a list of lines, without the line end characters.
My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts.
// Ensurs that a element (usually a div) stays on the screen
// aElementToStick = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
var $elementToStick = $(aElementToStick);
var top = $elementToStick.offset().top;
var origPosition = $elementToStick.css('position');
function positionFloater(a$Win) {
// Set the original position to allow the browser to adjust the horizontal position
$elementToStick.css('position', origPosition);
// Test how far down the page is scrolled
var scrollTop = a$Win.scrollTop();
// If the page is scrolled passed the top of the element make it stick to the top of the screen
if (top < scrollTop) {
// Get the horizontal position
var left = $elementToStick.offset().left;
// Set the positioning as fixed to hold it's position
$elementToStick.css('position', 'fixed');
// Reuse the horizontal positioning
$elementToStick.css('left', left);
// Hold the element at the top of the screen
$elementToStick.css('top', 0);
}
}
// Perform initial positioning
positionFloater($(window));
// Reposition when the window resizes
$(window).resize(function (e) {
positionFloater($(this));
});
// Reposition when the window scrolls
$(window).scroll(function (e) {
positionFloater($(this));
});
};
In my case this was because a file named ociw32.dll had been placed in c:\windows\system32. This is however only allowed to exist in c:\oracle\11.2.0.3\bin.
Deleting the file from system32, which had been placed there by an installation of Crystal Reports, fixed this issue
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14