To view entries in Drupal's own internal log system (the watchdog
database table), go to http://example.com/admin/reports/dblog. These can include Drupal-specific errors as well as general PHP or MySQL errors that have been thrown.
Use the watchdog()
function to add an entry to this log from your own custom module.
When Drupal bootstraps it uses the PHP function set_error_handler()
to set its own error handler for PHP errors. Therefore, whenever a PHP error occurs within Drupal it will be logged through the watchdog()
call at admin/reports/dblog
. If you look for PHP fatal errors, for example, in /var/log/apache/error.log
and don't see them, this is why. Other errors, e.g. Apache errors, should still be logged in /var/log
, or wherever you have it configured to log to.
This was so annoying. Open your project, click on Target, Open Build Phases tab. Check your Copy Bundle Resources for any red items.
Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles,
For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).
def pr(s):
try:
print(s)
except UnicodeEncodeError:
for c in s:
try:
print( c, end='')
except UnicodeEncodeError:
print( '?', end='')
NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!
Using code to parse ps aux
for linux and tasklist
for windows are your best options, until something more general comes along.
For windows, you can reference: http://www.rgagnon.com/javadetails/java-0593.html
Linux can pipe the results of ps aux
through grep
too, which would make processing/searching quick and easy. I'm sure you can find something similar for windows too.
$.each($('input[type=number]'),function(){
alert($(this).val());
});
This will alert the value of input type number
fields
Demo is present at http://jsfiddle.net/2dJAN/33/
I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:
echo $SHELL
Output
/bin/zsh
OR
/bin/bash
If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.
In case you need to check against any amount of whitespace, not just single space, you can do this:
To strip string of extra white space (also condences whitespace in the middle to one space):
trimmed=`echo -- $original`
The --
ensures that if $original
contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put ""
around $original
, or the spaces will not get removed.
After that you can just check if $trimmed
is empty.
[ -z "$trimmed" ] && echo "empty!"
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters «
and »
just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
var i = 1, p = document.getElementById("form_part"+1);_x000D_
while (p !== null){_x000D_
if (i === n){_x000D_
p.style.display = "";_x000D_
}_x000D_
else{_x000D_
p.style.display = "none";_x000D_
}_x000D_
i++;_x000D_
p = document.getElementById("form_part"+i);_x000D_
}_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
var sum =_x000D_
parseInt(document.getElementById("num1").value) +_x000D_
parseInt(document.getElementById("num2").value) +_x000D_
parseInt(document.getElementById("num3").value);_x000D_
_x000D_
alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
Part 1<br>_x000D_
<input type="number" value="1" id="num1"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
Part 2<br>_x000D_
<input type="number" value="2" id="num2"><br>_x000D_
<button type="button" onclick="shows_form_part(1)">«</button>_x000D_
<button type="button" onclick="shows_form_part(3)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
Part 3<br>_x000D_
<input type="number" value="3" id="num3"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">«</button>_x000D_
<button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
Try with code:
this.state.items[1] = 'new value';
var cloneObj = Object.assign({}, this.state.items);
this.setState({items: cloneObj });
Because it's all just about memory, in the end all the numerical values are stored in binary.
A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s.
When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative.
An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.
From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.
This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.
Html (you'll have to put the onclick attribute on every input you want it to work for on the page)
<input type="text" value="click the input to select" onclick="this.select();"/>
OR A BETTER OPTION
jQuery (this will work for every text input on the page, no need to change your html):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>
If the performance is an issue, you can use this command in MS_DOS:
dir /OD >d:\dir.txt
This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.
Even better, you can encapsule this to clear any type of controls you want in one method, like this:
public static void EstadoControles<T>(object control, bool estado, bool limpiar = false) where T : Control
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Enabled = estado;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.Enabled = estado;
if (!limpiar) return;
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Text = string.Empty;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.EditValue = @"-1";
}
}
If none of the above solutions solved your issue like in my case (still stuck with my RestClient module facing 405 ) try to request your Api with a tool like Postman or Fiddler. I mean the problem may be elsewhere like a bad formatted request.
I discover that my RestClient module was asking a 'Put' with an Id paremeter not well formatted :
http://myserver/api/someresource?id=75fd954d-d984-4a31-82fc-8132e1644f78
instead of
http://myserver/api/someresource/75fd954d-d984-4a31-82fc-8132e1644f78
Incidiously, bad formatted request returns 405 - Method Not Allowed (IIS 7.5)
You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.
You should do two things
add spring.jackson.serialization.write-dates-as-timestamps:false
in your application.properties
this will disable converting dates to timestamps and instead use a ISO-8601 compliant format
You can than customize the format by annotating the getter method of you dateOfBirth
property with @JsonFormat(pattern="yyyy-MM-dd")
Shoud be stated on the top of the page.
Something like.
/* =========================================================
* bootstrap-modal.js v1.4.0
* http://twitter.github.com/bootstrap/javascript.html#modal
* =========================================================
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
After DAYS of digging, someone on IRC suggested that I try to use the
Windows 7.1 SDK Command Prompt
Shortcut (links to C:\Windows\System32\cmd.exe /E:ON /V:ON /T:0E /K "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd"). I think you MUST have the older 7.1 SDK (even on Windows 8.1) because the newer ones use msbuild.exe instead of vcbuild.exe which is what node-gyp wants even though it's twice as old as node at this point :/
Once in that prompt, I had to run the following to get x86 context because the compiler was throwing as error otherwise about architecture:
setenv.cmd /Release /x86
THEN I was able to successfully run npm commands that were trying to use node-gyp to recompile things.
Assume file is already created in the predefined directory with name "table.txt
"
1) change the ownership for file :
sudo chown username:username table.txt
2) change the mode of the file
sudo chmod 777 table.txt
Now, try it should work!
Only one column version
df[column_name].fillna(method='ffill', inplace=True)
df[column_name].fillna(method='backfill', inplace=True)
I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.
If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.
You can try this
func getTime() -> (hour:Int, min:Int, sec:Int) {
let currentDateTime = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour,.Minute,.Second], fromDate: currentDateTime)
let hour = components.hour
let min = components.minute
let sec = components.second
return (hour,min,sec)
}
Now call that method and receive the date with hour,min and second
let currentTime = self.getTime()
print("Hour: \(currentTime.hour) Min: \(currentTime.min) Sec: \(currentTime.sec))")
No issues with the latest kartoza/qgis-desktop
I ran
docker pull kartoza/qgis-desktop
followed by
docker run -it --rm --name "qgis-desktop-2-4" -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest
I did try multiple times without the conflict error - you do have to exit the app beforehand. Also, please note the parameters do differ slightly.
If you're doing some performance tuning it's often recommended to set both -XX:PermSize
and -XX:MaxPermSize
to the same value to increase JVM
efficiency.
Here is some information:
You can also specify -XX:+CMSClassUnloadingEnabled
to enable class unloading
option if you are using CMS
GC
. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space
I recently needed to do the same thing, and was pleased that the colspan worked fine with consecutive pipes ||
Tested on v4.5 (latest on macports) and the v5.4 (latest on homebrew). Not sure why it doesn't work on the live preview site you provide.
A simple test that I started with was:
| Header ||
|--------------|
| 0 | 1 |
using the command:
multimarkdown -t html test.md > test.html
Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string comapnyName = castedItem["CompanyName"];
int? id = castedItem["ID"];
}
Here are some other approaches you can take.
1. CTE with union:
;WITH cte AS (SELECT a, b, c FROM table1)
SELECT a AS val FROM cte
UNION SELECT b AS val FROM cte
UNION SELECT c AS val FROM cte;
2. CTE with unpivot:
;WITH cte AS (SELECT a, b, c FROM table1)
SELECT DISTINCT val
FROM cte
UNPIVOT (val FOR col IN (a, b, c)) u;
string uriPath =
"file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;
According to the curl man page:
You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.
So the simplest and most efficient (curl will send them all down a single TCP connection [those to the same origin]) approach would be put them all on a single invocation of curl e.g.:
curl http://example.com/?update_=1 http://example.com/?update_=2
I had the same problem, but with small difference. I had added NetworkConnectionCallback to check situation when internet connection had changed at runtime, and checking like this before sending all requests:
private fun isConnected(): Boolean {
val activeNetwork = cManager.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}
There can be state like CONNECTING (you can see i? when you turn on wifi, icon starts blinking, after connecting to network, image is static). So, we have two different states: one CONNECT another CONNECTING, and when Retrofit tried to send request internet connection is disabled and it throws UnknownHostException. I forgot to add another type of exception in function which was responsible for sending requests.
try{
//for example, retrofit call
}
catch (e: Exception) {
is UnknownHostException -> "Unknown host!"
is ConnectException -> "No internet!"
else -> "Unknown exception!"
}
It's just a tricky moment that can by related with this problem.
Hope, I will help somebody)
What worked for me was to change my WHERE clause into a SELECT subquery
FROM:
DELETE FROM CommentTag WHERE [dbo].CommentTag.NoteId = [dbo].FetchedTagTransferData.IssueId
TO:
DELETE FROM CommentTag WHERE [dbo].CommentTag.NoteId = (SELECT NoteId FROM FetchedTagTransferData)
I created these extensions last night:
you can pass either positive or negative values;
example:
var someDate = new Date();
var expirationDate = someDate.addDays(10);
var previous = someDate.addDays(-5);
Date.prototype.addDays = function (num) {
var value = this.valueOf();
value += 86400000 * num;
return new Date(value);
}
Date.prototype.addSeconds = function (num) {
var value = this.valueOf();
value += 1000 * num;
return new Date(value);
}
Date.prototype.addMinutes = function (num) {
var value = this.valueOf();
value += 60000 * num;
return new Date(value);
}
Date.prototype.addHours = function (num) {
var value = this.valueOf();
value += 3600000 * num;
return new Date(value);
}
Date.prototype.addMonths = function (num) {
var value = new Date(this.valueOf());
var mo = this.getMonth();
var yr = this.getYear();
mo = (mo + num) % 12;
if (0 > mo) {
yr += (this.getMonth() + num - mo - 12) / 12;
mo += 12;
}
else
yr += ((this.getMonth() + num - mo) / 12);
value.setMonth(mo);
value.setYear(yr);
return value;
}
This relative path to absolute path converter shell function
cd
and pwd
)..
and .
Code:
function abspath() {
# generate absolute path from relative path
# $1 : relative filename
# return : absolute path
if [ -d "$1" ]; then
# dir
(cd "$1"; pwd)
elif [ -f "$1" ]; then
# file
if [[ $1 = /* ]]; then
echo "$1"
elif [[ $1 == */* ]]; then
echo "$(cd "${1%/*}"; pwd)/${1##*/}"
else
echo "$(pwd)/$1"
fi
fi
}
Sample:
# assume inside /parent/cur
abspath file.txt => /parent/cur/file.txt
abspath . => /parent/cur
abspath .. => /parent
abspath ../dir/file.txt => /parent/dir/file.txt
abspath ../dir/../dir => /parent/dir # anything cd can handle
abspath doesnotexist => # empty result if file/dir does not exist
abspath /file.txt => /file.txt # handle absolute path input
Note: This is based on the answers from nolan6000 and bsingh, but fixes the file case.
I also understand that the original question was about an existing command line utility. But since this seems to be THE question on stackoverflow for that including shell scripts that want to have minimal dependencies, I put this script solution here, so I can find it later :)
The more efficient (less obtrusive) way of doing this is through custom formatting.
Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.
Suppose we haven't used the "@" operator then our code would look like this:
$fileHandle = fopen($fileName, $writeAttributes);
And what if the file we are trying to open is not found? It will show an error message.
To suppress the error message we are using the "@" operator like:
$fileHandle = @fopen($fileName, $writeAttributes);
I believe you could create you own branch (using your own credential) from the same trunk as your workmate's branch, merge from your workmate's branch to your working copy and then merge from your branch. All future commit should be marked as coming from you.
Here is an article that explains it all, with their performance difference and usage over JOINS.
SQL Server CROSS APPLY and OUTER APPLY over JOINS
As suggested in this article, there is no performance difference between them for normal join operations (INNER AND CROSS).
The usage difference arrives when you have to do a query like this:
CREATE FUNCTION dbo.fn_GetAllEmployeeOfADepartment(@DeptID AS INT)
RETURNS TABLE
AS
RETURN
(
SELECT * FROM Employee E
WHERE E.DepartmentID = @DeptID
)
GO
SELECT * FROM Department D
CROSS APPLY dbo.fn_GetAllEmployeeOfADepartment(D.DepartmentID)
That is, when you have to relate with function. This cannot be done using INNER JOIN, which would give you the error "The multi-part identifier "D.DepartmentID" could not be bound." Here the value is passed to the function as each row is read. Sounds cool to me. :)
All of the provided answers are more complicated than necessary. Assuming you are building a jar file, all you need to do is add a <jar.finalName>
tag to your <properties>
section:
<properties>
<jar.finalName>${project.name}</jar.finalName>
</properties>
This will generate a jar:
project/target/${project.name}.jar
This is in the documentation - note the User Property
:
finalName:
Name of the generated JAR.
Type: java.lang.String
Required: No
User Property: jar.finalName
Default: ${project.build.finalName}
You should also be able to use this option on the command line with:
mvn -Djar.finalName=myCustomName ...
You should get myCustomName.jar, although I haven't tested this.
If you're working with .net core, you can use the dotnet CLI, for instance
dotnet add package <package name>
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
This is the shortest code that you can use to update the app config file even if don't have a config section defined:
void UpdateAppConfig(string param)
{
var doc = new XmlDocument();
doc.Load("YourExeName.exe.config");
XmlNodeList endpoints = doc.GetElementsByTagName("endpoint");
foreach (XmlNode item in endpoints)
{
var adressAttribute = item.Attributes["address"];
if (!ReferenceEquals(null, adressAttribute))
{
adressAttribute.Value = string.Format("http://mydomain/{0}", param);
}
}
doc.Save("YourExeName.exe.config");
}
I had to restart the rails application on the production so I looked for an another answer. I have found it below:
http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger
For python3 on Ubuntu
sudo apt-get install python3-setuptools
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
The left inset is caused by Toolbar's contentInsetStart
which by default is 16dp.
Change this to 72dp to align to the keyline.
Update for support library v24.0.0:
To match the Material Design spec there's an additional attribute contentInsetStartWithNavigation
which by default is 16dp. Change this if you also have a navigation icon.
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
To complete other answers, the gem-path gem can find the installation path of a particular gem.
Installation:
gem install gem-path
Usage:
gem path rails
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-4.0.13
gem path rails '< 4'
=> /home/cbliard/.rvm/gems/ruby-2.1.5/gems/rails-3.2.21
This is really handy as you can use it to grep or edit files:
grep -R 'Internal server error' "$(gem path thin)"
subl "$(gem path thin)"
The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.
So, you should:
Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute
to map "WithActionApi" first, then "DefaultApi".
Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional }
parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".
Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.
So your route should like this:
// Map this rule first
RouteTable.Routes.MapRoute(
"WithActionApi",
"api/{controller}/{action}/{id}"
);
RouteTable.Routes.MapRoute(
"DefaultApi",
"api/{controller}/{id}",
new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);
And your controller:
[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
return "object of id id";
}
[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
return new string[] { "byCategory1", "byCategory2" };
}
var data={
userName: $('#userName').val(),
email: $('#email').val(),
//add other properties similarly
}
and
$.ajax({
type: "POST",
url: "http://rt.ja.com/includes/register.php?submit=1",
data: data
success: function(html)
{
//alert(html);
$('#userError').html(html);
$("#userError").html(userChar);
$("#userError").html(userTaken);
}
});
You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.
Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.
var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);
Target: Is an element for which we need to bring it to top svg: Is the container of elements
For a proper HTML sanitizer in JS, see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
To quote other people:
A head is simply a reference to a commit object. Each head has a name (branch name or tag name, etc). By default, there is a head in every repository called master. A repository can contain any number of heads. At any given time, one head is selected as the “current head.” This head is aliased to HEAD, always in capitals".
Note this difference: a “head” (lowercase) refers to any one of the named heads in the repository; “HEAD” (uppercase) refers exclusively to the currently active head. This distinction is used frequently in Git documentation.
Another good source that quickly covers the inner workings of git (and therefor a better understanding of heads/HEAD) can be found here. References (ref:) or heads or branches can be considered like post-it notes stuck onto commits in the commit history. Usually they point to the tip of series of commits, but they can be moved around with git checkout
or git reset
etc.
Here Is my code For Zip the folders and its sub folders and its files and make it downloadable in zip Format
function zip()
{
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ;
$include_dir = false;
$archive = 'abc.zip'// File Name ;
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive;
if (!$zip->open($archive, ZipArchive::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}
If Any Issue With the Code Let Me know.
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
The original post contains the solution (ignore the responses, they don't add anything useful). The interesting work is done by the mentioned unix command readlink
with option -f
. Works when the script is called by an absolute as well as by a relative path.
For bash, sh, ksh:
#!/bin/bash
# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=$(readlink -f "$0")
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=$(dirname "$SCRIPT")
echo $SCRIPTPATH
For tcsh, csh:
#!/bin/tcsh
# Absolute path to this script, e.g. /home/user/bin/foo.csh
set SCRIPT=`readlink -f "$0"`
# Absolute path this script is in, thus /home/user/bin
set SCRIPTPATH=`dirname "$SCRIPT"`
echo $SCRIPTPATH
See also: https://stackoverflow.com/a/246128/59087
You've to create empty constructor because JAX-RS initializes the classes... Your constructor must have no arguments:
@XmlRootElement
public class Student implements Serializable {
public String first_name;
public String last_name;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Student()
{
first_name = "Fahad";
last_name = "Mullaji";
}
public Student()
{
}
}
To enable use bind()
method
$("#id").bind("click",eventhandler);
call this handler
function eventhandler(){
alert("Bind click")
}
To disable click useunbind()
$("#id").unbind("click");
No, there is no way to create an abstract class in Objective-C.
You can mock an abstract class - by making the methods/ selectors call doesNotRecognizeSelector: and therefore raise an exception making the class unusable.
For example:
- (id)someMethod:(SomeObject*)blah
{
[self doesNotRecognizeSelector:_cmd];
return nil;
}
You can also do this for init.
After a few hours of playing with the Oracle JDK 1.6, I was able to make it work without any code change. The magic is done by Bouncy Castle to handle SSL and allow JDK 1.6 to run with TLSv1.2 by default. In theory, it could also be applied to older Java versions with eventual adjustments.
${JAVA_HOME}/jre/lib/ext
folder${JAVA_HOME}/jre/lib/security/java.security
commenting out the providers section and adding some extra lines # Original security providers (just comment it)
# security.provider.1=sun.security.provider.Sun
# security.provider.2=sun.security.rsa.SunRsaSign
# security.provider.3=com.sun.net.ssl.internal.ssl.Provider
# security.provider.4=com.sun.crypto.provider.SunJCE
# security.provider.5=sun.security.jgss.SunProvider
# security.provider.6=com.sun.security.sasl.Provider
# security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI
# security.provider.8=sun.security.smartcardio.SunPCSC
# Add the Bouncy Castle security providers with higher priority
security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
# Original security providers with different priorities
security.provider.3=sun.security.provider.Sun
security.provider.4=sun.security.rsa.SunRsaSign
security.provider.5=com.sun.net.ssl.internal.ssl.Provider
security.provider.6=com.sun.crypto.provider.SunJCE
security.provider.7=sun.security.jgss.SunProvider
security.provider.8=com.sun.security.sasl.Provider
security.provider.9=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.10=sun.security.smartcardio.SunPCSC
# Here we are changing the default SSLSocketFactory implementation
ssl.SocketFactory.provider=org.bouncycastle.jsse.provider.SSLSocketFactoryImpl
Just to make sure it's working let's make a simple Java program to download files from one URL using https.
import java.io.*;
import java.net.*;
public class DownloadWithHttps {
public static void main(String[] args) {
try {
URL url = new URL(args[0]);
System.out.println("File to Download: " + url);
String filename = url.getFile();
File f = new File(filename);
System.out.println("Output File: " + f.getName());
BufferedInputStream in = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(f.getName());
int bytesRead;
byte dataBuffer[] = new byte[1024];
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
fileOutputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Now, just compile the DownloadWithHttps.java program and execute it with your Java 1.6
${JAVA_HOME}/bin/javac DownloadWithHttps.java
${JAVA_HOME}/bin/java DownloadWithHttps https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.10/commons-lang3-3.10.jar
Important note for Windows users: This solution was tested in a Linux OS, if you are using Windows, please replace the ${JAVA_HOME}
by %JAVA_HOME%
.
List<Employee> employees = new List<Employee>()
{
new Employee{Id =1,Name="AAAAA"}
, new Employee{Id =2,Name="BBBBB"}
, new Employee{Id =3,Name="AAAAA"}
, new Employee{Id =4,Name="CCCCC"}
, new Employee{Id =5,Name="AAAAA"}
};
List<Employee> duplicateEmployees = employees.Except(employees.GroupBy(i => i.Name)
.Select(ss => ss.FirstOrDefault()))
.ToList();
While, i would completely suggest using beautiful-soup in general, if anyone is looking to display the visible parts of a malformed html (e.g. where you have just a segment or line of a web-page) for whatever-reason, the the following will remove content between <
and >
tags:
import re ## only use with malformed html - this is not efficient
def display_visible_html_using_re(text):
return(re.sub("(\<.*?\>)", "",text))
Using @property
and @attribute.setter
helps you to not only use the "pythonic" way but also to check the validity of attributes both while creating the object and when altering it.
class Person(object):
def __init__(self, p_name=None):
self.name = p_name
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
if type(new_name) == str: #type checking for name property
self._name = new_name
else:
raise Exception("Invalid value for name")
By this, you actually 'hide' _name
attribute from client developers and also perform checks on name property type. Note that by following this approach even during the initiation the setter gets called. So:
p = Person(12)
Will lead to:
Exception: Invalid value for name
But:
>>>p = person('Mike')
>>>print(p.name)
Mike
>>>p.name = 'George'
>>>print(p.name)
George
>>>p.name = 2.3 # Causes an exception
Instead of returning a resultsArray
you return a promise for a results array and then then
that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:
function resultsByName(name)
{
var Card = Parse.Object.extend("Card");
var query = new Parse.Query(Card);
query.equalTo("name", name.toString());
var resultsArray = [];
return query.find({});
}
// later
resultsByName("Some Name").then(function(results){
// access results here by chaining to the returned promise
});
You can see more examples of using parse promises with queries in Parse's own blog post about it.
import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:
$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session
or
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
use this function:
public static string ConvertDataTableToHTML(DataTable dt)
{
string html = "<table>";
//add header row
html += "<tr>";
for(int i=0;i<dt.Columns.Count;i++)
html+="<td>"+dt.Columns[i].ColumnName+"</td>";
html += "</tr>";
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
html += "<tr>";
for (int j = 0; j< dt.Columns.Count; j++)
html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
html += "</tr>";
}
html += "</table>";
return html;
}
With Eclipse and Windows:
you have to copy 2 files - xxxPROJECTxxx.properties - log4j.properties here : C:\Eclipse\CONTENER\TOMCAT\apache-tomcat-7\lib
if($('#chk_all').is(":checked"))
{
$('#'+id).attr('checked', true);
}
else
{
$('#'+id).attr('checked', false);
}
Using backtick
or qx
helps, thanks everybody for the answers. However, I found that if you use backtick
or qx
, the output contains trailing newline and I need to remove that. So I used chomp
.
chomp($host = `hostname`);
chomp($domain = `domainname`);
$fqdn = $host.".".$domain;
More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html
Starting from a byte array you can use the binary package to do the conversions.
For example if you want to read ints :
buf := bytes.NewBuffer(b) // b is []byte
myfirstint, err := binary.ReadVarint(buf)
anotherint, err := binary.ReadVarint(buf)
The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.
Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.
It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"
In the above URL after the colon gives space. I also like to support Deepak.
This helps me a lot.
$(yourSelector).find('select option:eq(0)').prop('selected', true);
I had to set
Container_height = Element1_height = Element2_height
.Container {
position: relative;
}
.ElementOne, .Container ,.ElementTwo{
width: 283px;
height: 71px;
}
.ElementOne {
position:absolute;
}
.ElementTwo{
position:absolute;
}
Use can use z-index to set which one to be on top.
My situation was a little different. The solution was to strip the .pem from everything outside of the CERTIFICATE and PRIVATE KEY sections and to invert the order which they appeared. After converting from pfx to pem file, the certificate looked like this:
Bag Attributes
localKeyID: ...
issuer=...
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
Bag Attributes
more garbage...
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
After correcting the file, it was just:
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
The GO command isn't a Transact-SQL statement, but a special command recognized by several MS utilities including SQL Server Management Studio code editor.
The GO command is used to group SQL commands into batches which are sent to the server together. The commands included in the batch, that is, the set of commands since the last GO command or the start of the session, must be logically consistent. For example, you can't define a variable in one batch and then use it in another since the scope of the variable is limited to the batch in which it's defined.
For more information, see http://msdn.microsoft.com/en-us/library/ms188037.aspx.
If you are looking for a programmatical modal creation, you might love this:
http://nakupanda.github.io/bootstrap3-dialog/
Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
Don't make it a int()
, but make it a range()
will solve this problem.
inp = range(input("Enter a number: "))
The magic method __getitem__
is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.
Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__
method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.
import copy
# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1
class Person(object):
def __init__(self, name, age, dob):
self.name = name
self.age = age
self.dob = dob
def __getitem__(self, indx):
print ("Calling __getitem__")
p = copy.copy(self)
p.name = p.name.split(" ")[indx]
p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
return p
Suppose one user input is as follows:
p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))
With the help of __getitem__
method, the user can access the indexed attributes. e.g.,
print p[0].name # print first (or last) name
print p[Y].dob # print (Date or Month or ) Year of the 'date of birth'
CN refers to class name, so put in your LDAP query CN=Users. Should work.
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
It works.
You can format the jquery date with this line:
moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");
You use attach
without detach
- every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach
or do not use attach
at all.
Nice discussion and tips are here.
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
$date = '2009-10-22';
$sepparator = '-';
$parts = explode($sepparator, $date);
$dayForDate = date("l", mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]));
UPDATE databaseName.tableName
SET columnName = replace(columnName, '?', '''')
WHERE columnName LIKE '%?%'
For me the reason I was getting NPE is that I was using Mockito.any()
when mocking primitives. I found that by switching to using the correct variant from mockito gets rid of the errors.
For example, to mock a function that takes a primitive long
as parameter, instead of using any()
, you should be more specific and replace that with any(Long.class)
or Mockito.anyLong()
.
Hope that helps someone.
If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/
Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.
One liner to create a self signed certificate:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt
strstr(request, "favicon") != NULL
How about the following 3 statements?
-- change to your schema
ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;
-- check current schema
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;
-- generate drop table statements
SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';
COPY the RESULT and PASTE and RUN.
This is primarily a long comment supporting and building on the answer by @mattway
Given:
Some of the other proposed solutions on this page advocate hitting the datastore on every request. If you hit the main datastore to validate every authentication request, then I see less reason to use JWT instead of other established token authentication mechanisms. You've essentially made JWT stateful, instead of stateless if you go to the datastore each time.
(If your site receives a high volume of unauthorized requests, then JWT would deny them without hitting the datastore, which is helpful. There are probably other use cases like that.)
Given:
Truly stateless JWT authentication cannot be achieved for a typical, real world web app because stateless JWT does not have a way to provide immediate and secure support for the following important use cases:
User's account is deleted/blocked/suspended.
User's password is changed.
User's roles or permissions are changed.
User is logged out by admin.
Any other application critical data in the JWT token is changed by the site admin.
You cannot wait for token expiration in these cases. The token invalidation must occur immediately. Also, you cannot trust the client not to keep and use a copy of the old token, whether with malicious intent or not.
Therefore: I think the answer from @matt-way, #2 TokenBlackList, would be most efficient way to add the required state to JWT based authentication.
You have a blacklist that holds these tokens until their expiration date is hit. The list of tokens will be quite small compared to the total number of users, since it only has to keep blacklisted tokens until their expiration. I'd implement by putting invalidated tokens in redis, memcached or another in-memory datastore that supports setting an expiration time on a key.
You still have to make a call to your in-memory db for every authentication request that passes initial JWT auth, but you don't have to store keys for your entire set of users in there. (Which may or may not be a big deal for a given site.)
You can get it by using document.getElementById();
var fileVal=document.getElementById("some Id");
alert(fileVal.value);
will give the value of file,but it gives with fakepath as follows
c:\fakepath\filename
EDIT: Cactus is now a dead project: http://attic.apache.org/projects/jakarta-cactus.html
You may want to look at cactus.
http://jakarta.apache.org/cactus/
Project Description
Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters, ...).
The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it.
Cactus implements an in-container strategy, meaning that tests are executed inside the container.
var value1=$("id1").val();
var value2=$("id2").val();
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
Suppose you have this file:
$ cat /tmp/test.txt
Line 1
Line 2 has leading space
Line 3 followed by blank line
Line 5 (follows a blank line) and has trailing space
Line 6 has no ending CR
There are four elements that will alter the meaning of the file output read by many Bash solutions:
If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.
Here are the methods that may change the file (in comparison to what cat
returns):
1) Lose the last line and leading and trailing spaces:
$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)
2) Using process substitution with cat
will reads the entire file in one gulp and loses the meaning of individual lines:
$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
Line 2 has leading space
Line 3 followed by blank line
Line 5 (follows a blank line) and has trailing space
Line 6 has no ending CR'
(If you remove the "
from $(cat /tmp/test.txt)
you read the file word by word rather than one gulp. Also probably not what is intended...)
The most robust and simplest way to read a file line-by-line and preserve all spacing is:
$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
' Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space '
'Line 6 has no ending CR'
If you want to strip leading and trading spaces, remove the IFS=
part:
$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'
(A text file without a terminating \n
, while fairly common, is considered broken under POSIX. If you can count on the trailing \n
you do not need || [[ -n $line ]]
in the while
loop.)
More at the BASH FAQ
I had the same problem, I fixed it by removing PATHEXT from user variable. It must only exist in System variable with .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
Also remove the variable from user to system and only include that path on user variable
Use this code --
function myFunction() {
var str = "How are you doing today?";
var res = str.split("/");
}
Try using String.Split Method:
string text = @"First line
second line
third line";
foreach (string line in text.Split('\n'))
{
// do something
}
I learned something really useful and fundamental from here.
chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.
It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter
function showPhotos() {
$(this).find("span").slideToggle();
}
$(".photos")
.on("mouseenter", "li", showPhotos)
.on("mouseleave", "li", showPhotos);
Simple ASP.NET MVC subscription form with email textbox would be implemented like that:
The data from the form is mapped to this model
public class SubscribeModel
{
[Required]
public string Email { get; set; }
}
View name should match controller method name.
@model App.Models.SubscribeModel
@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
<button type="submit">Subscribe</button>
}
Controller is responsible for request processing and returning proper response view.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Subscribe(SubscribeModel model)
{
if (ModelState.IsValid)
{
//TODO: SubscribeUser(model.Email);
}
return View("Index", model);
}
}
Here is my project structure. Please notice, "Home" views folder matches HomeController name.
Consider the case statement as well which is compatible with most sh-based shells:
case $str in
/*)
echo 1
;;
*)
echo 0
;;
esac
The documentation on counting says that for group_by
queries it is better to use func.count()
:
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
Used Rn222's answer and aknuds1's answer to use an ISearchContext that returns either a single element, or a list. And a minimum number of elements can be specified:
public static class SearchContextExtensions
{
/// <summary>
/// Method that finds an element based on the search parameters within a specified timeout.
/// </summary>
/// <param name="context">The context where this is searched. Required for extension methods</param>
/// <param name="by">The search parameters that are used to identify the element</param>
/// <param name="timeOutInSeconds">The time that the tool should wait before throwing an exception</param>
/// <returns> The first element found that matches the condition specified</returns>
public static IWebElement FindElement(this ISearchContext context, By by, uint timeOutInSeconds)
{
if (timeOutInSeconds > 0)
{
var wait = new DefaultWait<ISearchContext>(context);
wait.Timeout = TimeSpan.FromSeconds(timeOutInSeconds);
return wait.Until<IWebElement>(ctx => ctx.FindElement(by));
}
return context.FindElement(by);
}
/// <summary>
/// Method that finds a list of elements based on the search parameters within a specified timeout.
/// </summary>
/// <param name="context">The context where this is searched. Required for extension methods</param>
/// <param name="by">The search parameters that are used to identify the element</param>
/// <param name="timeoutInSeconds">The time that the tool should wait before throwing an exception</param>
/// <returns>A list of all the web elements that match the condition specified</returns>
public static IReadOnlyCollection<IWebElement> FindElements(this ISearchContext context, By by, uint timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new DefaultWait<ISearchContext>(context);
wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds);
return wait.Until<IReadOnlyCollection<IWebElement>>(ctx => ctx.FindElements(by));
}
return context.FindElements(by);
}
/// <summary>
/// Method that finds a list of elements with the minimum amount specified based on the search parameters within a specified timeout.<br/>
/// </summary>
/// <param name="context">The context where this is searched. Required for extension methods</param>
/// <param name="by">The search parameters that are used to identify the element</param>
/// <param name="timeoutInSeconds">The time that the tool should wait before throwing an exception</param>
/// <param name="minNumberOfElements">
/// The minimum number of elements that should meet the criteria before returning the list <para/>
/// If this number is not met, an exception will be thrown and no elements will be returned
/// even if some did meet the criteria
/// </param>
/// <returns>A list of all the web elements that match the condition specified</returns>
public static IReadOnlyCollection<IWebElement> FindElements(this ISearchContext context, By by, uint timeoutInSeconds, int minNumberOfElements)
{
var wait = new DefaultWait<ISearchContext>(context);
if (timeoutInSeconds > 0)
{
wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds);
}
// Wait until the current context found the minimum number of elements. If not found after timeout, an exception is thrown
wait.Until<bool>(ctx => ctx.FindElements(by).Count >= minNumberOfElements);
// If the elements were successfuly found, just return the list
return context.FindElements(by);
}
}
Example usage:
var driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://localhost");
var main = driver.FindElement(By.Id("main"));
// It can be now used to wait when using elements to search
var btn = main.FindElement(By.Id("button"), 10);
btn.Click();
// This will wait up to 10 seconds until a button is found
var button = driver.FindElement(By.TagName("button"), 10)
// This will wait up to 10 seconds until a button is found, and return all the buttons found
var buttonList = driver.FindElements(By.TagName("button"), 10)
// This will wait for 10 seconds until we find at least 5 buttons
var buttonsMin = driver.FindElements(By.TagName("button"), 10, 5);
driver.Close();
Use get_the_category()
function.
$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);
Use setState
in your view to change employed
property of state. This is example of React render engine.
someFunctionWhichChangeParamEmployed(isEmployed) {
this.setState({
employed: isEmployed
});
}
getInitialState() {
return {
employed: true
}
},
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
inside onstart command put START_STICKY
... This service won't kill unless it is doing too much task and kernel wants to kill it for it...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).
enum NSURLError: Int {
case unknown = -1
case cancelled = -999
case badURL = -1000
case timedOut = -1001
case unsupportedURL = -1002
case cannotFindHost = -1003
case cannotConnectToHost = -1004
case connectionLost = -1005
case lookupFailed = -1006
case HTTPTooManyRedirects = -1007
case resourceUnavailable = -1008
case notConnectedToInternet = -1009
case redirectToNonExistentLocation = -1010
case badServerResponse = -1011
case userCancelledAuthentication = -1012
case userAuthenticationRequired = -1013
case zeroByteResource = -1014
case cannotDecodeRawData = -1015
case cannotDecodeContentData = -1016
case cannotParseResponse = -1017
//case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
case fileDoesNotExist = -1100
case fileIsDirectory = -1101
case noPermissionsToReadFile = -1102
//case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103
// SSL errors
case secureConnectionFailed = -1200
case serverCertificateHasBadDate = -1201
case serverCertificateUntrusted = -1202
case serverCertificateHasUnknownRoot = -1203
case serverCertificateNotYetValid = -1204
case clientCertificateRejected = -1205
case clientCertificateRequired = -1206
case cannotLoadFromNetwork = -2000
// Download and file I/O errors
case cannotCreateFile = -3000
case cannotOpenFile = -3001
case cannotCloseFile = -3002
case cannotWriteToFile = -3003
case cannotRemoveFile = -3004
case cannotMoveFile = -3005
case downloadDecodingFailedMidStream = -3006
case downloadDecodingFailedToComplete = -3007
/*
case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018
case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019
case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020
case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021
case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
*/
}
Direct link to URLError.Code
in the Swift github repository, which contains the up to date list of error codes being used (github link).
Now this was a nice little puzzle - great question!
Here's an alternative to Nicola Bonelli's solution that does not rely on the non-standard typeof
operator.
Unfortunately, it does not work on GCC (MinGW) 3.4.5 or Digital Mars 8.42n, but it does work on all versions of MSVC (including VC6) and on Comeau C++.
The longer comment block has the details on how it works (or is supposed to work). As it says, I'm not sure which behavior is standards compliant - I'd welcome commentary on that.
update - 7 Nov 2008:
It looks like while this code is syntactically correct, the behavior that MSVC and Comeau C++ show does not follow the standard (thanks to Leon Timmermans and litb for pointing me in the right direction). The C++03 standard says the following:
14.6.2 Dependent names [temp.dep]
Paragraph 3
In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.
So, it looks like that when MSVC or Comeau consider the toString()
member function of T
performing name lookup at the call site in doToString()
when the template is instantiated, that is incorrect (even though it's actually the behavior I was looking for in this case).
The behavior of GCC and Digital Mars looks to be correct - in both cases the non-member toString()
function is bound to the call.
Rats - I thought I might have found a clever solution, instead I uncovered a couple compiler bugs...
#include <iostream>
#include <string>
struct Hello
{
std::string toString() {
return "Hello";
}
};
struct Generic {};
// the following namespace keeps the toString() method out of
// most everything - except the other stuff in this
// compilation unit
namespace {
std::string toString()
{
return "toString not defined";
}
template <typename T>
class optionalToStringImpl : public T
{
public:
std::string doToString() {
// in theory, the name lookup for this call to
// toString() should find the toString() in
// the base class T if one exists, but if one
// doesn't exist in the base class, it'll
// find the free toString() function in
// the private namespace.
//
// This theory works for MSVC (all versions
// from VC6 to VC9) and Comeau C++, but
// does not work with MinGW 3.4.5 or
// Digital Mars 8.42n
//
// I'm honestly not sure what the standard says
// is the correct behavior here - it's sort
// of like ADL (Argument Dependent Lookup -
// also known as Koenig Lookup) but without
// arguments (except the implied "this" pointer)
return toString();
}
};
}
template <typename T>
std::string optionalToString(T & obj)
{
// ugly, hacky cast...
optionalToStringImpl<T>* temp = reinterpret_cast<optionalToStringImpl<T>*>( &obj);
return temp->doToString();
}
int
main(int argc, char *argv[])
{
Hello helloObj;
Generic genericObj;
std::cout << optionalToString( helloObj) << std::endl;
std::cout << optionalToString( genericObj) << std::endl;
return 0;
}
In my situation, in order to include color.sh
from the same directory in init.sh
, I had to do something as follows.
. ./color.sh
Not sure why the ./
and not color.sh
directly. The content of color.sh
is as follows.
RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`
Making use of File color.sh
does not error but, the color do not display. I have tested this in Ubuntu 18.04
and the Bash
version is:
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
SELECT * FROM Table1
WHERE MAKE+MODEL+[Serial Number] not in
(select make+model+[serial number] from Table2
WHERE make+model+[serial number] IS NOT NULL)
That worked for me, where make+model+[serial number]
was one field name
I was also a bit confused between adjustResize and adjustPan when I was a beginner. The definitions given above are correct.
AdjustResize : Main activity's content is resized to make room for soft input i.e keyboard
AdjustPan : Instead of resizing overall contents of the window, it only pans the content so that the user can always see what is he typing
AdjustNothing : As the name suggests nothing is resized or panned. Keyboard is opened as it is irrespective of whether it is hiding the contents or not.
I have a created a example for better understanding
Below is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Type Here"
app:layout_constraintTop_toBottomOf="@id/button1"/>
<Button
android:id="@+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/button2"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@id/button1"
app:layout_constraintEnd_toStartOf="@id/button3"
android:layout_marginBottom="@dimen/margin70dp"/>
<Button
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/button2"
android:layout_marginBottom="@dimen/margin70dp"/>
</android.support.constraint.ConstraintLayout>
Here is the design view of the xml
AdjustResize Example below:
AdjustPan Example below:
AdjustNothing Example below:
DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:
num_rows_deleted = db.session.query(Model).delete()
Also, don't forget that the deletion won't take effect until you commit, as in this snippet:
try:
num_rows_deleted = db.session.query(Model).delete()
db.session.commit()
except:
db.session.rollback()
If you could reload this, you might be able to use dtypes argument.
pd.read_csv(..., dtype={'COL_NAME':'str'})
Use the :javascript
filter. This will generate a script tag and escape the script contents as CDATA:
!!! 5
html(lang="en")
head
title "Test"
:javascript
if (10 == 10) {
alert("working")
}
body
You can use res.render() or res.redirect() method to redirect to another page using node.js express
Eg:
var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
//This reponds a post request for the login page
app.post('/login', function (req, res) {
console.log("Got a POST request for the login");
var data = {
"email": req.body.email,
"password": req.body.password
};
console.log(data);
//Data insertion code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("college");
var query = { email: data.email };
dbo.collection("user").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
if(result[0].password == data.password)
res.redirect('dashboard.html');
else
res.redirect('login-error.html');
db.close();
});
});
});
// This responds a POST request for the add user
app.post('/insert', function (req, res) {
console.log("Got a POST request for the add user");
var data = {
"first_name" : req.body.firstName,
"second_name" : req.body.secondName,
"organization" : req.body.organization,
"email": req.body.email,
"mobile" : req.body.mobile,
};
console.log(data);
**res.render('success.html',{email:data.email,password:data.password});**
});
//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js', {scope: '/'})
.then(function (registration) {
console.log(registration);
})
.catch(function (e) {
console.error(e);
})
} else {
console.log('Service Worker is not supported in this browser.');
}
// TODO add service worker code here
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
var server = app.listen(63342, function () {
var host = server.address().host;
var port = server.address().port;
console.log("Example app listening at http://localhost:%s", port)
});
Here in the login section, If the email and password matches in the database then the site is directed to dashbaord.html otherwise we will show page-error.html using res.redirect() method. Also you can use res.render() to render a page in node.js
Generally you cannot translate from a time zone like Asia/Kolkata to a GMT offset like +05:30 or +07:00. A time zone, as the name says, is a place on earth and comprises the historic, present and known future UTC offsets used by the people in that place (for now we can regard GMT and UTC as synonyms, strictly speaking they are not). For example, Asia/Kolkata has been at offset +05:30 since 1945. During periods between 1941 and 1945 it was at +06:30 and before that time at +05:53:20 (yes, with seconds precision). Many other time zones have summer time (daylight saving time, DST) and change their offset twice a year.
Given a point in time, we can make the translation for that particular point in time, though. I should like to provide the modern way of doing that.
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZoneOffset offsetIn1944 = LocalDateTime.of(1944, Month.JANUARY, 1, 0, 0)
.atZone(zone)
.getOffset();
System.out.println("Offset in 1944: " + offsetIn1944);
ZoneOffset offsetToday = OffsetDateTime.now(zone)
.getOffset();
System.out.println("Offset now: " + offsetToday);
Output when running just now was:
Offset in 1944: +06:30 Offset now: +05:30
For the default time zone set zone
to ZoneId.systemDefault()
.
To format the offset with the text GMT
use a formatter with OOOO
(four uppercase letter O) in the pattern:
DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("OOOO");
System.out.println(offsetFormatter.format(offsetToday));
GMT+05:30
I am recommending and in my code I am using java.time, the modern Java date and time API. The TimeZone
, Calendar
, Date
, SimpleDateFormat
and DateFormat
classes used in many of the other answers are poorly designed and now long outdated, so my suggestion is to avoid all of them.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:
<html>_x000D_
<body>_x000D_
<div id="counter">5</div>_x000D_
<script>_x000D_
setInterval(function() {_x000D_
var div = document.querySelector("#counter");_x000D_
var count = div.textContent * 1 - 1;_x000D_
div.textContent = count;_x000D_
if (count <= 0) {_x000D_
window.location.replace("https://example.com");_x000D_
}_x000D_
}, 1000);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
The initial content of the counter
div is the number of seconds to wait.
Seems like both the conditions are met, perhaps key('contact') is the issue
if(store.telefon) {
detailItems.push( new DetailItem('contact', store.telefon, 'Anrufen', 'fontawesome|phone') );
}
if(store.email) {
detailItems.push( new DetailItem('contact', store.email, 'Email', 'fontawesome|envelope') );
}
Take a look on your running processes, it seems like your current Tomcat instance did not stop. It's still running and NetBeans tries to start a second Tomcat-instance. Thats the reason for your exception, you just have to stop the first instance, or deploy you code on the current running one
Summary,
Code solution: Here
Configuration solutions: Here
With the help of Mike Chaliy, I found some solutions on how to do this through code. Because this issue is going to affect pretty much all projects we deploy to a live environment I held out for a purely configuration solution. I eventually found one which details how to do it in .net 3.0 and .net 3.5.
Taken from the site, below is an example of how to alter your applications web config:
<system.serviceModel>
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="net.tcp://payroll.myorg.com:8000"/>
<add prefix="http://shipping.myorg.com:9000"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
In the above example, net.tcp://payroll.myorg.com:8000 and http://shipping.myorg.com:9000 are the only base addresses, for their respective schemes, which will be allowed to be passed through. The baseAddressPrefixFilter does not support any wildcards .
The baseAddresses supplied by IIS may have addresses bound to other schemes not present in baseAddressPrefixFilter list. These addresses will not be filtered out.
Dns solution (untested): I think that if you created a new dns entry specific to your web application, added a new web site, and gave it a single host header matching the dns entry, you would mitigate this issue altogether, and would not have to write custom code or add prefixes to your web.config file.
Update platform string.
// Created from this thread: https://gist.github.com/Jaybles/1323251
// Apple TV
if ([platform isEqualToString:@"AppleTV2,1"]) return @"Apple TV 2G";
if ([platform isEqualToString:@"AppleTV3,1"]) return @"Apple TV 3G";
if ([platform isEqualToString:@"AppleTV3,2"]) return @"Apple TV 3G";
if ([platform isEqualToString:@"AppleTV5,3"]) return @"Apple TV 4G";
// Apple Watch
if ([platform isEqualToString:@"Watch1,1"]) return @"Apple Watch";
if ([platform isEqualToString:@"Watch1,2"]) return @"Apple Watch";
// iPhone
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (GSM)";
if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (GSM/2012)";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (CDMA)";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (Global)";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (Global)";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (Global)";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7 (Global)";
if ([platform isEqualToString:@"iPhone9,3"]) return @"iPhone 7 (GSM)";
if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus (Global)";
if ([platform isEqualToString:@"iPhone9,4"]) return @"iPhone 7 Plus (GSM)";
// iPad
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (Mid 2012)";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (CDMA)";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (GSM)";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (Global)";
// iPad Air
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air (China)";
if ([platform isEqualToString:@"iPad5,3"]) return @"iPad Air 2 (WiFi)";
if ([platform isEqualToString:@"iPad5,4"]) return @"iPad Air 2 (Cellular)";
// iPad Mini
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (GSM)";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (Global)";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2 (WiFi)";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2 (Cellular)";
if ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2 (China)";
if ([platform isEqualToString:@"iPad4,7"]) return @"iPad Mini 3 (WiFi)";
if ([platform isEqualToString:@"iPad4,8"]) return @"iPad Mini 3 (Cellular)";
if ([platform isEqualToString:@"iPad4,9"]) return @"iPad Mini 3 (China)";
if ([platform isEqualToString:@"iPad5,1"]) return @"iPad Mini 4 (WiFi)";
if ([platform isEqualToString:@"iPad5,2"]) return @"iPad Mini 4 (Cellular)";
// iPad Pro
if ([platform isEqualToString:@"iPad6,3"]) return @"iPad Pro (9.7 inch/WiFi)";
if ([platform isEqualToString:@"iPad6,4"]) return @"iPad Pro (9.7 inch/Cellular)";
if ([platform isEqualToString:@"iPad6,7"]) return @"iPad Pro (12.9 inch/WiFi)";
if ([platform isEqualToString:@"iPad6,8"]) return @"iPad Pro (12.9 inch/Cellular)";
// iPod
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
if ([platform isEqualToString:@"iPod7,1"]) return @"iPod Touch 6G";
// Simulator
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
Saving (w/o exception handling code):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
Loading (w/o exception handling code):
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();
Check the complete
and naturalWidth
properties, in that order.
https://stereochro.me/ideas/detecting-broken-images-js
function IsImageOk(img) {
// During the onload event, IE correctly identifies any images that
// weren’t downloaded as not complete. Others should too. Gecko-based
// browsers act like NS4 in that they report this incorrectly.
if (!img.complete) {
return false;
}
// However, they do have two very useful properties: naturalWidth and
// naturalHeight. These give the true size of the image. If it failed
// to load, either of these should be zero.
if (img.naturalWidth === 0) {
return false;
}
// No other way of checking: assume it’s ok.
return true;
}
I have faced the same issue and also not using virtual environment. easy_install is working for me.
easy_install boto3
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
Your syntax is slightly wrong. Say:
*/15 * * * * command
|
|--> `*/15` would imply every 15 minutes.
*
indicates that the cron expression matches for all values of the field.
/
describes increments of ranges.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
If you want to find all records that are not NULL, and either empty or have any number of spaces, this will work:
LIKE '%\ '
Make sure that there's a space after the backslash. More info here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
You need to use the AND function for the multiple conditions:
=IF(AND(A2>=75, A2<=79),0.255,IF(AND(A2>=80, X2<=84),0.327,IF(A2>=85,0.559,0)))
Did you try <br/>
, <br><br/>
or simply \n
? <br>
should be supported according to this source, though.
I like Milingu Kilu's solution but in the same spirit I prefer
sup { vertical-align:top; line-height:100%; }
This works for setting the value of the INPUT:
strftime('%Y-%m-%dT%H:%M:%S', time())
Try the following syntax:
document.body.innerHTML += "<p>My new content</p>";
SELECT COUNT(*) FROM information_schema.tables
One more useful command:
vmstat -s | grep memory
sample output on my machine is:
2050060 K total memory
1092992 K used memory
743072 K active memory
177084 K inactive memory
957068 K free memory
385388 K buffer memory
another useful command to get memory information is:
free
sample output is:
total used free shared buffers cached
Mem: 2050060 1093324 956736 108 385392 386812
-/+ buffers/cache: 321120 1728940
Swap: 2095100 2732 2092368
One observation here is that, the command free
gives information about swap space also.
The following link may be useful for you:
http://www.linuxnix.com/find-ram-details-in-linuxunix/
You can do this with PureBasic and MsScriptControl
All you need to do is pasting the MsScriptControl to the Purebasic editor and add something like this below
InitScriptControl()
SCtr_AddCode("MsgBox 1")
Was asked here before: Unix command to find lines common in two files
You could also try with perl (credit goes here)
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
quick solution could be:
SELECT your_db_column_name from "your_db_schema_name"."your_db_tabel_name";
Observe if the view has the model required:
View
@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>
<div class="row">
<table class="table table-striped table-hover table-width-custom">
<thead>
<tr>
....
Controller
[HttpGet]
public ActionResult ListItems()
{
SiteStore site = new SiteStore();
site.GetSites();
IEnumerable<SiteViewModel> sites =
site.SitesList.Select(s => new SiteViewModel
{
Id = s.Id,
Type = s.Type
});
return PartialView("_ListItems", sites);
}
In my case I Use a partial view but runs in normal views
row.IsNull("column")
More efficient (faster) to use Buffer.BlockCopy
over Array.CopyTo
,
int[] x = new int [] { 1, 2, 3};
int[] y = new int [] { 4, 5 };
int[] z = new int[x.Length + y.Length];
var byteIndex = x.Length * sizeof(int);
Buffer.BlockCopy(x, 0, z, 0, byteIndex);
Buffer.BlockCopy(y, 0, z, byteIndex, y.Length * sizeof(int));
I wrote a simple test program that "warms up the Jitter", compiled in release mode and ran it without a debugger attached, on my machine.
For 10,000,000 iterations of the example in the question
Concat took 3088ms
CopyTo took 1079ms
BlockCopy took 603ms
If I alter the test arrays to two sequences from 0 to 99 then I get results similar to this,
Concat took 45945ms
CopyTo took 2230ms
BlockCopy took 1689ms
From these results I can assert that the CopyTo
and BlockCopy
methods are significantly more efficient than Concat
and furthermore, if performance is a goal, BlockCopy
has value over CopyTo
.
To caveat this answer, if performance doesn't matter, or there will be few iterations choose the method you find easiest. Buffer.BlockCopy
does offer some utility for type conversion beyond the scope of this question.
I was having trouble getting this to work alongside background colours and accessory views in the cell. Ended up having to:
1) Set the cells background view property with a UIView set with a background colour.
let view = UIView()
view.backgroundColor = UIColor.white
self.backgroundView = view
2) Re-position this view in layoutSubviews to add the idea of spacing
override func layoutSubviews() {
super.layoutSubviews()
backgroundView?.frame = backgroundView?.frame.inset(by: UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0)) ?? CGRect.zero
}
I had this problem, too.
Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.
This sometimes happen if you remove Java from your path variables. To set the PATH variable again, add the full path of the jdk\bin directory to the PATH variable. Typically, the full path is:
C:\Program Files\Java\jdk-11\bin
To set the PATH variable on Microsoft Windows:
If you use Eclipse Collections you can use the collectIf()
method.
MutableList<Integer> source =
Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);
MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);
Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);
It evaluates eagerly and should be a bit faster than using a Stream.
Note: I am a committer for Eclipse Collections.
You can achieve this by adding border class of bootstrap
like for border left ,you can use border-left
working code
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="one"><h5>Rich Media Ad Production</h5><img src="images/richmedia.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="two"><h5>Web Design & Development</h5> <img src="images/web.png" ></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="three"><h5>Mobile Apps Development</h5> <img src="images/mobile.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center rightspan border-bottom" id="four"><h5>Creative Design</h5> <img src="images/mobile.png"> </div>
<div class="col-xs-12"><hr></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="five"><h5>Web Analytics</h5> <img src="images/analytics.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="six"><h5>Search Engine Marketing</h5> <img src="images/searchengine.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="seven"><h5>Mobile Apps Development</h5> <img src="images/socialmedia.png"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center rightspan" id="eight"><h5>Quality Assurance</h5> <img src="images/qa.png"></div>
<hr>
</div>
for more refrence al bootstrap classes all classes ,search for border
When you use mysql_fetch_object
, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field
instead of mysql_fetch_object
, that will give you the first field of the result set (id
in your case). The docs are here
If you have two unix timestamps, you can use this function (made a little more verbose for the sake of clarity):
// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
var firstDate = new Date(timeStampA * 1000);
var secondDate = new Date(timeStampB * 1000);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
return diffDays;
};
Example:
daysBetween(1096580303, 1308713220); // 2455
This should solve your problem:
select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);
Give a look also as this SQL Fiddle for test.
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
One of the best compressors (not specifically an obfuscator) is the YUI Compressor.
To resolve this issue:
The jstl jar
should be in your classpath. If you are using maven, add a dependency to jstl in your pom.xml
using the snippet provided here. If you are not using maven, download the jstl jar from here and deploy it into your WEB-INF/lib
.
Make sure you have the following taglib directive at the top of your jsp
:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
To verify this:-
<div class="Caption">
Model saved
</div>
Write this -
//div[contains(@class, 'Caption') and text()='Model saved']
And to verify this:-
<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
Save to server successful
</div>
Write this -
//div[@id='alertLabel' and text()='Save to server successful']
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
VLOOKUP deosnt work for String literals
In my case your docker service might be stopped
Command to start docker service:
$ sudo systemctl start docker
Command to verify if it start:
$ sudo docker run hello-world
The best "Pythonic" way to do this, exploiting the with
statement, is listed as Example #6 in PEP 343, which gives the background of the statement.
@contextmanager
def opened_w_error(filename, mode="r"):
try:
f = open(filename, mode)
except IOError, err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
Used as follows:
with opened_w_error("/etc/passwd", "a") as (f, err):
if err:
print "IOError:", err
else:
f.write("guido::0:0::/:/bin/sh\n")
I had same probleme but i fixed it by:
When putting a script file into a page, make sure it is
<script></script> and not <script />.
I have followed this: http://forums.asp.net/t/1742435.aspx?An+element+with+id+form1+could+not+be+found+Script+error+on+page+load
Hope this will help
Did you try to chomp the $str1
and $str2
?
I found a similar issue with using (another) $str1
eq 'Y' and it only went away when I first did:
chomp($str1);
if ($str1 eq 'Y') {
....
}
works after that.
Hope that helps.
You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.
Something like:
...
watch: {
leaveType () {
this.whateverMethod(this.leaveType)
}
},
methods: {
onChange() {
console.log('The new value is: ', this.leaveType)
}
}
The circumflex inside the square brackets means all characters except the subsequent range. You want a circumflex outside of square brackets.
As Matt Clark stated above
However, origin might not be set, so skip the deleting step and simply attempting to add can clear this up.
git remote add origin <"clone">
Where "clone" is simply going into your GitHub repo and copying the "HTTPS clone URL" and pasting into GitBash
Simple solution for all your web service requests, assuming you're using jQuery:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
// you can use originalOptions.type || options.type to restrict specific type of requests
options.data = jQuery.param($.extend(originalOptions.data||{}, {
timeStamp: new Date().getTime()
}));
});
Read more about the jQuery prefilter call here.
If you aren't using jQuery, check the docs for your library of choice. They may have similar functionality.
For better explain Dave Morrissey's answer I have made these steps for wrap with Console Output class in a laravel facade.
1) Create a Facade in your prefer folder (in my case app\Facades):
class ConsoleOutput extends Facade {
protected static function getFacadeAccessor() {
return 'consoleOutput';
}
}
2) Register a new Service Provider in app\Providers as follow:
class ConsoleOutputServiceProvider extends ServiceProvider
{
public function register(){
App::bind('consoleOutput', function(){
return new \Symfony\Component\Console\Output\ConsoleOutput();
});
}
}
3) Add all this stuffs in config\app.php file, registering the provider and alias.
'providers' => [
//other providers
App\Providers\ConsoleOutputServiceProvider::class
],
'aliases' => [
//other aliases
'ConsoleOutput' => App\Facades\ConsoleOutput::class,
],
That's it, now in any place of your Laravel application, just call your method in this way:
ConsoleOutput::writeln('hello');
Hope this help you.
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
If CURLOPT_FAILONERROR
is false
, http errors will not trigger curl
errors.
<?php
if (@$_GET['curl']=="yes") {
header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
$ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response=curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errno= curl_errno($ch);
if ($http_status==503)
echo "HTTP Status == 503 <br/>";
echo "Curl Errno returned $curl_errno <br/>";
}
When you do from socket import *
python is loading a socket
module to the current namespace. Thus you can use module's members as if they are defined within your current python module.
When you do import socket
, a module is loaded in a separate namespace. When you are accessing its members, you should prefix them with a module name. For example, if you want to refer to a socket
class, you will need to write client_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
.
As for the problem with timeout - all you need to do is to change except socket.Timeouterror:
to except timeout:
, since timeout
class is defined inside socket
module and you have imported all its members to your namespace.
See below, would welcome anyones feedback on the below code.
not common between two arrays:
List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());
Common between two arrays:
List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());
Is this what you are after?
MatchCollection matches = Regex.Matches(mystring, "-");
var opsys = process.platform;
if (opsys == "darwin") {
opsys = "MacOS";
} else if (opsys == "win32" || opsys == "win64") {
opsys = "Windows";
} else if (opsys == "linux") {
opsys = "Linux";
}
console.log(opsys) // I don't know what linux is.
const os = require("os"); // Comes with node.js
console.log(os.type());
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
First you need to determine the revision ID of the last known commit. You can use HEAD^
or HEAD~{1}
if you know you need to reverse exactly one commit.
git reset --hard <revision_id_of_last_known_good_commit>
git push --force
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
Firstly, you shouldn't have multiple elements with the same ID on a page - ID should be unique.
You could just remove the id attribute and and replace it with:
<input type='text' name='task'>
and to get an array of the values of task do
var taskArray = new Array();
$("input[name=task]").each(function() {
taskArray.push($(this).val());
});
if your node_modules got installed in say /home/UserName/ like in my case,
your package-lock.json file will also be there. just delete this file, go back to your app folder and run npm init
and then npm install <pkgname>
(e.g express) and a new node_modules folder will be created for your.
"The use of the checkbox is to determine what Item in the Listview that I selected"
Just add the tag to checkbox using setTag() method in the Adapter class. and other side using getTag() method.
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ServiceHelper helper=userServices.get(position);
holder.tvServiceName.setText(helper.getServiceName());
if(!helper.isServiceStatus()){
holder.btnAdd.setVisibility(View.VISIBLE);
holder.btnAdd.setTag(helper.getServiceName());
holder.checkBoxServiceStatus.setVisibility(View.INVISIBLE);
}else{
holder.checkBoxServiceStatus.setVisibility(View.VISIBLE);
//This Line
holder.checkBoxServiceStatus.setTag(helper.getServiceName());
holder.btnAdd.setVisibility(View.INVISIBLE);
}
}
In xml code of the checkbox just put the "android:onClick="your method""attribute.
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="checkboxClicked"
android:id="@+id/checkBox_Service_row"
android:layout_marginRight="5dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
In your class Implement that method "your method".
protected void checkboxClicked(View view)
{
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
}
}
import platform
platform.architecture()
From the Python docs:
Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
You're missing a reference to System.Linq.
Add
using System.Linq
to get access to the ToList() function on the current code file.
To give a little bit of information over why this is necessary, Enumerable.ToList<TSource>
is an extension method. Extension methods are defined outside the original class that it targets. In this case, the extension method is defined on System.Linq
namespace.
If you are just getting started with a new project then I would suggest that you use PDO instead of the old odbc_exec()
approach. Here is a simple example:
<?php
$bits = 8 * PHP_INT_SIZE;
echo "(Info: This script is running as $bits-bit.)\r\n\r\n";
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Gord\\Desktop\\foo.accdb;';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql =
"SELECT AgentName FROM Agents " .
"WHERE ID < ? AND AgentName <> ?";
$sth = $dbh->prepare($sql);
// query parameter value(s)
$params = array(
5,
'Homer'
);
$sth->execute($params);
while ($row = $sth->fetch()) {
echo $row['AgentName'] . "\r\n";
}
NOTE: The above approach is sufficient if you do not need to support Unicode characters above U+00FF
. If you do need to support such characters then neither PDO_ODBC
nor the old odbc_
functions will work; you'll need to use the solution described in this answer.
Set the second TextInput
focus, when the previous TextInput
's onSubmitEditing
is triggered.
Try this
Adding a Ref to second TextInput
ref={(input) => { this.secondTextInput = input; }}
Bind focus function to first TextInput's onSubmitEditing event.
onSubmitEditing={() => { this.secondTextInput.focus(); }}
Remember to set blurOnSubmit to false, to prevent keyboard flickering.
blurOnSubmit={false}
When all done, it should looks like this.
<TextInput
placeholder="FirstTextInput"
returnKeyType="next"
onSubmitEditing={() => { this.secondTextInput.focus(); }}
blurOnSubmit={false}
/>
<TextInput
ref={(input) => { this.secondTextInput = input; }}
placeholder="secondTextInput"
/>
Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.
Let me explain using step-by-step guidance.
First, download the source code from https://github.com/rmtheis/tess-two.
Import all three projects. After importing you will get an error.
To solve the error you have to create a res
folder in the tess-two project
First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"
After doing this in all three project the error should be gone.
Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.
Now you just need to import it into your workspace, but first you have to download android-ndk from this site:
http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file
Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable
Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture
done it
Now open cmd and go to on D:\Android Workspace\tess-two like below
If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:
Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest
Import test-two in this and run OCRTest and run it; you will get the best example of OCR.
You could do it this way but it leaves it as a varchar
declare @s varchar(50)
set @s = '2011-09-28 18:01:00'
select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)
or
select convert(varchar(20), @s, 105)
A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field
L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.
Try this
<input type="submit"
value="HOME"
onclick="goHome()"
style="font-size : 20px; width: 100%; height: 100px;" />
While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date
object instead of a datetime.datetime
. So for those searching and finding this thread:
datetime.date
has no .strptime
method; use the one on datetime.datetime
instead and then call .date()
on it to receive the datetime.date
object.
Like so:
>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)
The problem is with Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
this line. The Class qualified name is wrong
It is sqlserver.jdbc
not jdbc.sqlserver
The answer has already been here. If you don't want to use any library, you can follow these steps:
Explanation:
In onCreateViewHolder
method we can check viewType
and depending on the value (our "special" kind) inflate a special layout.
For example:
public static final int TITLE = 0;
public static final int ITEM = 1;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (context == null) {
context = parent.getContext();
}
if (viewType == TITLE) {
view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_title, parent,false);
return new TitleElement(view);
} else if (viewType == ITEM) {
view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_item, parent,false);
return new ItemElement(view);
}
return null;
}
where class ItemElement
and class TitleElement
can look like ordinary ViewHolder
:
public class ItemElement extends RecyclerView.ViewHolder {
//TextView text;
public ItemElement(View view) {
super(view);
//text = (TextView) view.findViewById(R.id.text);
}
So the idea of all of that is interesting. But i am interested if it's effectively, cause we need to sort the data list. And i think this will take the speed down. If any thoughts about it, please write me :)
And also the opened question : is how to hold the "special" layout on the top, while the items are recycling. Maybe combine all of that with CoordinatorLayout
.
No simple way AFAIK. If the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:
create a statement with a few (e.g. 10) parameters:
... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...
Bind all actuall parameters
setString(1,"foo"); setString(2,"bar");
Bind the rest as NULL
setNull(3,Types.VARCHAR) ... setNull(10,Types.VARCHAR)
NULL never matches anything, so it gets optimized out by the SQL plan builder.
The logic is easy to automate when you pass a List into a DAO function:
while( i < param.size() ) {
ps.setString(i+1,param.get(i));
i++;
}
while( i < MAX_PARAMS ) {
ps.setNull(i+1,Types.VARCHAR);
i++;
}
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.
If you cannot detach the production db you should use backup and restore.
You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.
You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.
This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
In summary, I've fixed the problem by putting the database file (* .db) in a subfolder.
The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
public mySentences:Array<Object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Or rather,
export interface type{
id:number;
text:string;
}
public mySentences:type[] = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary):
None < any integer < any string
Thus the check i < ''
holds True
for any integer i
.
It has been reasonably deprecated in python3. Now such comparisons end up with
TypeError: unorderable types: str() < int()
Edit: Although the return type has changed in new versions of HTML (see Tim Down's updated answer), the code below still works.
As others have said, it's a NodeList. Here's a complete, working example you can try:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function findTheOddOnes()
{
var theOddOnes = document.getElementsByClassName("odd");
for(var i=0; i<theOddOnes.length; i++)
{
alert(theOddOnes[i].innerHTML);
}
}
</script>
</head>
<body>
<h1>getElementsByClassName Test</h1>
<p class="odd">This is an odd para.</p>
<p>This is an even para.</p>
<p class="odd">This one is also odd.</p>
<p>This one is not odd.</p>
<form>
<input type="button" value="Find the odd ones..." onclick="findTheOddOnes()">
</form>
</body>
</html>
This works in IE 9, FF 5, Safari 5, and Chrome 12 on Win 7.