This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:
https://pathcopycopy.github.io/
Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:
it is because view child require two argument try like this
@ViewChild('nameInput', { static: false, }) nameInputRef: ElementRef;
@ViewChild('amountInput', { static: false, }) amountInputRef: ElementRef;
Moving tables:
First run:
SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';
-- Or suggested in the comments (did not test it myself)
SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; '
FROM dba_tables
WHERE OWNER = '<SCHEMA>'
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>
Where <schema_name>
is the name of the user.
And <tablespace_name>
is the destination tablespace.
As a result you get lines like:
ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Moving indexes:
First run:
SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;'
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';
The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.
As a result you should get something like:
ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Last but not least, moving LOBs:
First run:
SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';
This moves the LOB objects to the other tablespace.
As a result you should get something like:
ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);
Paste the results in a script or in a oracle sql developer like application and run it.
O and there is one more thing:
For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.
Enable NSZombieEnabled to know which object is being released and then accessed.
Then check if the getResultSetFromDB:
has anything to do with that. Also check if docids
has anything inside and if it is being retained.
This way you can be sure there is nothing wrong.
You can start web pages using command line in any browser typing this command
cd %your chrome directory%
start /max http://google.com
save it as bat and run it :)
Think of a table of vehicles with an integer Primary Key.
The registration number would be a candidate key.
In the real world registration numbers are subject change so it depends somewhat on the circumstances what might qualify as a candidate key.
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
Send Json data string to a web address and get a result with method post
in C#
public string SendJsonToUrl(string Url, string StrJsonData)
{
if (Url == "" || StrJsonData == "") return "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = StrJsonData.Length;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(StrJsonData);
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
}
catch (Exception exp)
{
throw new Exception("SendJsonToUrl", exp);
}
}
in PHP
<?php
$input = file_get_contents('php://input');
$json = json_decode($input ,true);
?>
The correct syntax ( as tested in VS 2008 SP1), is this:
public static class ErrorCode
{
public static IDictionary<string, string> ErrorCodeDic;
static ErrorCode()
{
ErrorCodeDic = new Dictionary<string, string>()
{ {"1", "User name or password problem"} };
}
}
The short and straightforward answer would be because char[]
is mutable while String
objects are not.
Strings
in Java are immutable objects. That is why they can't be modified once created, and therefore the only way for their contents to be removed from memory is to have them garbage collected. It will be only then when the memory freed by the object can be overwritten, and the data will be gone.
Now garbage collection in Java doesn't happen at any guaranteed interval. The String
can thus persist in memory for a long time, and if a process crashes during this time, the contents of the string may end up in a memory dump or some log.
With a character array, you can read the password, finish working with it as soon as you can, and then immediately change the contents.
Im using a custom image instead of the default title text to the right of my apps logo. This is set up programatically like
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setCustomView(R.layout.include_ab_txt_logo);
actionBar.setDisplayShowCustomEnabled(true);
The issues with the above answers for me are @Cliffus's suggestion does not work for me due to the issues others have outlined in the comments and while @dushyanth programatic padding setting may have worked in the past I would think that the fact that the spacing is now set using android:layout_marginEnd="8dip"
since API 17 manually setting the padding should have no effect. See the link he posted to git to verify its current state.
A simple solution for me is to set a negative margin on my custom view in the actionBar, like so android:layout_marginLeft="-14dp"
. A quick test shows it works for me on 2.3.3 and 4.3 using ActionBarCompat
Hope this helps someone!
Just substitute "user", "pass", "SSHD_IP". And create a file called known_hosts.txt with the content of the server's ~/.ssh/known_hosts. You will get a shell.
public class Known_Hosts {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
jsch.setKnownHosts("known_hosts.txt");
Session session = jsch.getSession("user", "SSHD_IP", 22);
session.setPassword("pass");
session.connect();
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
} catch (Exception e) {
System.out.println(e);
}
}
}
https://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html also has charts for locating methods and constructors.
div {
display: flex;
flex-direction: row;
}
was the solution that worked for me. In some cases with div
-lists this is needed.
some alternative direction values are row-reverse, column, column-reverse, unset, initial, inherit
which do the things you expect them to do
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
Update
data
was re-introduced in RC.4
How do I pass data in Angular 2 components while using Routing?
I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.
I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!
UIView+Border.h:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface UIView (Border)
-(void)setBorderColor:(UIColor *)color;
-(void)setBorderWidth:(CGFloat)width;
-(void)setCornerRadius:(CGFloat)radius;
@end
UIView+Border.m:
#import "UIView+Border.h"
@implementation UIView (Border)
// Note: cannot use synthesize in a Category
-(void)setBorderColor:(UIColor *)color
{
self.layer.borderColor = color.CGColor;
}
-(void)setBorderWidth:(CGFloat)width
{
self.layer.borderWidth = width;
}
-(void)setCornerRadius:(CGFloat)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = radius > 0;
}
@end
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)From the documentation on http://curl.haxx.se/docs/httpscripting.html :
HTTP Authentication
curl --user name:password http://www.example.com
Put a file to a HTTP server with curl:
curl --upload-file uploadfile http://www.example.com/receive.cgi
Send post data with curl:
curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi
I've found an example on the internet.
Some guy wrote this code and worked perfectly
HTML
<div ng-cloak ng-app="ManagerApp">
<div id="MainWrap" class="container" ng-controller="ManagerCtrl">
<span class="label label-info label-ext">Exposing Controller Function outside the module via onClick function call</span>
<button onClick='ajaxResultPost("Update:Name:With:JOHN","accept",true);'>click me</button>
<br/> <span class="label label-warning label-ext" ng-bind="customParams.data"></span>
<br/> <span class="label label-warning label-ext" ng-bind="customParams.type"></span>
<br/> <span class="label label-warning label-ext" ng-bind="customParams.res"></span>
<br/>
<input type="text" ng-model="sampletext" size="60">
<br/>
</div>
</div>
JAVASCRIPT
var angularApp = angular.module('ManagerApp', []);
angularApp.controller('ManagerCtrl', ['$scope', function ($scope) {
$scope.customParams = {};
$scope.updateCustomRequest = function (data, type, res) {
$scope.customParams.data = data;
$scope.customParams.type = type;
$scope.customParams.res = res;
$scope.sampletext = "input text: " + data;
};
}]);
function ajaxResultPost(data, type, res) {
var scope = angular.element(document.getElementById("MainWrap")).scope();
scope.$apply(function () {
scope.updateCustomRequest(data, type, res);
});
}
*I did some modifications, see original: font JSfiddle
Did you try to allow it for this directory via .htaccess?
Options +Indexes
I use this for some of my directories where directory listing is disabled by my provider
JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.
Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .
To stop this behaviour we need to return the function to onClick.
The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!
Use -
onClick={() => { this.props.removeTaskFunction(todo) }}
which means-
var onClick = function() {
return this.props.removeTaskFunction(todo);
}.bind(this);
You want to use coalesce()
:
where coalesce(email, email2) like '%[email protected]%'
If you want to handle empty strings ('') versus NULL, a case works:
where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'
And, if you are worried about the string really being just spaces:
where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'
As an aside, the sample if
statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));
You can create your own conversion function:
static long ToLong(string lNumber)
{
if (string.IsNullOrEmpty(lNumber))
throw new Exception("Not a number!");
char[] chars = lNumber.ToCharArray();
long result = 0;
bool isNegative = lNumber[0] == '-';
if (isNegative && lNumber.Length == 1)
throw new Exception("- Is not a number!");
for (int i = (isNegative ? 1:0); i < lNumber.Length; i++)
{
if (!Char.IsDigit(chars[i]))
{
if (chars[i] == '.' && i < lNumber.Length - 1 && Char.IsDigit(chars[i+1]))
{
var firstDigit = chars[i + 1] - 48;
return (isNegative ? -1L:1L) * (result + ((firstDigit < 5) ? 0L : 1L));
}
throw new InvalidCastException($" {lNumber} is not a valid number!");
}
result = result * 10 + ((long)chars[i] - 48L);
}
return (isNegative ? -1L:1L) * result;
}
It can be improved further:
The smallest one I know is lighttpd.
Security, speed, compliance, and flexibility -- all of these describe lighttpd (pron. lighty) which is rapidly redefining efficiency of a webserver; as it is designed and optimized for high performance environments. With a small memory footprint compared to other web-servers, effective management of the cpu-load, and advanced feature set (FastCGI, SCGI, Auth, Output-Compression, URL-Rewriting and many more) lighttpd is the perfect solution for every server that is suffering load problems. And best of all it's Open Source licensed under the revised BSD license.
Edit: removed Windows version link, now a spam/malware plugin site.
In pandas you can do str.len
with your boundary and using the Boolean result to filter it .
df[df['column name'].str.len().lt(2)]
I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.
dangerouslySetInnerHtml
to embed the <video>
code. For example:<div dangerouslySetInnerHTML={{ __html: `
<video class="video-js" playsinline autoplay loop muted>
<source src="../video_path.mp4" type="video/mp4"/>
</video>`}}
/>
Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)
list(cursor)
works because a cursor is an iterable; you can also use cursor
in a loop:
for row in cursor:
# ...
A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall()
has to return the full list instead.
There is little point in using list(cursor)
over cursor.fetchall()
; the end effect is then indeed the same, but you wasted an opportunity to stream results instead.
This is the only command that worked for me. (I got it from M 8.0 documentation)
ALTER USER 'root'@'*' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOURPASSWORD';
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
export default class App extends Component {
render() {
return (
<View>// you need to wrap the two Views an another View
<View style={styles.box1}></View>
<View style={styles.box2}></View>
</View>
);
}
}
const styles = StyleSheet.create({
box1:{
height:100,
width:100,
backgroundColor:'red'
},
box2:{
height:100,
width:100,
backgroundColor:'green',
position: 'absolute',
top:10,
left:30
},
});
That's because itoa
isn't a standard function. Try snprintf
instead.
char str[LEN];
snprintf(str, LEN, "%d", 42);
PostgreSQL automatically creates indexes on primary keys and unique constraints, but not on the referencing side of foreign key relationships.
When Pg creates an implicit index it will emit a NOTICE
-level message that you can see in psql
and/or the system logs, so you can see when it happens. Automatically created indexes are visible in \d
output for a table, too.
The documentation on unique indexes says:
PostgreSQL automatically creates an index for each unique constraint and primary key constraint to enforce uniqueness. Thus, it is not necessary to create an index explicitly for primary key columns.
and the documentation on constraints says:
Since a DELETE of a row from the referenced table or an UPDATE of a referenced column will require a scan of the referencing table for rows matching the old value, it is often a good idea to index the referencing columns. Because this is not always needed, and there are many choices available on how to index, declaration of a foreign key constraint does not automatically create an index on the referencing columns.
Therefore you have to create indexes on foreign-keys yourself if you want them.
Note that if you use primary-foreign-keys, like 2 FK's as a PK in a M-to-N table, you will have an index on the PK and probably don't need to create any extra indexes.
While it's usually a good idea to create an index on (or including) your referencing-side foreign key columns, it isn't required. Each index you add slows DML operations down slightly, so you pay a performance cost on every INSERT
, UPDATE
or DELETE
. If the index is rarely used it may not be worth having.
This answer is a summary of comments; but it really deserves its own answer.
The accepted answer (by @BjarkeCK) works, but as written, there is a maximum allowable page height of about 120 inches — roughly the height of 11 normal sized pages. So this is not a perfect solution.
However, there is a hack. You have to edit the source code of your local browser which renders the Page-Sizer settings window and either increase or delete the max
attribute for the page height input. As shown in the following screen shot.
To access the source code you need to edit, position your cursor inside the custom height field, right-click, then choose inspect element.
Note that you also have to delete all the page breaks in your original document otherwise no data will render after the first one.
You can easily create your own serializer
var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);
string Serialize<T>(T o)
{
var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;
var jv = JValue.FromObject(o);
return new JObject(new JProperty(attr.Title, jv)).ToString();
}
You need to tell the compiler it has been declared:
declare var bootbox: any;
If you have better type information you can add that too, in place of any
.
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
I use this: it uses temporary file but goes deeply in a directory until it find a regular file and return it.
# find for a quasi-random file in a directory tree:
# directory to start search from:
ROOT="/";
tmp=/tmp/mytempfile
TARGET="$ROOT"
FILE="";
n=
r=
while [ -e "$TARGET" ]; do
TARGET="$(readlink -f "${TARGET}/$FILE")" ;
if [ -d "$TARGET" ]; then
ls -1 "$TARGET" 2> /dev/null > $tmp || break;
n=$(cat $tmp | wc -l);
if [ $n != 0 ]; then
FILE=$(shuf -n 1 $tmp)
# or if you dont have/want to use shuf:
# r=$(($RANDOM % $n)) ;
# FILE=$(tail -n +$(( $r + 1 )) $tmp | head -n 1);
fi ;
else
if [ -f "$TARGET" ] ; then
rm -f $tmp
echo $TARGET
break;
else
# is not a regular file, restart:
TARGET="$ROOT"
FILE=""
fi
fi
done;
I am not an expert in python but you could try: say
i = (1,2)
res = lambda i: (i[1],i[0])
print 'res(1, 2) = {0}'.format(res(1, 2))
above would give o/p as:
res(1, 2) = (2,1)
Below command will work in command prompt:
copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y
To Copy all files:
copy c:\folder\*.* \\dest-machine\destfolder /Z /Y
There are several ways.
awk has a system()
function that will run a shell command:
system("cmd")
You can print to a pipe:
print "blah" | "cmd"
You can have awk construct commands, and pipe all the output to the shell:
awk 'some script' | sh
forceUpdate();
method will work but it is advisable to use setState();
For me such issue occur when I had multiple export
statements in single .ts
file...
The error message
Cannot 'squash' without a previous commit
means you likely attempted to “squash downward.” Git always squashes a newer commit into an older commit or “upward” as viewed on the interactive rebase todo list, that is into a commit on a previous line. Changing the command on your todo list’s very first line to squash
will always produce this error as there is nothing for the first commit to squash into.
First get back to where you started with
$ git rebase --abort
Say your history is
$ git log --pretty=oneline
a931ac7c808e2471b22b5bd20f0cad046b1c5d0d c
b76d157d507e819d7511132bdb5a80dd421d854f b
df239176e1a2ffac927d8b496ea00d5488481db5 a
That is, a was the first commit, then b, and finally c. After committing c we decide to squash b and c together:
(Note: Running git log
pipes its output into a pager, less
by default on most platforms. To quit the pager and return to your command prompt, press the q
key.)
Running git rebase --interactive HEAD~2
gives you an editor with
pick b76d157 b
pick a931ac7 c
# Rebase df23917..a931ac7 onto df23917
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
(Notice that this todo list is in the reverse order as compared with the output of git log
.)
Changing b’s pick
to squash
will result in the error you saw, but if instead you squash c into b (newer commit into the older or “squashing upward”) by changing the todo list to
pick b76d157 b
squash a931ac7 c
and save-quitting your editor, you'll get another editor whose contents are
# This is a combination of 2 commits.
# The first commit's message is:
b
# This is the 2nd commit message:
c
When you save and quit, the contents of the edited file become commit message of the new combined commit:
$ git log --pretty=oneline
18fd73d3ce748f2a58d1b566c03dd9dafe0b6b4f b and c
df239176e1a2ffac927d8b496ea00d5488481db5 a
Interactive rebase rewrites history. Attempting to push to a remote that contains the old history will fail because it is not a fast-forward.
If the branch you rebased is a topic or feature branch in which you are working by yourself, no big deal. Pushing to another repository will require the --force
option, or alternatively you may be able, depending on the remote repository’s permissions, to first delete the old branch and then push the rebased version. Examples of those commands that will potentially destroy work is outside the scope of this answer.
Rewriting already-published history on a branch in which you are working with other people without very good reason such as leaking a password or other sensitive details forces work onto your collaborators and is antisocial and will annoy other developers. The “Recovering From an Upstream Rebase” section in the git rebase
documentation explains, with added emphasis.
Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history. This section explains how to do the fix from the downstream’s point of view. The real fix, however, would be to avoid rebasing the upstream in the first place. …
A lot of big examples, let me explain in clear and crispy way.
ViewModel = Model that is created to serve the view.
ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.
View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.
Few examples of View Models are below
ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.
The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.
Here is a small example of List data using ViewModel.
Hope this will be useful.
Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.
//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
Note that it automatically adds ellipses, if you don't want that just use '\\1'
as the second parameter for the preg_replace
call.
You can't set the value
of a file
input in the markup, like you did with value="123"
.
This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/
If you want a fragment solution, I have made a fork of android-color-picker where DialogFragment is used and is re-created on configuration change. Here's the link: https://github.com/lomza/android-color-picker
Here are couple of utility functions I use to do just this.
/**
* sets all the time related fields to ZERO!
*
* @param date
*
* @return Date with hours, minutes, seconds and ms set to ZERO!
*/
public static Date zeroTime( final Date date )
{
return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
}
/**
* Set the time of the given Date
*
* @param date
* @param hourOfDay
* @param minute
* @param second
* @param ms
*
* @return new instance of java.util.Date with the time set
*/
public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
gc.set( Calendar.MINUTE, minute );
gc.set( Calendar.SECOND, second );
gc.set( Calendar.MILLISECOND, ms );
return gc.getTime();
}
I found the solution on this page: https://github.com/MrRio/jsPDF/issues/434 From the user: wangzhixuan
I copy the solution here: // suppose your picture is already in a canvas
var imgData = canvas.toDataURL('image/png');
/*
Here are the numbers (paper width and height) that I found to work.
It still creates a little overlap part between the pages, but good enough for me.
if you can find an official number from jsPDF, use them.
*/
var imgWidth = 210;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save( 'file.pdf');?
Just use this code as the basis of a simple JQuery plugin.
$.extend({
distinct : function(anArray) {
var result = [];
$.each(anArray, function(i,v){
if ($.inArray(v, result) == -1) result.push(v);
});
return result;
}
});
Use as so:
$.distinct([0,1,2,2,3]);
Check out http://www.asciitable.com/
Look at the Hx
, (Hex) column; 2C
maps to ,
Any unusual encoding can be checked this way
+----+-----+----+-----+----+-----+----+-----+
| Hx | Chr | Hx | Chr | Hx | Chr | Hx | Chr |
+----+-----+----+-----+----+-----+----+-----+
| 00 | NUL | 20 | SPC | 40 | @ | 60 | ` |
| 01 | SOH | 21 | ! | 41 | A | 61 | a |
| 02 | STX | 22 | " | 42 | B | 62 | b |
| 03 | ETX | 23 | # | 43 | C | 63 | c |
| 04 | EOT | 24 | $ | 44 | D | 64 | d |
| 05 | ENQ | 25 | % | 45 | E | 65 | e |
| 06 | ACK | 26 | & | 46 | F | 66 | f |
| 07 | BEL | 27 | ' | 47 | G | 67 | g |
| 08 | BS | 28 | ( | 48 | H | 68 | h |
| 09 | TAB | 29 | ) | 49 | I | 69 | i |
| 0A | LF | 2A | * | 4A | J | 6A | j |
| 0B | VT | 2B | + | 4B | K | 6B | k |
| 0C | FF | 2C | , | 4C | L | 6C | l |
| 0D | CR | 2D | - | 4D | M | 6D | m |
| 0E | SO | 2E | . | 4E | N | 6E | n |
| 0F | SI | 2F | / | 4F | O | 6F | o |
| 10 | DLE | 30 | 0 | 50 | P | 70 | p |
| 11 | DC1 | 31 | 1 | 51 | Q | 71 | q |
| 12 | DC2 | 32 | 2 | 52 | R | 72 | r |
| 13 | DC3 | 33 | 3 | 53 | S | 73 | s |
| 14 | DC4 | 34 | 4 | 54 | T | 74 | t |
| 15 | NAK | 35 | 5 | 55 | U | 75 | u |
| 16 | SYN | 36 | 6 | 56 | V | 76 | v |
| 17 | ETB | 37 | 7 | 57 | W | 77 | w |
| 18 | CAN | 38 | 8 | 58 | X | 78 | x |
| 19 | EM | 39 | 9 | 59 | Y | 79 | y |
| 1A | SUB | 3A | : | 5A | Z | 7A | z |
| 1B | ESC | 3B | ; | 5B | [ | 7B | { |
| 1C | FS | 3C | < | 5C | \ | 7C | | |
| 1D | GS | 3D | = | 5D | ] | 7D | } |
| 1E | RS | 3E | > | 5E | ^ | 7E | ~ |
| 1F | US | 3F | ? | 5F | _ | 7F | DEL |
+----+-----+----+-----+----+-----+----+-----+
This should works:
Step1:
defaultConfig {
applicationId "service.ingreens.com.gpsautoon"
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
Step 2:
compile 'com.android.support:multidex:1.0.1'
Step 3: Take another class
public class MyApplication extends MultiDexApplication {
}
Step 4: Add this line on manifest
<application
android:name="android.support.multidex.MultiDexApplication">
</application>
If only certain files need access to the modules in lib, just add a require statement to the files that need it. For example, if one model needs to access one module, add:
require 'mymodule'
at the top of the model.rb file.
Do you have access to the SQL Server you are querying? Can you see a Table or View called dbo.Projects there? If not, that would be a good place to look.
Linq to SQL creates an object map between the database and the application. If your new DLL that you're deploying doesn't match with the database anymore, then this is the sort of error you'd expect to get.
Do you perhaps have different database schemas between your development environment and the deployment environment?
The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD]
.
CJK Radicals Supplement is a Unicode block containing alternative, often positional, forms of the Kangxi radicals. They are used headers in dictionary indices and other CJK ideograph collections organized by radical-stroke.
Kanbun is a Unicode block containing annotation characters used in Japanese copies of classical Chinese texts, to indicate reading order.
CJK Unified Ideographs Extension-A is a Unicode block containing rare Han ideographs.
CJK Unified Ideographs is a Unicode block containing the most common CJK ideographs used in modern Chinese and Japanese.
CJK Compatibility Ideographs is a Unicode block created to contain Han characters that were encoded in multiple locations in other established character encodings, in addition to their CJK Unified Ideographs assignments, in order to retain round-trip compatibility between Unicode and those encodings.
For the details please refer to here, and the extensions are provided in other answers.
Bubbling
Event propagate to the upto root element is **BUBBLING**.
Capturing
Event propagate from body(root) element to eventTriggered Element is **CAPTURING**.
Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.
Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.
One thing to consider might be a "ForTest" suffix:
internal void DoThisForTest(string name)
{
DoThis(name);
}
private void DoThis(string name)
{
// Real implementation
}
Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.
If you've been doing performance tuning, you might have removed mod_dir. Try putting it back and that might fix your issue.
Hi please check the below link
https://www.postgresql.org/docs/current/xfunc-sql.html
EX:
CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;
Just for information, i made a little tool for Windows doing the same thing than "grep -F -x -f file1 file2" (As i haven't found anything equivalent to this command on Windows)
Here it is : http://www.nerdzcore.com/?page=commonlines
Usage is "CommonLines inputFile1 inputFile2 outputFile"
Source code is also available (GPL)
Of course, this problem was recognized by the language designers as well. They did a lot of work and the async functions proposal finally made it into
You don't need a single then
invocation or callback function anymore, as in an asynchronous function (that returns a promise when being called) you can simply wait for promises to resolve directly. It also features arbitrary control structures like conditions, loops and try-catch-clauses, but for the sake of convenience we don't need them here:
async function getExample() {
var resultA = await promiseA(…);
// some processing
var resultB = await promiseB(…);
// more processing
return // something using both resultA and resultB
}
While we were waiting for ES8, we already did use a very similar kind of syntax. ES6 came with generator functions, which allow breaking the execution apart in pieces at arbitrarily placed yield
keywords. Those slices can be run after each other, independently, even asynchronously - and that's just what we do when we want to wait for a promise resolution before running the next step.
There are dedicated libraries (like co or task.js), but also many promise libraries have helper functions (Q, Bluebird, when, …) that do this async step-by-step execution for you when you give them a generator function that yields promises.
var getExample = Promise.coroutine(function* () {
// ^^^^^^^^^^^^^^^^^ Bluebird syntax
var resultA = yield promiseA(…);
// some processing
var resultB = yield promiseB(…);
// more processing
return // something using both resultA and resultB
});
This did work in Node.js since version 4.0, also a few browsers (or their dev editions) did support generator syntax relatively early.
However, if you want/need to be backward-compatible you cannot use those without a transpiler. Both generator functions and async functions are supported by the current tooling, see for example the documentation of Babel on generators and async functions.
And then, there are also many other compile-to-JS languages
that are dedicated to easing asynchronous programming. They usually use a syntax similar to await
, (e.g. Iced CoffeeScript), but there are also others that feature a Haskell-like do
-notation (e.g. LatteJs, monadic, PureScript or LispyScript).
Here is a code sample:
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new PInfo
{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username
}) AsEnumerable().
Select(y => new PInfo
{
ServerName = y.ServerName,
ProcessID = y.ProcessID,
UserName = y.UserName
}).ToList();
Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:
public interface ISpeak
{
public String talk();
}
public class Dog implements ISpeak
{
public String talk()
{
return "bark!";
}
}
public class Cat implements ISpeak
{
public String talk()
{
return "meow!";
}
}
Both the Cat
and Dog
class implement the ISpeak
interface.
What's great about interfaces is that we can now refer to instances of this class through the ISpeak
interface. Consider the following example:
Dog dog = new Dog();
Cat cat = new Cat();
List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();
animalsThatTalk.add(dog);
animalsThatTalk.add(cat);
for (ISpeak ispeak : animalsThatTalk)
{
System.out.println(ispeak.talk());
}
The output for this loop would be:
bark!
meow!
Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.
One of the most common interfaces used in Java, for example, is Comparable
. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.
For example:
public class Person implements Comparable<Person>
{
private String firstName;
private String lastName;
// Getters/Setters
public int compareTo(Person p)
{
return this.lastName.compareTo(p.getLastName());
}
}
Now consider this code:
// Some code in other class
List<Person> people = getPeopleList();
Collections.sort(people);
What this code did was provide a natural ordering to the Person
class. Because we implemented the Comparable
interface, we were able to leverage the Collections.sort()
method to sort our List
of Person
objects by its natural ordering, in this case, by last name.
HTML has little to no vertical positioning due to typographic nature of content layout. Vertical Rule just doesn't fit its semantics.
If you don't want to copy the array (say it is very large), you might want to create a wrapper List<Integer>
that can be used in a sort:
final int[] elements = {1, 2, 3, 4};
List<Integer> wrapper = new AbstractList<Integer>() {
@Override
public Integer get(int index) {
return elements[index];
}
@Override
public int size() {
return elements.length;
}
@Override
public Integer set(int index, Integer element) {
int v = elements[index];
elements[index] = element;
return v;
}
};
And now you can do a sort on this wrapper List using a custom comparator.
The answers here do an excellent job in defining both monoids and monads, however, they still don't seem to answer the question:
And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?
The crux of the matter that is missing here, is the different notion of "monoid", the so-called categorification more precisely -- the one of monoid in a monoidal category. Sadly Mac Lane's book itself makes it very confusing:
All told, a monad in
X
is just a monoid in the category of endofunctors ofX
, with product×
replaced by composition of endofunctors and unit set by the identity endofunctor.
Why is this confusing? Because it does not define what is "monoid in the category of endofunctors" of X
. Instead, this sentence suggests taking a monoid inside the set of all endofunctors together with the functor composition as binary operation and the identity functor as a monoidal unit. Which works perfectly fine and turns into a monoid any subset of endofunctors that contains the identity functor and is closed under functor composition.
Yet this is not the correct interpretation, which the book fails to make clear at that stage. A Monad f
is a fixed endofunctor, not a subset of endofunctors closed under composition. A common construction is to use f
to generate a monoid by taking the set of all k
-fold compositions f^k = f(f(...))
of f
with itself, including k=0
that corresponds to the identity f^0 = id
. And now the set S
of all these powers for all k>=0
is indeed a monoid "with product × replaced by composition of endofunctors and unit set by the identity endofunctor".
And yet:
S
can be defined for any functor f
or even literally for any self-map of X
. It is the monoid generated by f
.S
given by the functor composition and the identity functor has nothing do with f
being or not being a monad.And to make things more confusing, the definition of "monoid in monoidal category" comes later in the book as you can see from the table of contents. And yet understanding this notion is absolutely critical to understanding the connection with monads.
Going to Chapter VII on Monoids (which comes later than Chapter VI on Monads), we find the definition of the so-called strict monoidal category as triple (B, *, e)
, where B
is a category, *: B x B-> B
a bifunctor (functor with respect to each component with other component fixed) and e
is a unit object in B
, satisfying the associativity and unit laws:
(a * b) * c = a * (b * c)
a * e = e * a = a
for any objects a,b,c
of B
, and the same identities for any morphisms a,b,c
with e
replaced by id_e
, the identity morphism of e
. It is now instructive to observe that in our case of interest, where B
is the category of endofunctors of X
with natural transformations as morphisms, *
the functor composition and e
the identity functor, all these laws are satisfied, as can be directly verified.
What comes after in the book is the definition of the "relaxed" monoidal category, where the laws only hold modulo some fixed natural transformations satisfying so-called coherence relations, which is however not important for our cases of the endofunctor categories.
Finally, in section 3 "Monoids" of Chapter VII, the actual definition is given:
A monoid
c
in a monoidal category(B, *, e)
is an object ofB
with two arrows (morphisms)
mu: c * c -> c
nu: e -> c
making 3 diagrams commutative. Recall that in our case, these are morphisms in the category of endofunctors, which are natural transformations corresponding to precisely join
and return
for a monad. The connection becomes even clearer when we make the composition *
more explicit, replacing c * c
by c^2
, where c
is our monad.
Finally, notice that the 3 commutative diagrams (in the definition of a monoid in monoidal category) are written for general (non-strict) monoidal categories, while in our case all natural transformations arising as part of the monoidal category are actually identities. That will make the diagrams exactly the same as the ones in the definition of a monad, making the correspondence complete.
In summary, any monad is by definition an endofunctor, hence an object in the category of endofunctors, where the monadic join
and return
operators satisfy the definition of a monoid in that particular (strict) monoidal category. Vice versa, any monoid in the monoidal category of endofunctors is by definition a triple (c, mu, nu)
consisting of an object and two arrows, e.g. natural transformations in our case, satisfying the same laws as a monad.
Finally, note the key difference between the (classical) monoids and the more general monoids in monoidal categories. The two arrows mu
and nu
above are not anymore a binary operation and a unit in a set. Instead, you have one fixed endofunctor c
. The functor composition *
and the identity functor alone do not provide the complete structure needed for the monad, despite that confusing remark in the book.
Another approach would be to compare with the standard monoid C
of all self-maps of a set A
, where the binary operation is the composition, that can be seen to map the standard cartesian product C x C
into C
. Passing to the categorified monoid, we are replacing the cartesian product x
with the functor composition *
, and the binary operation gets replaced with the natural transformation mu
from
c * c
to c
, that is a collection of the join
operators
join: c(c(T))->c(T)
for every object T
(type in programming). And the identity elements in classical monoids, which can be identified with images of maps from a fixed one-point-set, get replaced with the collection of the return
operators
return: T->c(T)
But now there are no more cartesian products, so no pairs of elements and thus no binary operations.
You can convert the java.util.Date
object into a String
object, which will format the date as yyyy-mm-dd.
LocalDate has a parse
method that will convert it to a LocalDate
object. The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.
Date to LocalDate
LocalDate.parse(Date.toString())
The answer is in here :
To declare a bounded type parameter, list the type parameter's name, followed by the
extends
keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean eitherextends
(as in classes) orimplements
(as in interfaces).
So there you have it, it's a bit confusing, and Oracle knows it.
I used to use a class like this. The statusCode is set when there is an error with the error message set in message. Data is stored either in the Map or in a List as and when appropriate.
/**
*
*/
package com.test.presentation.response;
import java.util.Collection;
import java.util.Map;
/**
* A simple POJO to send JSON response to ajax requests. This POJO enables us to
* send messages and error codes with the actual objects in the application.
*
*
*/
@SuppressWarnings("rawtypes")
public class GenericResponse {
/**
* An array that contains the actual objects
*/
private Collection rows;
/**
* An Map that contains the actual objects
*/
private Map mapData;
/**
* A String containing error code. Set to 1 if there is an error
*/
private int statusCode = 0;
/**
* A String containing error message.
*/
private String message;
/**
* An array that contains the actual objects
*
* @return the rows
*/
public Collection getRows() {
return rows;
}
/**
* An array that contains the actual objects
*
* @param rows
* the rows to set
*/
public void setRows(Collection rows) {
this.rows = rows;
}
/**
* An Map that contains the actual objects
*
* @return the mapData
*/
public Map getMapData() {
return mapData;
}
/**
* An Map that contains the actual objects
*
* @param mapData
* the mapData to set
*/
public void setMapData(Map mapData) {
this.mapData = mapData;
}
/**
* A String containing error code.
*
* @return the errorCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* A String containing error code.
*
* @param errorCode
* the errorCode to set
*/
public void setStatusCode(int errorCode) {
this.statusCode = errorCode;
}
/**
* A String containing error message.
*
* @return the errorMessage
*/
public String getMessage() {
return message;
}
/**
* A String containing error message.
*
* @param errorMessage
* the errorMessage to set
*/
public void setMessage(String errorMessage) {
this.message = errorMessage;
}
}
Hope this helps.
Change "methodInfo" to "classInstance", just like in the call with the null parameter array.
result = methodInfo.Invoke(classInstance, parametersArray);
The reason is that modprobe
looks into /lib/modules/$(uname -r)
for the modules and therefore won't work with local file path. That's one of differences between modprobe
and insmod
.
Just a minor addition: The speed difference between memcpy()
and std::copy()
can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy()
clearly wins:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 17 ns 17 ns 40867738
bm_stdcopy 62 ns 62 ns 11176219
bm_stdcopy_n 72 ns 72 ns 9481749
When optimizations are enabled (-O3
), everything looks pretty much the same again:
Benchmark Time CPU Iterations
---------------------------------------------------
bm_memcpy 3 ns 3 ns 274527617
bm_stdcopy 3 ns 3 ns 272663990
bm_stdcopy_n 3 ns 3 ns 274732792
The bigger the array the less noticeable the effect gets, but even at N=1000
memcpy()
is about twice as fast when optimizations aren't enabled.
Source code (requires Google Benchmark):
#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>
constexpr int N = 10;
void bm_memcpy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
memcpy(r.data(), a.data(), N * sizeof(int));
}
}
void bm_stdcopy(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy(a.begin(), a.end(), r.begin());
}
}
void bm_stdcopy_n(benchmark::State& state)
{
std::vector<int> a(N);
std::vector<int> r(N);
while (state.KeepRunning())
{
std::copy_n(a.begin(), N, r.begin());
}
}
BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);
BENCHMARK_MAIN()
/* EOF */
My original reply was factually incorrect and I'm glad it was removed. The code below will work under the following conditions a) you know that nobody else modified the sequence b) the sequence was modified by your session. In my case, I encountered a similar issue where I was calling a procedure which modified a value and I'm confident the assumption is true.
SELECT mysequence.CURRVAL INTO v_myvariable FROM DUAL;
Sadly, if you didn't modify the sequence in your session, I believe others are correct in stating that the NEXTVAL is the only way to go.
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
The important concept is that you are evaluating an expression in your Razor code. The best way to do this (if, for example, you are in a foreach loop) is using a generic method.
The syntax for calling a generic method in Razor is:
@(expression)
In this case, the expression is:
User.Identity.IsAuthenticated ? "auth" : "anon"
Therefore, the solution is:
@(User.Identity.IsAuthenticated ? "auth" : "anon")
This code can be used anywhere in Razor, not just for an html attribute.
See @Kyralessa 's comment for C# Razor Syntax Quick Reference (Phil Haack's blog).
Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.
I've added some CSS to the demo below to change the button's font color to red when its aria-expanded
is set to true
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
You can also just make a new dictionary with a dictionary comprehension. This avoids importing copy.
dout = dict((k,v) for k,v in mydict.items())
Of course in python >= 2.7 you can do:
dout = {k:v for k,v in mydict.items()}
But for backwards compat., the top method is better.
For camera access use:
<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>
Generate a Windows command file (batch) for installing extensions:
for /F "tokens=*" %i in ('code --list-extensions')
do @echo call code --install-extension %i >> install.cmd
You need to test $?
instead, which is the exit status of the previous command. passwd
exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)
passwd
while [ $? -ne 0 ]; do
passwd
done
With your backtick version, you're comparing passwd's output, which would be stuff like Enter password
and confirm password
and the like.
You should set default values in migrations:
$table->tinyInteger('role')->default(1);
Drawing from Van Nguyen's answer above, use update instead of save. This gives you access to the upsert option.
NOTE: This method overrides the entire document when found (From the docs)
var conditions = { name: 'borne' } , update = { $inc: { visits: 1 }} , options = { multi: true };
Model.update(conditions, update, options, callback);
function callback (err, numAffected) { // numAffected is the number of updated documents })
If you want to update a selection of the document, but not the whole thing, you can use the $set method with update. (again, From the docs)... So, if you want to set...
var query = { name: 'borne' }; Model.update(query, ***{ name: 'jason borne' }***, options, callback)
Send it as...
Model.update(query, ***{ $set: { name: 'jason borne' }}***, options, callback)
This helps prevent accidentally overwriting all of your document(s) with { name: 'jason borne' }
.
I used custom DTO (interface) to map a native query to - the most flexible approach and refactoring-safe.
The problem I had with this - that surprisingly, the order of fields in the interface and the columns in the query matters. I got it working by ordering interface getters alphabetically and then ordering the columns in the query the same way.
This it the best way to calculate the size of a directory. Only other way would still use recursion but be a bit easier to use and isn't as flexible.
float folderSize = 0.0f;
FileInfo[] files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories);
foreach(FileInfo file in files) folderSize += file.Length;
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
self.logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
filename=logname
)filemode='a'
)format=...
)datefmt='%H:%M:%S'
)level=logging.DEBUG
).Another solution not using IFS and still preserving the spaces:
$ var="a bc,def,ghij"
$ while read line; do echo line="$line"; done < <(echo "$var" | tr ',' '\n')
line=a bc
line=def
line=ghij
I found the answer. IE stores passwords in two different locations based on the password type:
%APPDATA%\Microsoft\Credentials
, in encrypted filesHKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
, encrypted with the urlFrom a very good page on NirSoft.com:
Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:
AutoComplete Passwords: These passwords are saved in the following location in the Registry:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).HTTP Authentication Passwords: These passwords are stored in the Credentials file under
Documents and Settings\Application Data\Microsoft\Credentials
, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.
In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead
/CredWrite
, where the user can manage their passwords from within an established UI system in Windows.
In order to read or write to the standard input/output streams you need to include it.
int main( int argc, char * argv[] )
{
std::cout << "Hello World!" << std::endl;
return 0;
}
That program will not compile unless you add #include <iostream>
The second line isn't necessary
using namespace std;
What that does is tell the compiler that symbol names defined in the std
namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example
#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
cout << "Hello World!" << endl;
return 0;
}
Notice you no longer need to refer to the output stream with the fully qualified name std::cout
and can use the shorter name cout
.
I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:
#include <iostream>
using std::cout;
using std::endl;
int main( int argc, char * argv[] )
{
cout << "Hello World!" << endl;
return 0;
}
But that is a matter of personal preference.
Why does not it work?
Because the background CSS with background:none!important
has one #ID
A CSS selector file that contains an #id
will always have a higher value than one .class
If you want to work, you need add #id
on your .image-list li
like this:
#an-element .image-list li {
display: inline-block;
background-image: url("http://placekitten.com/150/50")!important;
padding: 1em;
border: 1px solid blue;
}
One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.
public File getFilesDir ()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int)
are stored.
public static File getExternalStorageDirectory ()
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState()
.
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
On devices with multiple users (as described by UserManager), each user has their own isolated external storage. Applications only have access to the external storage for the user they're running as.
If you want to get your application path use getFilesDir()
which will give you path /data/data/your package/files
You can get the path using the Environment
var of your data/package
using the
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath();
which will return the path from the root directory of your external storage as
/storage/sdcard/Android/data/your pacakge/files/data
To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE
and READ_EXTERNAL_STORAGE
in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Check out the Best Documentation to get the paths of direcorty
Yes,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
It is the same as super
in Java, except it allows calling implementations from different bases when you have multiple inheritance.
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
Try this:
MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.mapview);
mapFragment.getView().setVisibility(View.GONE);
There was a Python enhancement proposal PEP 299 which aimed to replace if __name__ == '__main__':
idiom with def __main__:
, but it was rejected. It's still a good read to know what to keep in mind when using if __name__ = '__main__':
.
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED - TESTED SCRIPT
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
<script>
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
alert(cellVal);
}
}
</script>
LinqToSql will automatically convert a .Skip(N1).Take(N2) into the TSQL syntax for you. In fact, every "query" you do in Linq, is actually just creating a SQL query for you in the background. To test this, just run SQL Profiler while your application is running.
The skip/take methodology has worked very well for me, and others from what I read.
Out of curiosity, what type of self-paging query do you have, that you believe is more efficient than Linq's skip/take?
The package nail
provides an enhanced mailx like interface. It includes the -r
option.
On Centos 5 installing the package mailx
gives you a program called mail
, which doesn't support the mailx
options.
I'm running SQL Developer 17.2.0.188 build 188.1159 which does indeed contain data modeling capability. I just created a relational model diagram via the menu: File->Data Modeler->Import->Data Dictionary....
I also have the stand-alone Data Modeler, which does the same thing.
As the Data Modeler tutorial states:
Figure 4: Relational model and diagram for HR
The diagram you’ve generated is not an ERD. Logical models are higher abstractions. An ERD represents entities and their attributes and relations, whereas a relational or physical model represents tables, columns, and foreign keys."
To add on top of @Pranav Singh and @Rahul Tripathi answer. After doing all the mentioned by those 2 users, my .net app still wasnt connecting to the database. My solution was.
Open Sql Server Configuration Manager, go to Network configuration of SQL SERVER, click on protocols, right click on TCP/IP and select enabled. I also right clicked on it opened properties, Ip directions, and scrolled to the bottom (IPAII , and there in TCP Port, I did setup a port (1433 is supposed to be default))
I have tried the code that Marcos posted and it didn't worked for me. Whatever i was given to the Y coordinate the cursor didn't moved on Y axis. The code below will work if you want the position of the cursor relative to the left-up corner of your desktop, not relative to your application.
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_MOVE = 0x0001;
public void DoMouseClick()
{
X = Cursor.Position.X;
Y = Cursor.Position.Y;
//move to coordinates
pt = (Point)pc.ConvertFromString(X + "," + Y);
Cursor.Position = pt;
//perform click
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
I only use mouse_event function to actually perform the click. You can give X and Y what coordinates you want, i used values from textbox:
X = Convert.ToInt32(tbX.Text);
Y = Convert.ToInt32(tbY.Text);
In Kotlin 1.2 simply call:
invalidateOptionsMenu()
and the onCreateOptionsMenu
function will be called again.
You can also use the bitwise complement of the array index to step through the array in reverse:
>>> array = [0, 10, 20, 40]
>>> [array[~i] for i, _ in enumerate(array)]
[40, 20, 10, 0]
Whatever you do, don't do it this way ;)
They're the same thing (in API Level 8+). Use match_parent
.
FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)
...
fill_parent
: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced bymatch_parent
.
http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html
There is nothing wrong with your code. The problem is not visible form here.
Check if after the submit, the script is called at all.
Have a look at what is submitted: var_dump($_REQUEST)
Oxi's answer is just wrong.¹
What you want is:
var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;
Working example:
(function (){
var i = 20, l = 20, html = '';
while (i--){
html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
html += '[ Scroll to #DIV' +i+ ' ]</a>';
html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
}
document.write( html );
})();
¹ I haven't got enough reputation to comment on his answer
Make sure you are using the latest version of JQuery. We were facing this error for JQuery 1.10.2 and the error got resolved after using JQuery 1.11.1
If Apache is installed as a Windows service, any errors will show up in the Windows System event log. To view the System event log, navigate to Windows Administrative Tools->Event Viewer and open the System log in the Windows Logs folder. Or, you can see the same errors by running httpd.exe at the command line. In my case, httpd.exe is located here: C:\Bitnami\wampstack-5.6.26-2\apache2\bin.
If there is a problem with starting Apache, most likely the problem can be fixed by editing the httpd.conf file located in the \apache2\conf folder. As already suggested, you can check the syntax of the httpd.conf file by running httpd.exe -t at the command line.
I found that the I had to
Change
SetEnv PATH "C:\Bitnami\wampstack-5.6.26-2\apache2\bin;${PATH}"
in httpd.conf
to
SetEnv PATH "C:\Bitnami\wampstack-5.6.26-2\apache2\bin;%PATH%"
A way to use a custom sort function
//func has to return 0 in the case in which they are equal
sort_unique = function(arr,func) {
func = func || function (a, b) {
return a*1 - b*1;
};
arr = arr.sort(func);
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (func(arr[i-1],arr[i]) != 0)
ret.push(arr[i]);
}
}
return ret;
}
Example: desc order for an array of objects
MyArray = sort_unique(MyArray , function(a,b){
return b.iterator_internal*1 - a.iterator_internal*1;
});
The first step would be to add
position: 'absolute',
then if you want the element full width, add
left: 0,
right: 0,
then, if you want to put the element in the bottom, add
bottom: 0,
// don't need set top: 0
if you want to position the element at the top, replace bottom: 0
by top: 0
Use Getdate()
select sum(transaction_amount) from TransactionMaster
where Card_No=' 123' and transaction_date =convert(varchar(10), getdate(), 102)
You can do it this simple way :
A1 = Mahi
A2 = NULL(blank)
Select A2 Right click on cell --> Format cells --> change to TEXT
Then put the date in A2 (A2 =31/07/1990)
Then concatenate it will work. No need of any formulae.
=CONCATENATE(A1,A2)
mahi31/07/1990
(This works on the empty cells ie.,Before entering the DATE value to cell you need to make it as TEXT).
Use copyOfRange method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
For more details:
There is an article here that describes your problem
http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/
<fb:visible-to-connection>
Fans will see this content.
<fb:else>
Non-fans will see this content.
</fb:else>
</fb:visible-to-connection>
It seems that you can handle the signing problem by doing a "logical AND" on the values before you use them:
Example (Value of byte[]
header[0]
is 0x86
):
System.out.println("Integer "+(int)header[0]+" = "+((int)header[0]&0xff));
Result:
Integer -122 = 134
This worked for me:
git branch
Copy the current branch name to clipboard
git pull origin <paste-branch-name>
git push
Sometimes this syntax wont work:
df[['col1','col2']] = df[['col1','col2']].fillna()
Use the following instead:
df['col1','col2']
I have been in the same situation, my complete solution has been posted here
Basically I load a template in the directive in this way
var tpl = '' +
<div ng-if="maxLength"
ng-include="\'length.tpl.html\'">
</div>' +
'<div ng-if="required"
ng-include="\'required.tpl.html\'">
</div>';
then according to the value of maxLength
and required
I can dynamically load one of the 2 templates, only one of them at a time is shown if necessary.
I heope it helps.
You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIView
subclass to use as a background for your UILabel
. In that UIView
subclass, override the drawRect:
method and insert code similar to the following:
- (void)drawRect:(CGRect)rect
{
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGGradientRef glossGradient;
CGColorSpaceRef rgbColorspace;
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35, // Start color
1.0, 1.0, 1.0, 0.06 }; // End color
rgbColorspace = CGColorSpaceCreateDeviceRGB();
glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
CGRect currentBounds = self.bounds;
CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);
CGGradientRelease(glossGradient);
CGColorSpaceRelease(rgbColorspace);
}
This particular example creates a white, glossy-style gradient that is drawn from the top of the UIView
to its vertical center. You can set the UIView
's backgroundColor
to whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradient
function.
You just need to size this UIView
appropriately and add your UILabel
as a subview of it to get the effect you desire.
EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0).
A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
template <typename T, typename U>
struct CompareByMember {
// This is a pointer-to-member, it represents a member of class T
// The data member has type U
U T::*field;
CompareByMember(U T::*f) : field(f) {}
bool operator()(const T &lhs, const T &rhs) {
return lhs.*field < rhs.*field;
}
};
struct Test {
int a;
int b;
std::string c;
Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};
// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
return o << t.c;
}
int main() {
std::vector<Test> vec;
vec.push_back(Test(1, 10, "y"));
vec.push_back(Test(2, 9, "x"));
// sort on the string field
std::sort(vec.begin(), vec.end(),
CompareByMember<Test,std::string>(&Test::c));
std::cout << "sorted by string field, c: ";
std::cout << vec[0] << " " << vec[1] << "\n";
// sort on the first integer field
std::sort(vec.begin(), vec.end(),
CompareByMember<Test,int>(&Test::a));
std::cout << "sorted by integer field, a: ";
std::cout << vec[0] << " " << vec[1] << "\n";
// sort on the second integer field
std::sort(vec.begin(), vec.end(),
CompareByMember<Test,int>(&Test::b));
std::cout << "sorted by integer field, b: ";
std::cout << vec[0] << " " << vec[1] << "\n";
}
Output:
sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y
Tooting my own horn if I may, I'd also like to suggest taking a look at an option parsing library that I've written: dropt.
One feature that it offers that many others don't is the ability to override earlier options. For example, if you have a shell alias:
alias bar="foo --flag1 --flag2 --flag3"
and you want to use bar
but with--flag1
disabled, it allows you to do:
bar --flag1=0
Extending Richard Cook's answer.
Here's the ant
task to run any program (including, but not limited to Java programs):
<target name="run">
<exec executable="name-of-executable">
<arg value="${arg0}"/>
<arg value="${arg1}"/>
</exec>
</target>
Here's the task to run a Java program from a .jar
file:
<target name="run-java">
<java jar="path for jar">
<arg value="${arg0}"/>
<arg value="${arg1}"/>
</java>
</target>
You can invoke either from the command line like this:
ant -Darg0=Hello -Darg1=World run
Make sure to use the -Darg
syntax; if you ran this:
ant run arg0 arg1
then ant
would try to run targets arg0
and arg1
.
In an ASP.NET application, I think it goes to the Output or Console window which is visible during debugging.
The command line arguments are separated by space. If you want provide an argument with a space in it, you should quote it. So use git commit -m "initial commit"
.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
UITableViewCell
has three default selection styles:-
Implementation is as follows:-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
I had the same issue, but my solution wasn't as obvious as the suggested ones. It turned out that my php-file was written in UTF-8, which caused issues. I copy/pasted the content of the entire file into a new php-file (Notepad++ tells me this is written in ANSI rather than UTF-8), and now it work flawlessly.
If you get this error in an Amplify project, check that "awsConfigFilePath"
is not configured in amplify/.config/local-aws-info.json
In my case I had to remove it, so my environment looked like the following:
{
// **INCORRECT**
// This will not use your profile in ~/.aws/credentials, but instead the
// specified config file path
// "dev": {
// "configLevel": "project",
// "useProfile": false,
// "awsConfigFilePath": "/Users/dev1/.amplify/awscloudformation/cEclTB7ddy"
// },
// **CORRECT**
"dev": {
"configLevel": "project",
"useProfile": true,
"profileName": "default",
}
}
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
There's a simple JavaScript tri-state input field implementation at https://github.com/supernifty/tristate-checkbox
If they are not hashable, you can sort them and do a single loop over the result counting the items (identical items will be next to each other). But it might be faster to make them hashable and use a dict.
def most_common(lst):
cur_length = 0
max_length = 0
cur_i = 0
max_i = 0
cur_item = None
max_item = None
for i, item in sorted(enumerate(lst), key=lambda x: x[1]):
if cur_item is None or cur_item != item:
if cur_length > max_length or (cur_length == max_length and cur_i < max_i):
max_length = cur_length
max_i = cur_i
max_item = cur_item
cur_length = 1
cur_i = i
cur_item = item
else:
cur_length += 1
if cur_length > max_length or (cur_length == max_length and cur_i < max_i):
return cur_item
return max_item
I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:
<xsl:value-of select="count(//td[text()=' '])" />
The value returned is 1, which is the correct value in my test case.
However, I did have to declare nbsp as an entity within my XML and XSL using the following:
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]>
I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.
Edit: My code sample actually contains the characters ' ' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!
remove
user.setId(1);
because it is auto generate on the DB, and continue with persist command.
My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.
Try this:
<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);"> function validate_fileupload(fileName) { var allowed_extensions = new Array("jpg","png","gif"); var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename. for(var i = 0; i <= allowed_extensions.length; i++) { if(allowed_extensions[i]==file_extension) { return true; // valid file extension } } return false; }
curl -X GET -H "Accept: application/vnd.api+json" localhost:8082/v3/clusters
where localhost:8082
is Kafka Proxy address.
Using the patchwork package, you can simply use +
operator:
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2
Other operators include /
to stack plots to place plots side by side, and ()
to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p
. For more examples, see the package documentation.
Add this method to a static class:
public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false)
{
var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0));
if (relativeToScreen)
{
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0));
absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y);
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
Set relativeToScreen
paramater to true
for placement from top left corner of whole screen or to false
for placement from top left corner of application window.
You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)
This may seem a bit lengthy, but it worked for me without any error.
At first, Install phppgadmin from Ubuntu Software Center.
Then run these steps in terminal.
sudo apt-get install libpq-dev python-dev
pip install psycopg2
sudo apt-get install postgresql postgresql-contrib phppgadmin
Start the apache server
sudo service apache2 start
Now run this too in terminal, to edit the apache file.
sudo gedit /etc/apache2/apache2.conf
Add the following line to the opened file:
Include /etc/apache2/conf.d/phppgadmin
Now reload apache. Use terminal.
sudo /etc/init.d/apache2 reload
Now you will have to create a new database. Login as 'postgres' user. Continue in terminal.
sudo su - postgres
In case you have trouble with the password of 'postgres', you can change it using the answer here https://stackoverflow.com/a/12721020/1990793 and continue with the steps.
Now create a database
createdb <db_name>
Now create a new user to login to phppgadmin later, providing a new password.
createuser -P <new_user>
Now your postgressql has been setup, and you can go to:
http://localhost/phppgadmin/
and login using the new user you've created, in order to view the database.
Recently had this problem but with unkown number of promises.Solved using jQuery.map().
function methodThatChainsPromises(args) {
//var args = [
// 'myArg1',
// 'myArg2',
// 'myArg3',
//];
var deferred = $q.defer();
var chain = args.map(methodThatTakeArgAndReturnsPromise);
$q.all(chain)
.then(function () {
$log.debug('All promises have been resolved.');
deferred.resolve();
})
.catch(function () {
$log.debug('One or more promises failed.');
deferred.reject();
});
return deferred.promise;
}
To anyone that is using an xib method to create a UIView and having this problem, you will notice that you won't have the "view" outlet under the connections inspector menu. But if you set the File's Owners custom class to a UIViewController and then you will see the "view" outlet, which you can just CMND connect an outlet to the CustomView.
My problem solve this one
compile fileTree(dir: 'libs', include: ['*.jar'])
to
provided fileTree(dir: 'libs', include: ['*.jar'])
I have just removed UITableView
from Interface Builder
, created it once again and strange 35px gone away.
It seems that it there is a strange bug in Interface Builder
.
Either use instanceof
or method Class.isAssignableFrom(Class<?> cls)
.
If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.
Don't use delete as it won't remove an element from an array it will only set it as undefined, which will then not be reflected correctly in the length of the array.
If you know the key you should use splice i.e.
myArray.splice(key, 1);
For someone in Steven's position you can try something like this:
for (var key in myArray) {
if (key == 'bar') {
myArray.splice(key, 1);
}
}
or
for (var key in myArray) {
if (myArray[key] == 'bar') {
myArray.splice(key, 1);
}
}
what worked for me was and is superfast is
import pandas as pd
import dask.dataframe as dd
import time
t=time.clock()
df_train = dd.read_csv('../data/train.csv', usecols=[col1, col2])
df_train=df_train.compute()
print("load train: " , time.clock()-t)
Another working solution is:
import pandas as pd
from tqdm import tqdm
PATH = '../data/train.csv'
chunksize = 500000
traintypes = {
'col1':'category',
'col2':'str'}
cols = list(traintypes.keys())
df_list = [] # list to hold the batch dataframe
for df_chunk in tqdm(pd.read_csv(PATH, usecols=cols, dtype=traintypes, chunksize=chunksize)):
# Can process each chunk of dataframe here
# clean_data(), feature_engineer(),fit()
# Alternatively, append the chunk to list and merge all
df_list.append(df_chunk)
# Merge all dataframes into one dataframe
X = pd.concat(df_list)
# Delete the dataframe list to release memory
del df_list
del df_chunk
In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above
Just type the following commands from console.
cd /your_project
heroku restart
Here are a few ways of removing a single '
from a string in python.
replace
is usually used to return a string with all the instances of the substring replaced.
"A single ' char".replace("'","")
str.translate
To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.
"A single ' char".translate(None,"'")
You will have to use str.maketrans
"A single ' char".translate(str.maketrans({"'":None}))
Regular Expressions using re
are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.
re.sub("'","","A single ' char")
Other Ways
There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string
.
Using list comprehension
''.join([c for c in string if c != "'"])
Using generator Expression
''.join(c for c in string if c != "'")
Another final method can be used also (Again not recommended - works only if there is only one occurrence )
You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
An example of endpoint configuration in your scenario is
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="ITestService"/>
</service>
</services>
so, the service will be available at
Apply [WebGet] to the operation contract to make it RESTful. e.g.
public interface ITestService
{
[OperationContract]
[WebGet]
string HelloWorld(string text)
}
Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.
For plain old XML as return format, this is an example that would work both for SOAP and XML.
[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
[OperationContract]
[WebGet(UriTemplate = "accounts/{id}")]
Account[] GetAccount(string id);
}
POX behavior for REST Plain Old XML
<behavior name="poxBehavior">
<webHttp/>
</behavior>
Endpoints
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="ITestService"/>
</service>
</services>
Service will be available at
REST request try it in browser,
SOAP request client endpoint configuration for SOAP service after adding the service reference,
<client>
<endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
contract="ITestService" name="BasicHttpBinding_ITestService" />
</client>
in C#
TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");
Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.
Django also has the 'latest(field_name = None)' function that finds the latest (max. value) entry. It not only works with date fields but also with strings and integers.
You can give the field name when calling that function:
max_rated_entry = YourModel.objects.latest('rating')
return max_rated_entry.details
Or you can already give that field name in your models meta data:
from django.db import models
class YourModel(models.Model):
#your class definition
class Meta:
get_latest_by = 'rating'
Now you can call 'latest()' without any parameters:
max_rated_entry = YourModel.objects.latest()
return max_rated_entry.details
Got the issue when trying Xcode 9 beta and going back to Xcode 8. A simple Clean on the target resolved the issue.
I was having the same issue
My Issue
Caused by: java.security.PrivilegedActionException: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Two classes have the same XML type name "{urn:cpq_tns_Kat_getgroupsearch}Kat_getgroupsearch". Use @XmlType.name and @XmlType.namespace to assign different names to them.
this problem is related to the following location:
at katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearch
at public javax.xml.bind.JAXBElement katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory.createKatGetgroupsearch(katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearch)
at katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory
this problem is related to the following location:
at cpq_tns_kat_getgroupsearch.KatGetgroupsearch
Two classes have the same XML type name "{urn:cpq_tns_Kat_getgroupsearch}Kat_getgroupsearchResponse0". Use @XmlType.name and @XmlType.namespace to assign different names to them.
this problem is related to the following location:
at katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearchResponse0
at public javax.xml.bind.JAXBElement katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory.createKatGetgroupsearchResponse0(katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearchResponse0)
at katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory
this problem is related to the following location:
at cpq_tns_kat_getgroupsearch.KatGetgroupsearchResponse0
Changed made to solve it are below
I change the respective name to namespace
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(**name** =
"Kat_getgroupsearch", propOrder = {
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(namespace =
"Kat_getgroupsearch", propOrder = {
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(**name** = "Kat_getgroupsearchResponse0", propOrder = {
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(namespace = "Kat_getgroupsearchResponse0", propOrder = {
why?
As written in error log two classes have same name so we should use namespace because XML namespaces are used for providing uniquely named elements and attributes in an XML document.
I don't know how to delete all at once, but you can use ipcs
to list resources, and then use loop and delete with ipcrm
. This should work, but it needs a little work. I remember that I made it work once in class.
Use the -H
header again before the Authorization:Basic things. So it will be
curl -i \
-H 'Accept:application/json' \
-H 'Authorization:Basic BASE64_string' \
http://example.com
Here, BASE64_string
= Base64 of username:password
For me it was because 2 linux VMs were both mapped to the same home file system. One VM was running git-1.7.1 an the other was running git-2.14
The VM running git-1.7.1 would always show 4 files as changed (even thought the contents and line endings were identical).
Once 'git status' was run on the VM running g-2.14, then both VMs would start reporting the repository as clean. 'git status' has side effects. It is not an immutable operation. And git-1.7.1 does not understand the world in the same way that git-2+ does.
You might want to try this if results still flows down to children, in many cases JQuery will still apply to children.
$("ul.rootlist > li > a")
Using this method: E > F Matches any F element that is a child of an element E.
Tells JQuery to look only for explicit children. http://www.w3.org/TR/CSS2/selector.html
You can make use of java.net.URL
and/or java.net.URLConnection
.
URL url = new URL("https://stackoverflow.com");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
Also see the Oracle's simple tutorial on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider Apache HttpClient instead.
By the way: if your next question is "How to process HTML result?", then the answer is "Use a HTML parser. No, don't use regex for this.".
You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.
UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.
constructor(props){
super(props);
}
getInitialState(){
return {"showHideSidenav":"hidden"};
}
render() {
return (
<div className="header">
<i className="border hide-on-small-and-down"></i>
<div className="container">
<a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
<Menu className="menu hide-on-small-and-down"/>
<Sidenav className={this.props.showHideSidenav}/>
</div>
</div>
)
}
toggleSidenav() {
var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
this.setState({"showHideSidenav":css});
}
Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.
.hidden {
display:none;
}
.show{
display:block;
}
Instead of using for every new Java version a new link or changing existing scripts, I was looking for a more generic way to automate the download of the required Java packages and later installation via yum localinstall ${JAVA_ENVIRONMENT}-${JAVA_VERSION}-linux-x64.rpm
.
I've used a somehow trivial approach similar to manual/user action to find the package and to download it. I am also pretty sure that one will find a more elegant way to do it by using other tools like egrep
, awk
, etc.., so leave it as an example here:
#!/bin/bash
### Proxy settings
# If there is a company proxy
PROXY="my.proxy.local:8080"
PROXY_TYPE="--proxy-ntlm" # or leave empty with ""
USER="user"
PASS='pass'
### Find out the links to JRE and JDK
# To do so, got to the page http://www.oracle.com/technetwork/java/javase/downloads/
BASE_URL="technetwork/java/javase/downloads"
# Put the whole page into a single string/line
BASE_URL_OUTPUT="$(curl -s -k ${PROXY_TYPE} -x "http://${USER}:${PASS}@${PROXY}" -L0 http://www.oracle.com/${BASE_URL}/)"
# Define the environments to download
JAVA_ENVIRONMENTS=("JRE" "JDK") # ! yet "SERVER-JRE"
for JAVA_ENVIRONMENT in "${JAVA_ENVIRONMENTS[@]}"
do
echo
echo "JAVA_ENVIRONMENT="$JAVA_ENVIRONMENT
echo
for (( JAVA_BASE_VERSION = 8; JAVA_BASE_VERSION <= 10; JAVA_BASE_VERSION += 2 ))
do
echo "JAVA_BASE_VERSION="$JAVA_BASE_VERSION
### "Read the page"
# and follow the links for the package interested in
DOWNLOAD_SITE="$(echo $BASE_URL_OUTPUT | grep -m 1 -io "${JAVA_ENVIRONMENT}${JAVA_BASE_VERSION}-downloads-[0-9]*.html" -- | tail -1)"
echo "DOWNLOAD_SITE="$DOWNLOAD_SITE
### Gather the necessary download links
# To do so, following the link to the download site
# reading and accept the license
#
# ... the greedy regular expression is to address the different syntax of the links
# and already prepared for OR .gz files
DOWNLOAD_LINK_OUTPUT="$(curl -s -k ${PROXY_TYPE} -x "http://${USER}:${PASS}@${PROXY}" -L -j -H "Cookie: oraclelicense=accept-securebackup-cookie" http://www.oracle.com/${BASE_URL}/${DOWNLOAD_SITE} | grep -io "filepath.*${JAVA_ENVIRONMENT}-[${JAVA_BASE_VERSION}].*linux[-_]x64[._].*\(rpm\)" -- | cut -d '"' -f 3 | tail -1)"
# and echo out the link
echo "DOWNLOAD_LINK_OUTPUT="$DOWNLOAD_LINK_OUTPUT
done
done
Since the download links are available now, one may proceed further with wget
or curl
.
Use the ToDictionary
method directly.
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
You can also use it with Page Object Pattern, e.g:
Try this code:
@FindBy(xpath = "//*[contains(text(), 'Best Choice')]")
WebElement buttonBestChoice;
There's no reasonable way to check whether a value has been initialized.
If you care about whether something has been initialized, instead of trying to check for it, put code into the constructor(s) to ensure that they are always initialized and be done with it.
WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:
var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With WebClient, you just do DownloadString
:
var client = new WebClient();
var content = client.DownloadString("http://example.com");
Note: I left out the using
statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.
In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.
you can also refactor your solution removing the first loop:
Set<Integer> set = new HashSet<Integer>();
Collection<Integer> removeCandidates = new LinkedList<Integer>(set);
for(Integer element : set)
if(element % 2 == 0)
removeCandidates.add(element);
set.removeAll(removeCandidates);
The accepted answer may solve the question, but if you want multiline if
conditions in the dockerfile, you can do that placing \
at the end of each line (similar to how you would do in a shell script) and ending each command with ;
. You can even define someting like set -eux
as the 1st command.
Example:
RUN set -eux; \
if [ -f /path/to/file ]; then \
mv /path/to/file /dest; \
fi; \
if [ -d /path/to/dir ]; then \
mv /path/to/dir /dest; \
fi
In your case:
FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
echo Argument not provided; \
else \
echo Argument is $arg; \
fi
Then build with:
docker build -t my_docker . --build-arg arg=42
typedef enum {
ERR_CODE_OK = 0,
ERR_CODE_SNAP,
ERR_CODE_NUM
} ERR_CODE;
const char* g_err_msg[ERR_CODE_NUM] = {
/* ERR_CODE_OK */ "OK",
/* ERR_CODE_SNAP */ "Oh, snap!",
};
Above is my simple solution. One benefit of it is the 'NUM' which controls the size of the message array, it also prevents out of boundary access (if you use it wisely).
You can also define a function to get the string:
const char* get_err_msg(ERR_CODE code) {
return g_err_msg[code];
}
Further to my solution, I then found the following one quite interesting. It generally solved the sync problem of the above one.
Slides here: http://www.slideshare.net/arunksaha/touchless-enum-tostring-28684724
Code here: https://github.com/arunksaha/enum_to_string
Currently I'm using this solution:
$firstDay = new \DateTime('first day of this month');
$lastDay = new \DateTime('last day of this month');
The only issue I came upon is that strange time is being set. I needed correct range for our search interface and I ended up with this:
$firstDay = new \DateTime('first day of this month 00:00:00');
$lastDay = new \DateTime('first day of next month 00:00:00');
Simply pass view object into onButtonClicked function. getView() does not seem to work as expected inside fragment. Try this code for your FragmentOne fragment
PS. you have redefined object view in your original FragmentOne code.
package com.example.fragmenttutorial;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
onButtonClicked(view);
return view;
}
protected void onButtonClicked(View view)
{
if(view.getId() == R.id.buttonSayHi){
Fragment fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
I don't hear about "apstring".If you want to use string with c++ ,you can do like this:
#include<string>
using namespace std;
int main()
{
string str;
cin>>str;
cout<<str;
...
return 0;
}
I hope this can avail
cURL is an option, using Ajax as well eventhough solving back-end problems with the front-end isn't so neat.
A very useful post about doing it without cURL is this one: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
The code to do this (untested, unimproved, from the blog post):
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
Another take on this that hasn't been mentioned here is that, when in debug, the project may build, but it won't run, giving the error message displayed in the question.
If this is the case, another option to look at is the output file versus the target file. These should match.
A quick way to check the output file is to go to the project's property pages, then go to Configuration Properties -> Linker -> General (In VS 2013 - exact path may vary depending on IDE version).
There is an "Output File" setting. If it is not $(OutDir)$(TargetName)$(TargetExt)
, then you may run into issues.
This is also discussed in more detail here.
I know i'm 3 years late to this question, but I felt like chiming in.
While Gumbo's solution works great, it doesn't handle a few cases where no exception is raised for JSON.parse({something that isn't JSON})
I also prefer to return the parsed JSON at the same time, so the calling code doesn't have to call JSON.parse(jsonString)
a second time.
This seems to work well for my needs:
function tryParseJSON (jsonString){
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
// but... JSON.parse(null) returns null, and typeof null === "object",
// so we must check for that, too. Thankfully, null is falsey, so this suffices:
if (o && typeof o === "object") {
return o;
}
}
catch (e) { }
return false;
};
Perhaps the best way to explain it is with an example:
git checkout master && git pull
. Master is already up to date.git checkout master && git pull
. Master is already up to date.git merge topic-branch-A
git merge topic-branch-B
git push origin master
before Alicegit push origin master
, which is rejected because it's not a fast-forward merge.git pull --rebase origin master
git push origin master
, and everyone is happy they don't have to read a useless merge commit when they look at the logs in the future.Note that the specific branch being merged into is irrelevant to the example. Master in this example could just as easily be a release branch or dev branch. The key point is that Alice & Bob are simultaneously merging their local branches to a shared remote branch.
As of Swift 4+
It's just:
test1.count
for reasons.
(Thanks to Martin R)
As of Swift 2:
With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:
test1.characters.count
(Thanks to JohnDifool for the heads up)
As of Swift 1
Use the count characters method:
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
right from the Apple Swift Guide
(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie)
instead)
for your variable, it would be
length = count(test1) // was countElements in earlier versions of Swift
Or you can use test1.utf16count
First Issue: You want to run Mysql server from Mysql and from Xampp also want to browse phpmyadmin so that you can operate database.Then follow the rules:
From "Xampp/phpmyadmin" directory in config.inc.php file find the below code. And follow the given instructions below. I have tried like this and I was successful to run both localhost/phpMyAdmin on browser, MySQL Command prompt as well as MySQL query browser.
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'pma';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['controluser'] = 'user_name/root';
$cfg['Servers'][$i]['controlpass'] = 'passwaord';
And replace the above each statement with the below each corresponding code.
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'Muhammad Ashikuzzaman';
$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = 'Muhammad Ashikuzzaman';
Second Issue: Way 1 : You can quit Skype first. And when Apche server is started then again you can run Skype. If you want to run Apache in another port then replace in xampp/apache/conf/httpd.conf "ServerName localhost:80" by "ServerName localhost:81" At line 184. After that even it may not work. Then replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80
by
#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81
at line 45
Way 2 : If you want to use port 80. Then follow this. In Windows 8 “World Wide Publishing Service is using this port and stopping this service will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop. If you don't find there then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
If it isn't I could see things heading that way.
I'm working on redoing the website for the company I work for and the designer they hired used a 960px width layout. There is also a 960px grid system that seems to be getting quite popular (http://960.gs/).
I've been out of web stuff for a few years but from what I've read catching up on things it seems 960/980 is about right. For mobile ~320px sticks in my mind, by which 960 is divisible. 960 is also evenly divisible by 2, 3, 4, 5, and 6.
If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:
INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');
I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS()
and CHAR()
worked for me.
INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));
For older Ubuntu distros i.e 16.04, 14.04, 12.04 etc
sudo apt-get install zip unzip php7.0-zip
Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.
.Net core:
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
using (var httpClient = new HttpClient(httpClientHandler))
{
var httpResponse = httpClient.GetAsync("https://example.com").Result;
}
}
.Net framework:
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
Update:
How to get cert.GetCertHashString()
value in Chrome:
Click on Secure
or Not Secure
in the address bar.
Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower()
.
WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh
Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
In your 'test' directive Html tag, the attribute name of the function should not be camelCased, but dash-based.
so - instead of :
<test color1="color1" updateFn="updateFn()"></test>
write:
<test color1="color1" update-fn="updateFn()"></test>
This is angular's way to tell the difference between directive attributes (such as update-fn function) and functions.
count = 0 if count == N else N+1
- the ternary operator. Although I'd say your solution is more readable than this.
You should do ex.StackTrace instead of ex.ToString()
Here is a COMPLETE Javascript-free, CSS-based solution that allows you to target Internet Explorer 1-11!
My Internet Explorer Only CSS Solution
This works by hiding IE1-7 from all your modern sheets using @import
, giving IE1-7 a clean, white page layout, then applies three simple CSS media query "hacks" to isolate IE8-11 in the imported sheet. It even affects IE on Mac!
The advantage to this strategy is its 100% effective in targeting IE1-11, giving you complete control over how you customize CSS for those targeted browsers, while freeing you up as a designer to focus on newer CSS3 and cutting-edge styles and layouts in Edge and all other modern browsers going forward. I have been using a version of this since 2004 but recently updated it for 2021.
HOW IT WORKS
First create two CSS style sheet links. The first is a basic element style sheet that gives all browsers, old and new, a simple white, block-level layout. Linked CSS has wide support in older CSS1 browsers going back to 1995. A wide range of old browsers will see this first sheet and display your content and layouts in a clean, white block-level content page. I like to put "reset" element-only styles in here. The second sheet is an import sheet that will load all your advanced CSS styles using a single @import
rule that hides styles to a wide range of browsers including IE1-7.
<link media="screen" rel="stylesheet" type="text/css" href="OldBrowsers.css" />
<link media="screen" rel="stylesheet" type="text/css" href="Import.css" />
Next, in your "Import.css" sheet add this @import rule exactly as formatted (Its hidden from IE1-7 and a wide range of older browsers listed below):
@import 'ModernBrowsers.css' all;
All CSS in this imported sheet will be hidden from IE1-7 and a wide range of older browsers. IE 1-7 doesn't understand "media type" value "all" so will fail to import this sheet. This specific version of import is also not recognized by many older browsers (pre-2001). Those browsers are so old now, you just need to deliver them a white web page with stacked blocks of content. Use "OldBrowsers" to do so.
Next, in "ModernBrowsers.css" you want to target IE8-11 using CSS media query "hacks" alongside all your normal selectors and classes. Simply apply the following media query, IE-only fixes to your modern, imported style sheet to target these specific IE browsers. Drop into these blocks any styles specific to them. You can attack your layout or other style issues in IE now in media query "batches" now rather than by multiple selector "hacks":
/* IE8 */
@media \0screen {
body {
background: red !important;
}
}
/* IE9 */
@media all and (monochrome:0) {
body {
background: blue\9 !important;
}
}
/* IE10-11 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
body {
background: green !important;
}
}
Simple! You have now targeted styles for IE1-11 (all Internet Explorer browsers!)
With this solution you achieve the following:
The @import
excludes IE 1-7 from your modern styles, completely! Those agents, along with the list below, will never see your modern imported styles and get a clean white style sheet content page older browsers can still use as far as viewing your content (use "OldBrowsers.css" to style them). The following browsers are excluded from "ModernBrowsers.css" using the above @import
rule:
In your "ModernBrowsers" imported sheet, you can now safely target IE browsers version 8-11 using simple media query "hacks".
This system uses a simple @import
style sheet system that is fast and manageable using traditional, non-support for external style rules rather than CSS fixes sprinkled throughout multiple sheets. (BTW...Do not listen to anyone saying @import
is slow, as it is not. My import sheet has ONE LINE and is maybe a kilobyte or less in size! @import
has been used since the birth of the WWW and is no different than a simple CSS link. Compare this to the Megabytes of Javascript kids today are shoving into browsers using these new "modern" ECMAScript SPA API's just to display a tiny paragraph of news!)
All old IE browsers and a wide range of other user agnets are excluded from modern styles now using this import strategy, which allows these agents to collapse back to plain, "block-level", white pages and stacked content layouts that are fully accessible by older browsers.
Notice this solution has no IE conditional comments! (you should NEVER use those)
With this solution, web designs are now 100% free to use custom, cutting edge CSS3 technologies without having to ever worry about older browsers and IE1-11 ever again!
I will be posting my formal version of this Universal CSS System on GitHub soon! So stay tuned...
This is part of the new "progressive" CSS, 100% Javacript-free, design concept in 2021 for addressing cross-browser style issues, where older agents are allowed to degrade gracefully to simpler layouts rather than struggling to fix problems in cryptic old, broken, box-model agents (IE6) that don't need custom layouts any longer today as the long tail of their slow demise continues online.
And its my hope we stop creating these gigantic, CPU-hog, Javascripted, polyfill nightmare solutions for addressing what used to be years ago solved by simple CSS solutions like this one.
You can get the filecount like so:
$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
$filecount = count($files);
}
echo "There were $filecount files";
where the "*"
is you can change that to a specific filetype if you want like "*.jpg"
or you could do multiple filetypes like this:
glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)
the GLOB_BRACE
flag expands {a,b,c} to match 'a', 'b', or 'c'
One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:
npm cache clean
And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.
This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.
You use EXECUTENONQUERY()
for INSERT
,UPDATE
and DELETE
.
But for SELECT
you must use EXECUTEREADER()
.........
I'd love to use regex to accomplish this, but since you can only use lists, loops, functions, etc..
here's what I came up with:
stringWithNumbers="I have 10 bananas for my 5 monkeys!"
stringWithoutNumbers=''.join(c if c not in map(str,range(0,10)) else "" for c in stringWithNumbers)
print(stringWithoutNumbers) #I have bananas for my monkeys!
assign
copy:
retain:
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
If you have to do group by
using hibernate criteria use projections.groupPropery
like the following,
@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
When using JBOSS Server, double click on the server:
Go to "Open Launch Configuration"
Then change min and max memory sizes (like 1G, 1m):
Write a Boolean function that checks the regex and use apply on the column
foo[foo['b'].apply(regex_function)]
Go to xampp/php/php.ini
Find this line:
max_execution_time=30
And change its value to any number you want. Restart Apache.