<meta http-equiv="X-UA-Compatible" content="IE=8" />
should force your page to render in IE8 standards. The user may add the site to compatibility list but this tag will take precedence.
A quick way to check would be to load the page and type the following the address bar :
javascript:alert(navigator.userAgent)
If you see IE7 in the string, it is loading in compatibility mode, otherwise not.
console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property
if (window.console)
console.log(msg)
this throws an exception in IE9 and will not work correctly. Do not do this
if (console)
console.log(msg)
I tried out the filters referenced above and strongly disliked the effect it created. I also didn't want to use any plugins since they'd slow down loading time for what seems like such a basic effect.
In my case I was looking for a text shadow with a 0px blur, which means the shadow is an exact replica of the text but just offset and behind. This effect can be easily recreated with jquery.
<script>
var shadowText = $(".ie9 .normalText").html();
$(".ie9 .normalText").before('<div class="shadow">' + shadowText + '</div>');
</script>
<style>
.ie9 .shadow { position: relative; top: 2px; left: -3px; }
</style>
This will create an identical effect to the css3 text-shadow below.
text-shadow: -3px 2px 0px rgba(0, 0, 0, 1.0);
here's a working example (see the large white text over the main banner image) http://www.cb.restaurantconnectinc.com/
Need to include these two scripts for IE
<script src="http://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="http://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
Maybe you like to check the links below:
Standard CSS3 rotate should work in IE9, but I believe you need to give it a vendor prefix, like so:
-ms-transform: rotate(10deg);
It is possible that it may not work in the beta version; if not, try downloading the current preview version (preview 7), which is a later revision that the beta. I don't have the beta version to test against, so I can't confirm whether it was in that version or not. The final release version is definitely slated to support it.
I can also confirm that the IE-specific filter
property has been dropped in IE9.
[Edit]
People have asked for some further documentation. As they say, this is quite limited, but I did find this page: http://css3please.com/ which is useful for testing various CSS3 features in all browsers.
But testing the rotate feature on this page in IE9 preview caused it to crash fairly spectacularly.
However I have done some independant tests using -ms-transform:rotate()
in IE9 in my own test pages, and it is working fine. So my conclusion is that the feature is implemented, but has got some bugs, possibly related to setting it dynamically.
Another useful reference point for which features are implemented in which browsers is www.canIuse.com -- see http://caniuse.com/#search=rotation
[EDIT]
Reviving this old answer because I recently found out about a hack called CSS Sandpaper which is relevant to the question and may make things easier.
The hack implements support for the standard CSS transform
for for old versions of IE. So now you can add the following to your CSS:
-sand-transform: rotate(10deg);
...and have it work in IE 6/7/8, without having to use the filter
syntax. (of course it still uses the filter syntax behind the scenes, but this makes it a lot easier to manage because it's using similar syntax to other browsers)
Internet Explorer and Edge do not support some MP4 formats that Chrome does. You can use ffprobe
to see the exact MP4 format. In my case I have these two videos:
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf56.40.101
Duration: 00:00:12.10, start: 0.000000, bitrate: 287 kb/s
Stream #0:0(und): Video: h264 (High 4:4:4 Predictive) (avc1 / 0x31637661), yuv444p, 1000x1000 [SAR 1:1 DAR 1:1], 281 kb/s, 60 fps, 60 tbr, 15360 tbn, 120 tbc (default)
Metadata:
handler_name : VideoHandler
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'b.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf57.66.102
Duration: 00:00:33.83, start: 0.000000, bitrate: 505 kb/s
Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 1280x680, 504 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
Metadata:
handler_name : VideoHandler
Both play fine in Chrome, but the first one fails in IE and Edge. The problem is that IE and Edge don't support yuv444. You can convert to a shittier colourspace like this:
ffmpeg -i input.mp4 -pix_fmt yuv420p output.mp4
Not exactly the same, but could work for some cases: there is another option ALLOWALL
which will effectively remove the restriction, which might be a nice thing for testing/pre-production environments
As an aside on more modern websites, if you are using conditional statements on your html tag as per boilerplate, this will for some reason cause ie9 to default to compatibility mode. The fix here is to move your conditional statements off the html tag and add them to the body tag, in other words out of the head section. That way you can still use those classes in your style sheet to target older browsers.
The issue might be to do with your server configuration - it may not be sending the right headers for the font files. Take a look at the answer given for the question IE9 blocks download of cross-origin web font.
EricLaw suggests adding the following to your Apache config
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://mydomain.com"
</IfModule>
</FilesMatch>
Opera will soon start having builds available with gradient support, as well as other CSS features.
The W3C CSS Working Group is not even finished with CSS 2.1, y'all know that, right? We intend to be finished very soon. CSS3 is modularized precisely so we can move modules through to implementation faster rather than an entire spec.
Every browser company uses a different software cycle methodology, testing, and so on. So the process takes time.
I'm sure many, many readers well know that if you're using anything in CSS3, you're doing what's called "progressive enhancement" - the browsers with the most support get the best experience. The other part of that is "graceful degradation" meaning the experience will be agreeable but perhaps not the best or most attractive until that browser has implemented the module, or parts of the module that are relevant to what you want to do.
This creates quite an odd situation that unfortunately front-end devs get extremely frustrated by: inconsistent timing on implementations. So it's a real challenge on either side - do you blame the browser companies, the W3C, or worse yet - yourself (goodness knows we can't know it all!) Do those of us who are working for a browser company and W3C group members blame ourselves? You?
Of course not. It's always a game of balance, and as of yet, we've not as an industry figured out where that point of balance really is. That's the joy of working in evolutionary technology :)
Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)
Thank goodness I found this. The following is extremely important:
<meta http-equiv="X-UA-Compatible" content="IE=9" >
Without this, none of the reports I'd been generating would work post IE9 install despite having worked great in IE8. They would show up properly in a web browser control, but there would be missing letters, jacked up white space, etc, when I called .Print(). They were just basic HTML that should be capable of being rendered even in Mosaic. heh Not sure why the IE7 compatibility mode was going haywire. Notably, you could .Print() the same page 5 times and have it be missing different letters each time. It would even carry over into PDF output, so it's definitely the browser.
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
It happened in IE 11 for me. And I was calling the jquery .load function. So I did it the old fashion way and put something in the url to disable cacheing.
$("#divToReplaceHtml").load('@Url.Action("Action", "Controller")/' + @Model.ID + "?nocache=" + new Date().getTime());
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
This makes each version of IE use its standard mode, so IE 9 will use IE 9 standards mode. (If instead you wanted newer versions of IE to also specifically use IE 9 standards mode, you would replace Edge
by 9
. But it is difficult to see why you would want that.)
For explanations, see http://hsivonen.iki.fi/doctype/#ie8 (it looks rather messy, but that’s because IE is messy in its behaviors).
If you want to input a description you can use this. This works on IE 9 and all other browsers.
<input type="text" onclick="if(this.value=='CVC2: '){this.value='';}" onblur="if(this.value==''){this.value='CVC2: ';}" value="CVC2: "/>
Getting a cross-domain JSON with jQuery in Internet Explorer 8 and newer versions
Very useful link:
Can help with the trouble of returning json from a X Domain Request.
Hope this helps somebody.
In my particular case, I had a similar error on a legacy website used in my organization. To solve the issue, I had to list the website a a "Trusted site".
To do so:
I'm leaving this here in the remote case it will help someone.
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
I'd just like to note another possible approach - and that is by using git
git-notes(1), in existence since v 1.6.6 (Note to Self - Git) (I'm using git
version 1.7.9.5).
Basically, I used git svn
to clone an SVN repository with linear history (no standard layout, no branches, no tags), and I wanted to compare revision numbers in the cloned git
repository. This git clone doesn't have tags by default, so I cannot use git describe
. The strategy here likely would work only for linear history - not sure how it would turn out with merges etc.; but here is the basic strategy:
git rev-list
for list of all commit history
rev-list
is by default in "reverse chronological order", we'd use its --reverse
switch to get list of commits sorted by oldest firstbash
shell to
git log
with --notes
, which will also dump a commit's note, which in this case would be the "revision number"git status
)First, let's note that git
has a default location of notes - but you can also specify a ref
(erence) for notes - which would store them in a different directory under .git
; for instance, while in a git
repo folder, you can call git notes get-ref
to see what directory that will be:
$ git notes get-ref
refs/notes/commits
$ git notes --ref=whatever get-ref
refs/notes/whatever
The thing to be noted is that if you notes add
with a --ref
, you must also afterwards use that reference again - otherwise you may get errors like "No note found for object XXX...".
For this example, I have chosen to call the ref
of the notes "linrev" (for linear revision) - this also means it is not likely the procedure will interfere with already existing notes. I am also using the --git-dir
switch, since being a git
newbie, I had some problems understanding it - so I'd like to "remember for later" :)
; and I also use --no-pager
to suppress spawning of less
when using git log
.
So, assuming you're in a directory, with a subfolder myrepo_git
which is a git
repository; one could do:
### check for already existing notes:
$ git --git-dir=./myrepo_git/.git notes show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
$ git --git-dir=./myrepo_git/.git notes --ref=linrev show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
### iterate through rev-list three, oldest first,
### create a cmdline adding a revision count as note to each revision
$ ix=0; for ih in $(git --git-dir=./myrepo_git/.git rev-list --reverse HEAD); do \
TCMD="git --git-dir=./myrepo_git/.git notes --ref linrev"; \
TCMD="$TCMD add $ih -m \"(r$((++ix)))\""; \
echo "$TCMD"; \
eval "$TCMD"; \
done
# git --git-dir=./myrepo_git/.git notes --ref linrev add 6886bbb7be18e63fc4be68ba41917b48f02e09d7 -m "(r1)"
# git --git-dir=./myrepo_git/.git notes --ref linrev add f34910dbeeee33a40806d29dd956062d6ab3ad97 -m "(r2)"
# ...
# git --git-dir=./myrepo_git/.git notes --ref linrev add 04051f98ece25cff67e62d13c548dacbee6c1e33 -m "(r15)"
### check status - adding notes seem to not affect it:
$ cd myrepo_git/
$ git status
# # On branch master
# nothing to commit (working directory clean)
$ cd ../
### check notes again:
$ git --git-dir=./myrepo_git/.git notes show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
$ git --git-dir=./myrepo_git/.git notes --ref=linrev show
# (r15)
### note is saved - now let's issue a `git log` command, using a format string and notes:
$ git --git-dir=./myrepo_git/.git --no-pager log --notes=linrev --format=format:"%h: %an: %ad: >>%s<< %N" HEAD
# 04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000: >>test message 15 << (r15)
# 77f3902: _user_: Sun Apr 21 18:29:00 2013 +0000: >>test message 14<< (r14)
# ...
# 6886bbb: _user_: Sun Apr 21 17:11:52 2013 +0000: >>initial test message 1<< (r1)
### test git log with range:
$ git --git-dir=./myrepo_git/.git --no-pager log --notes=linrev --format=format:"%h: %an: %ad: >>%s<< %N" HEAD^..HEAD
# 04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000: >>test message 15 << (r15)
### erase notes - again must iterate through rev-list
$ ix=0; for ih in $(git --git-dir=./myrepo_git/.git rev-list --reverse HEAD); do \
TCMD="git --git-dir=./myrepo_git/.git notes --ref linrev"; \
TCMD="$TCMD remove $ih"; \
echo "$TCMD"; \
eval "$TCMD"; \
done
# git --git-dir=./myrepo_git/.git notes --ref linrev remove 6886bbb7be18e63fc4be68ba41917b48f02e09d7
# Removing note for object 6886bbb7be18e63fc4be68ba41917b48f02e09d7
# git --git-dir=./myrepo_git/.git notes --ref linrev remove f34910dbeeee33a40806d29dd956062d6ab3ad97
# Removing note for object f34910dbeeee33a40806d29dd956062d6ab3ad97
# ...
# git --git-dir=./myrepo_git/.git notes --ref linrev remove 04051f98ece25cff67e62d13c548dacbee6c1e33
# Removing note for object 04051f98ece25cff67e62d13c548dacbee6c1e33
### check notes again:
$ git --git-dir=./myrepo_git/.git notes show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
$ git --git-dir=./myrepo_git/.git notes --ref=linrev show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
So, at least in my specific case of fully linear history with no branches, the revision numbers seem to match with this approach - and additionally, it seems that this approach will allow using git log
with revision ranges, while still getting the right revision numbers - YMMV with a different context, though...
Hope this helps someone,
Cheers!
EDIT: Ok, here it is a bit easier, with git
aliases for the above loops, called setlinrev
and unsetlinrev
; when in your git repository folder, do (Note the nasty bash
escaping, see also #16136745 - Add a Git alias containing a semicolon):
cat >> .git/config <<"EOF"
[alias]
setlinrev = "!bash -c 'ix=0; for ih in $(git rev-list --reverse HEAD); do \n\
TCMD=\"git notes --ref linrev\"; \n\
TCMD=\"$TCMD add $ih -m \\\"(r\\$((++ix)))\\\"\"; \n\
#echo \"$TCMD\"; \n\
eval \"$TCMD\"; \n\
done; \n\
echo \"Linear revision notes are set.\" '"
unsetlinrev = "!bash -c 'ix=0; for ih in $(git rev-list --reverse HEAD); do \n\
TCMD=\"git notes --ref linrev\"; \n\
TCMD=\"$TCMD remove $ih\"; \n\
#echo \"$TCMD\"; \n\
eval \"$TCMD 2>/dev/null\"; \n\
done; \n\
echo \"Linear revision notes are unset.\" '"
EOF
... so you can simply invoke git setlinrev
before trying to do log involving linear revision notes; and git unsetlinrev
to delete those notes when you're done; an example from inside the git repo directory:
$ git log --notes=linrev --format=format:"%h: %an: %ad: >>%s<< %N" HEAD^..HEAD
04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000: >>test message 15 <<
$ git setlinrev
Linear revision notes are set.
$ git log --notes=linrev --format=format:"%h: %an: %ad: >>%s<< %N" HEAD^..HEAD
04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000: >>test message 15 << (r15)
$ git unsetlinrev
Linear revision notes are unset.
$ git log --notes=linrev --format=format:"%h: %an: %ad: >>%s<< %N" HEAD^..HEAD
04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000: >>test message 15 <<
The time it would take the shell to complete these aliases, would depend on the size of the repository history.
This is simple if you only use Selenium WebDriver, and forget the usage of Selenium-RC. I'd go like this.
WebDriver driver = new FirefoxDriver();
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("[email protected]");
The reason for NullPointerException
however is that your variable driver
has never been started, you start FirefoxDriver
in a variable wb
thas is never being used.
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
SET @x=@x+1
INSERT INTO Numbers VALUES (@x)
END
here is the function:
CREATE FUNCTION dbo.ListDates
(
@StartDate char(10)
,@EndDate char(10)
)
RETURNS
@DateList table
(
Date datetime
)
AS
BEGIN
IF ISDATE(@StartDate)!=1 OR ISDATE(@EndDate)!=1
BEGIN
RETURN
END
INSERT INTO @DateList
(Date)
SELECT
CONVERT(datetime,@StartDate)+n.Number-1
FROM Numbers n
WHERE Number<=DATEDIFF(day,@StartDate,CONVERT(datetime,@EndDate)+1)
RETURN
END --Function
use this:
select * from dbo.ListDates('2010-01-01', '2010-01-13')
output:
Date
-----------------------
2010-01-01 00:00:00.000
2010-01-02 00:00:00.000
2010-01-03 00:00:00.000
2010-01-04 00:00:00.000
2010-01-05 00:00:00.000
2010-01-06 00:00:00.000
2010-01-07 00:00:00.000
2010-01-08 00:00:00.000
2010-01-09 00:00:00.000
2010-01-10 00:00:00.000
2010-01-11 00:00:00.000
2010-01-12 00:00:00.000
2010-01-13 00:00:00.000
(13 row(s) affected)
Note that the default when you make a class is not public as far as packages are considered. Make sure that you actually write public class [MyClass] {
when defining your class. I've made this mistake more times than I care to admit.
Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block
, so when one is pushed down the hole line is pushed down with him. Float fixes this:
#header button {
float:left;
}
Here's a working jsfidle.
Just use the Random class:
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
Added more complex example with "custom validation" on the side of controller http://jsfiddle.net/82PX4/3/
<div class='line' ng-repeat='line in ranges' ng-form='lineForm'>
low: <input type='text'
name='low'
ng-pattern='/^\d+$/'
ng-change="lowChanged(this, $index)" ng-model='line.low' />
up: <input type='text'
name='up'
ng-pattern='/^\d+$/'
ng-change="upChanged(this, $index)"
ng-model='line.up' />
<a href ng-if='!$first' ng-click='removeRange($index)'>Delete</a>
<div class='error' ng-show='lineForm.$error.pattern'>
Must be a number.
</div>
<div class='error' ng-show='lineForm.$error.range'>
Low must be less the Up.
</div>
</div>
Refer to:
http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.apps/2004-05/0436.html
You need the static version of the library to link it.
A shared library is actually an executable in a special format with entry points specified (and some sticky addressing issues included). It does not have all the information needed to link statically.
You can't statically link a shared library (or dynamically link a static one).
The flag -static
will force the linker to use static libraries (.a) instead of shared (.so) ones. But static libraries aren't always installed by default, so you may have to install the static library yourself.
Another possible approach is to use statifier or Ermine. Both tools take as input a dynamically linked executable and as output create a self-contained executable with all shared libraries embedded.
one more if you want to switch IE 8 page render in IE 8 standard mode
<meta http-equiv="X-UA-Compatible" content="IE=100" /> <!-- IE8 mode -->
You can use the following if you want to specify tricky formats:
df['date_col'] = pd.to_datetime(df['date_col'], format='%d/%m/%Y')
More details on format
here:
Spring 2 introduced ResponseStatusException using this you can return String, different HTTP status code, DTO at the same time.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
What worked for me:
class MyComponent extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); // Create a ref
}
// Scroll to ref function
scrollToMyRef = () => {
window.scrollTo({
top:this.myRef.offsetTop,
// behavior: "smooth" // optional
});
};
// On component mount, scroll to ref
componentDidMount() {
this.scrollToMyRef();
}
// Render method. Note, that `div` element got `ref`.
render() {
return (
<div ref={this.myRef}>My component</div>
)
}
}
The only way to remove the YouTube branding (while keeping the video clickable) is to place the embed iFrame inside a container that has overflow
set to hidden
and has a slightly smaller height than the iFrame.
Of course this means the bottom of your video gets chopped off.
Also, you will be most likely breaching YouTube's Terms of Service.
CSS:
.videoWrapper {
width: 550px;
height: 250px;
overflow: hidden;
}
HTML:
<div class="videoWrapper">
<iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
I think that the Ruby on Rails 3.0 method is now request.fullpath
.
I use a variable to store the entire connection string and pass it into the ConnectionString expression. This overwrites all settings for the connection and allows you store the password.
var timedifference = new Date().getTimezoneOffset();
This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.
No need for regex. os.path.splitext
is your friend:
os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
Here's working example with anonymous output record, if you have any questions place a comment below:
public partial class Form1 : Form
{
DataTable table;
public Form1()
{
InitializeComponent();
#region TestData
table = new DataTable();
table.Clear();
for (int i = 1; i < 12; ++i)
table.Columns.Add("Col" + i);
for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
{
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; ++i)
row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
table.Rows.Add(row);
}
#endregion
bind();
}
public void bind()
{
var filtered = from t in table.AsEnumerable()
select new
{
col1 = t.Field<string>(0),//column of index 0 = "Col1"
col2 = t.Field<string>(1),//column of index 1 = "Col2"
col3 = t.Field<string>(5),//column of index 5 = "Col6"
col4 = t.Field<string>(6),//column of index 6 = "Col7"
col5 = t.Field<string>(4),//column of index 4 = "Col3"
};
filteredData.AutoGenerateColumns = true;
filteredData.DataSource = filtered.ToList();
}
}
select case
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
then 0
else 1
end
Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.
Run Sql Profiler. Attach it to your database of course.
Then right click in the GUI (in SSMS) and click "Refresh".
And then go see what Profiler "catches".
I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".
Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.
But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.
SELECT
u.name AS [Name],
'Server[@Name=' + quotename(CAST(
serverproperty(N'Servername')
AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
u.create_date AS [CreateDate],
u.principal_id AS [ID],
CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
WHERE
(u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
ORDER BY
[Name] ASC
I prefer a short way using a nullable enum type variable.
var enumValue = (MyEnum?)enumInt;
if (!enumValue.HasValue)
{
throw new ArgumentException(nameof(enumValue));
}
I modified the sample by dimarzionist. This version will only work with Enums and not let structs get through.
public static T ParseEnum<T>(string enumString)
where T : struct // enum
{
if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)
throw new Exception("Type given must be an Enum");
try
{
return (T)Enum.Parse(typeof(T), enumString, true);
}
catch (Exception ex)
{
return default(T);
}
}
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
I might've over-engineered my own solution without realizing that Type.valueOf("enum string")
actually existed.
I guess it gives more granular control but I'm not sure it's really necessary.
public enum Type {
DEBIT,
CREDIT;
public static Map<String, Type> typeMapping = Maps.newHashMap();
static {
typeMapping.put(DEBIT.name(), DEBIT);
typeMapping.put(CREDIT.name(), CREDIT);
}
public static Type getType(String typeName) {
if (typeMapping.get(typeName) == null) {
throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
}
return typeMapping.get(typeName);
}
}
I guess you're exchanging IllegalArgumentException
for RuntimeException
(or whatever exception you wish to throw) which could potentially clean up code.
When styling a input type submit use the following code.
input[type=submit] {
background-color: pink; //Example stlying
}
You have to use bindPreferenceSummaryToValue function on the onCreate method.
Example:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
}
See lesson 3 on Udacity Android Course: https://www.udacity.com/course/viewer#!/c-ud853/l-1474559101/e-1643578599/m-1643578601
A lot of these answers are simplistic, and if someone is beginning WPF, they may not know all of the "ins-and-outs", as it is more complicated than just telling someone "Use .ShowDialog()
!". But that is the method (not .Show()
) that you want to use in order to block use of the underlying window and to keep the code from continuing until the modal window is closed.
First, you need 2 WPF windows. (One will be calling the other.)
From the first window, let's say that was called MainWindow.xaml, in its code-behind will be:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
Then add your button to your XAML:
<Button Name="btnOpenModal" Click="btnOpenModal_Click" Content="Open Modal" />
And right-click the Click
routine, select "Go to definition". It will create it for you in MainWindow.xaml.cs:
private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
}
Within that function, you have to specify the other page using its page class. Say you named that other page "ModalWindow", so that becomes its page class and is how you would instantiate (call) it:
private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
ModalWindow modalWindow = new ModalWindow();
modalWindow.ShowDialog();
}
Say you have a value you need set on your modal dialog. Create a textbox and a button in the ModalWindow
XAML:
<StackPanel Orientation="Horizontal">
<TextBox Name="txtSomeBox" />
<Button Name="btnSaveData" Click="btnSaveData_Click" Content="Save" />
</StackPanel>
Then create an event handler (another Click
event) again and use it to save the textbox value to a public static variable on ModalWindow
and call this.Close()
.
public partial class ModalWindow : Window
{
public static string myValue = String.Empty;
public ModalWindow()
{
InitializeComponent();
}
private void btnSaveData_Click(object sender, RoutedEventArgs e)
{
myValue = txtSomeBox.Text;
this.Close();
}
}
Then, after your .ShowDialog()
statement, you can grab that value and use it:
private void btnOpenModal_Click(object sender, RoutedEventArgs e)
{
ModalWindow modalWindow = new ModalWindow();
modalWindow.ShowDialog();
string valueFromModalTextBox = ModalWindow.myValue;
}
I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.
Just add
::-webkit-scrollbar {display:none;}
To your id or class of the div you're using the scroll bar with.
Here is a helpful link Custom Scroll Bar in Webkit
From a web page this cannot work since IE restricts the use of that object.
You can use the Set structure from ES6 to make your code faster and more readable:
// Create Set
this.items = new Set();
add(item) {
this.items.add(item);
// Set to array
console.log([...this.items]);
}
app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
var data = {
"fruit": {
"apple": req.params.fruitName,
"color": req.params.fruitColor
}
};
send.json(data);
});
If that doesn't work, try using console.log(req.params) to see what it is giving you.
You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!
Here's a solution that keeps numbers as numbers:
# first remember the names
n <- df.aree$name
# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))
str(df.aree) # Check the column types
With the package pROC
you can use the function auc()
like this example from the help page:
> data(aSAH)
>
> # Syntax (response, predictor):
> auc(aSAH$outcome, aSAH$s100b)
Area under the curve: 0.7314
You can pass PHP arrays to JavaScript using json_encode
PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
app = Celery(__name__, broker=app.config['CELERY_BROKER'],
backend=app.config['CELERY_BACKEND'], include=['util.xxxx', 'util.yyyy'])
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementTo illustrate Jon's point what's shown below cannot be done if Logger was a static class.The class SomeClass
expects an instance of ILogger
implementation to be passed into its constructor.
Singleton class is important for dependency injection to be possible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass(Logger.GetLogger());
}
}
public class SomeClass
{
public SomeClass(ILogger MyLogger)
{
}
}
public class Logger : ILogger
{
private static Logger _logger;
private Logger() { }
public static Logger GetLogger()
{
if (_logger==null)
{
_logger = new Logger();
}
return _logger;
}
public void Log()
{
}
}
public interface ILogger
{
void Log();
}
}
Try this code:
<?php
$path = '/var/www/html/project/somefolder';
$dirs = array();
// directory handle
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
if ($entry != '.' && $entry != '..') {
if (is_dir($path . '/' .$entry)) {
$dirs[] = $entry;
}
}
}
echo "<pre>"; print_r($dirs); exit;
cat /sys/class/net/ethX
is by far the easiest method.
The interface has to be up though, else you will get an invalid argument error.
So first:
ifconfig ethX up
Then:
cat /sys/class/net/ethX
The algorithm (HS256
) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.
If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.
For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.
PHP has several libraries for XML Manipulation.
The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows
<?php
$doc = new DOMDocument( );
$ele = $doc->createElement( 'Root' );
$ele->nodeValue = 'Hello XML World';
$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');
?>
Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.
This works.
public class TestButton {
public TestButton() {
JFrame f = new JFrame();
f.setSize(new Dimension(200,200));
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
final JButton stop = new JButton("Stop");
final JButton start = new JButton("Start");
p.add(start);
p.add(stop);
f.getContentPane().add(p);
stop.setEnabled(false);
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(true);
stop.setEnabled(false);
}
});
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(false);
stop.setEnabled(true);
}
});
f.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
new TestButton();
}
}
If you only have two choices to select from:
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
For example,
import pandas as pd
import numpy as np
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)
yields
Set Type color
0 Z A green
1 Z B green
2 X B red
3 Y C red
If you have more than two conditions then use np.select
. For example, if you want color
to be
yellow
when (df['Set'] == 'Z') & (df['Type'] == 'A')
blue
when (df['Set'] == 'Z') & (df['Type'] == 'B')
purple
when (df['Type'] == 'B')
black
,then use
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
conditions = [
(df['Set'] == 'Z') & (df['Type'] == 'A'),
(df['Set'] == 'Z') & (df['Type'] == 'B'),
(df['Type'] == 'B')]
choices = ['yellow', 'blue', 'purple']
df['color'] = np.select(conditions, choices, default='black')
print(df)
which yields
Set Type color
0 Z A yellow
1 Z B blue
2 X B purple
3 Y C black
(untested) something like this may do the job
WITH
base AS
(
select * -- get the table
from sometable
order by name -- in the desired order
),
twenty AS
(
select * -- get the first 30 rows
from base
where rownum < 30
order by name -- in the desired order
)
select * -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name -- in the desired order
There is also the analytic function rank, that you can use to order by.
This is how I solved my issue.
I noticed if you are including jar files with your compilation, adding the current directory (./) to the classpath helps.
javac -cp "abc.jar;efg.jar" MyClass.java
java -cp "abc.jar;efg.jar" MyClass
VS
javac -cp "./;abc.jar;efg.jar" MyClass.java
java -cp "./;abc.jar;efg.jar" MyClass
According to reactjs.org, componentWillMount will not be supported in the future. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount
There is no need to use componentWillMount.
If you want to do something before the component mounted, just do it in the constructor().
If you want to do network requests, do not do it in componentWillMount. It is because doing this will lead to unexpected bugs.
Network requests can be done in componentDidMount.
Hope it helps.
updated on 08/03/2019
The reason why you ask for componentWillMount is probably because you want to initialize the state before renders.
Just do it in useState.
const helloWorld=()=>{
const [value,setValue]=useState(0) //initialize your state here
return <p>{value}</p>
}
export default helloWorld;
or maybe You want to run a function in componentWillMount, for example, if your original code looks like this:
componentWillMount(){
console.log('componentWillMount')
}
with hook, all you need to do is to remove the lifecycle method:
const hookComponent=()=>{
console.log('componentWillMount')
return <p>you have transfered componeWillMount from class component into hook </p>
}
I just want to add something to the first answer about useEffect.
useEffect(()=>{})
useEffect runs on every render, it is a combination of componentDidUpdate, componentDidMount and ComponentWillUnmount.
useEffect(()=>{},[])
If we add an empty array in useEffect it runs just when the component mounted. It is because useEffect will compare the array you passed to it. So it does not have to be an empty array.It can be array that is not changing. For example, it can be [1,2,3] or ['1,2']. useEffect still only runs when component mounted.
It depends on you whether you want it to run just once or runs after every render. It is not dangerous if you forgot to add an array as long as you know what you are doing.
I created a sample for hook. Please check it out.
https://codesandbox.io/s/kw6xj153wr
updated on 21/08/2019
It has been a while since I wrote the above answer. There is something that I think you need to pay attention to. When you use
useEffect(()=>{},[])
When react compares the values you passed to the array [], it uses Object.is()
to compare.
If you pass an object to it, such as
useEffect(()=>{},[{name:'Tom'}])
This is exactly the same as:
useEffect(()=>{})
It will re-render every time because when Object.is()
compares an object, it compares its reference, not the value itself. It is the same as why {}==={} returns false because their references are different.
If you still want to compare the object itself not the reference, you can do something like this:
useEffect(()=>{},[JSON.stringify({name:'Tom'})])
substring(startIndex, endIndex(not included))
substr(startIndex, how many characters)
const string = 'JavaScript';
console.log('substring(1,2)', string.substring(1,2)); // a
console.log('substr(1,2)', string.substr(1,2)); // av
Wouldn't
(int) Math.Min(Int32.MaxValue, longValue)
be the correct way, mathematically speaking?
you can store it in array and then use whichever line you want.. this is the code snippet that i have used to read line from file and store it in a string array, hope this will be useful for you :)
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[30];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
You can use this command,
jmeter -n -t /path to the script.jmx -l /path to save results with file name file.jtl
But if you really want to run a load test in a remote machine, you should be able to make it run eventhough you close the window. So we can use nohup to ignore the HUP (hangup) signal. So you can use this command as below.
nohup sh jmeter.sh -n -t /path to the script.jmx -l /path to save results with file name file.jtl &
Make sure the value in the child's project/parent/version node matches its parent's project/version value
In VS + NUnit I usually create folders in my project to group functional tests together. Then I create unit test fixture classes and name them after the type of functionality I'm testing. The [Test] methods are named along the lines of Can_add_user_to_domain
:
- MyUnitTestProject
+ FTPServerTests <- Folder
+ UserManagerTests <- Test Fixture Class
- Can_add_user_to_domain <- Test methods
- Can_delete_user_from_domain
- Can_reset_password
Try this:
input.focus();
input.scrollIntoView()
You can also "prepend" the environment variable setting by using 'environment' command:
run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }
Not to trample on BBoy's already decent answer, but I've done the code that maintains aspect ratio. I took his suggestion, so he should get partial credit here!
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
pd.DefaultPageSettings.Landscape = true; //or false!
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(@"C:\...\...\image.jpg");
Rectangle m = args.MarginBounds;
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
args.Graphics.DrawImage(i, m);
};
pd.Print();
The property you are looking for that first td is rowspan
:
http://www.angelfire.com/fl5/html-tutorial/tables/tr_code.htm
<table>
<tr><td rowspan="2"></td><td colspan='4'></td></tr>
<tr><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
Use tolist()
:
import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
For your task you can use pandas.DataFrame.dropna (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html):
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [1, 2, 3, 4, np.nan],
'b': [1, 2, np.nan, 4, np.nan],
'c': [np.nan, 2, np.nan, 4, np.nan]})
df = df.dropna(axis='columns', thresh=3)
print(df)
Whith thresh parameter you can declare the max count for NaN values for all columns in DataFrame.
Code outputs:
a b
0 1.0 1.0
1 2.0 2.0
2 3.0 NaN
3 4.0 4.0
4 NaN NaN
Using the DataFormatter
this issue is resolved. Thanks to "Gagravarr" for the initial post.
DataFormatter formatter = new DataFormatter();
String empno = formatter.formatCellValue(cell0);
Following will give you the selected content as well as updating the clipboard.
Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.
document.querySelector('element').bind('copy', function(event) {
var selectedText = window.getSelection().toString();
selectedText = selectedText.replace(/\u200B/g, "");
clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
clipboardData.setData('text/html', selectedText);
event.preventDefault();
});
I didn't have the name in my Input ... my request was empty... glad that is finished and I can keep coding. Thanks everyone!
Answer I used by Jason Kim:
So instead of
<input type="password" class="form-control" id="password">
I have this
<input type="password" class="form-control" id="password" name="password">
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
You have indented part of your code in settings.py:
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
#'django.contrib.admindocs',
'tinymce',
'sorl.thumbnail',
'south',
'django_facebook',
'djcelery',
'devserver',
'main',
Therefore, it is giving you an error.
Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:
>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
I used the following on Mac OSX.
currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")
You can reference Microsoft.VisualBasic.dll
.
Then using the code below.
Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");
Alternatively, by adding a using
directive allowing for a shorter syntax in your code (which I'd personally prefer).
using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");
Or you can do what Pranay Rana suggests, that's what I would've done too...
select * from SHOW VARIABLES WHERE Variable_name = 'hostname';
There is another useful method called AutoResizeColumn
which allows you to auto size a specific column with the required parameter.
You can call it like this:
listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);
you can't assign an event by string. Use that:
elemm.onclick = function(){ alert('blah'); };
The right way to iterate on a list inside list is:
//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
ArrayList<String> currentList = collection.get(i);
//now iterate on the current list
for (int j = 0; j < currentList.size(); j++) {
String s = currentList.get(1);
}
}
Since this is a fatal error and also quite difficult to debug, maybe the fix could be put somewhere (in the provided command line?):
export GPG_TTY=$(tty)
I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:
http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes
>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue)
as a parameter, but the Queue
class is abstract. I solved that by using a QueuePtr(myQueue)
constructor like so:
using QueuePtr = std::unique_ptr<Queue>;
and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue
when you make a std::unique_ptr
of its type, which can't happen.
If anyone is coming here looking for an answer that utilizes iframe
here it is
<iframe srcdoc="<html><body>your-html-here</body></html>" />
Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.
public class PQ {
public static void main(String[] args) {
// create dog object here
Dog dog = new PQ().new Dog();
//OR
PQ pq = new PQ();
Dog dog1 = pq.new Dog();
}
abstract class Animal {
abstract void checkup();
}
class Dog extends Animal {
@Override
void checkup() {
System.out.println("Dog checkup");
}
}
class Cat extends Animal {
@Override
void checkup() {
System.out.println("Cat Checkup");
}
}
}
The answer from Alexander refers to complete docs...
Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.
I had the same problem working on a project with asp.NET. I was using bootstrap 3.1.0 solved it downgrading to Bootstrap 2.3.2.
You can try something like this:
public interface PersonRepository extends CrudRepository<Person, Long> {
@Query("select p from Person AS p"
+ " ,Name AS n"
+ " where p.forename = n.forename "
+ " and p.surname = n.surname"
+ " and n = :name")
Set<Person>findByName(@Param("name") Name name);
}
Answering to myself. From the RequireJS website:
//THIS WILL FAIL
define(['require'], function (require) {
var namedModule = require('name');
});
This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.
My solution:
// Modules configuration (modules that will be used as Jade helpers)
define(function () {
return {
'moment': 'path/to/moment',
'filesize': 'path/to/filesize',
'_': 'path/to/lodash',
'_s': 'path/to/underscore.string'
};
});
The loader:
define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
var deps;
// Dynamic require
require(_.values(Config), function () {
deps = _.object(_.keys(Config), arguments);
// Use deps...
});
});
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
You can use a list comprehension:
>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]
The script in How to get rid of the white margin in MATLAB's saveas or print outputs does what you want.
Make your figure boundaries tight:
ti = get(gca,'TightInset')
set(gca,'Position',[ti(1) ti(2) 1-ti(3)-ti(1) 1-ti(4)-ti(2)]);
... if you directly do saveas (or print), MATLAB will still add the annoying white space. To get rid of them, we need to adjust the ``paper size":
set(gca,'units','centimeters')
pos = get(gca,'Position');
ti = get(gca,'TightInset');
set(gcf, 'PaperUnits','centimeters');
set(gcf, 'PaperSize', [pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'PaperPosition',[0 0 pos(3)+ti(1)+ti(3) pos(4)+ti(2)+ti(4)]);
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:
string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
Right code of two ppl before ^_^
/* return true if values of array are empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr as $value){
if(!empty($value)){
return false;
}
}
}
return true;
}
Just checked IE 7, Firefox 3.6.8 Mac, Firefox 3.6.8 Windows, and Safari:
word-wrap: break-word;
works for long links inside of a div with a set width and no overflow declared in the css:
#consumeralerts_leftcol{
float:left;
width: 250px;
margin-bottom:10px;
word-wrap: break-word;
}
I don't see any incompatibility issues
It only comes when your list or dictionary not available in the local function.
//by importing Decimal format we can do...
import java.util.Scanner;
import java.text.DecimalFormat;
public class Average
{
public static void main(String[] args)
{
int sub1,sub2,sub3,total;
Scanner in = new Scanner(System.in);
System.out.print("Enter Subject 1 Marks : ");
sub1 = in.nextInt();
System.out.print("Enter Subject 2 Marks : ");
sub2 = in.nextInt();
System.out.print("Enter Subject 3 Marks : ");
sub3 = in.nextInt();
total = sub1 + sub2 + sub3;
System.out.println("Total Marks of Subjects = " + total);
res = (float)total;
average = res/3;
System.out.println("Before Rounding Decimal.. Average = " +average +"%");
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("After Rounding Decimal.. Average = " +df.format(average)+"%");
}
}
/* Output
Enter Subject 1 Marks : 72
Enter Subject 2 Marks : 42
Enter Subject 3 Marks : 52
Total Marks of Subjects = 166
Before Rounding Decimal.. Average = 55.333332%
After Rounding Decimal.. Average = 55.33%
*/
/* Output
Enter Subject 1 Marks : 98
Enter Subject 2 Marks : 88
Enter Subject 3 Marks : 78
Total Marks of Subjects = 264
Before Rounding Decimal.. Average = 88.0%
After Rounding Decimal.. Average = 88%
*/
/* You can Find Avrerage values in two ouputs before rounding average
And After rounding Average..*/
Doesn't log4j just use the application root directory if you don't specify a root directory in your FileAppender's path property? So you should just be able to use:
log4j.appender.file.File=logs/MyLog.log
It's been awhile since I've done Java web development, but this seems to be the most intuitive, and also doesn't collide with other unfortunately named logs writing to the ${catalina.home}/logs directory.
for(i=1;i<13;i++)
{
alert($("#tdt"+i).val());
}
simple and best way to use date function
example
SELECT * FROM
data
WHERE date(datetime) = '2009-10-20'
OR
SELECT * FROM
data
WHERE date(datetime ) >= '2009-10-20' && date(datetime ) <= '2009-10-20'
You could use scrollTop
instead of scrollIntoView()
:
var target = document.getElementById("target");
target.parentNode.scrollTop = target.offsetTop;
jsFiddle: http://jsfiddle.net/LEqjm/
If there's more than one scrollable element that you want to scroll, you'll need to change the scrollTop
of each one individually, based on the offsetTop
s of the intervening elements. This should give you the fine-grained control to avoid the problem you're having.
EDIT: offsetTop isn't necessarily relative to the parent element - it's relative to the first positioned ancestor. If the parent element isn't positioned (relative, absolute or fixed), you may need to change the second line to:
target.parentNode.scrollTop = target.offsetTop - target.parentNode.offsetTop;
You could also position the hidden div off the screen with a negative margin rather than using display:none, much like a the text indent image replacement technique.
eg.
position:absolute;
left: -2000px;
top: 0;
This way the height() is still available.
You have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy
do not stack, but you can make multiple calls to addOrderBy
:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');
Using reduce is clever, but the OP's set method may have issues if the parent keys do not pre-exist in the nested dictionary. Since this is the first SO post I saw for this subject in my google search, I would like to make it slightly better.
The set method in ( Setting a value in a nested python dictionary given a list of indices and value ) seems more robust to missing parental keys. To copy it over:
def nested_set(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
Also, it can be convenient to have a method that traverses the key tree and get all the absolute key paths, for which I have created:
def keysInDict(dataDict, parent=[]):
if not isinstance(dataDict, dict):
return [tuple(parent)]
else:
return reduce(list.__add__,
[keysInDict(v,parent+[k]) for k,v in dataDict.items()], [])
One use of it is to convert the nested tree to a pandas DataFrame, using the following code (assuming that all leafs in the nested dictionary have the same depth).
def dict_to_df(dataDict):
ret = []
for k in keysInDict(dataDict):
v = np.array( getFromDict(dataDict, k), )
v = pd.DataFrame(v)
v.columns = pd.MultiIndex.from_product(list(k) + [v.columns])
ret.append(v)
return reduce(pd.DataFrame.join, ret)
for installing multiple packages, i am using a setup.py file with following code:
import sys
import subprocess
import pkg_resources
required = {'numpy','pandas','<etc>'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])
You need to pass some data into it. An empty dictionary, for example.
if __name__ == '__main__': DHT('a').showData()
However, in your example a parameter is not even needed. You can declare it by just:
def __init__(self):
Maybe you mean to set it from the data?
class DHT:
def __init__(self, data):
self.data['one'] = data['one']
self.data['two'] = data['two']
self.data['three'] = data['three']
def showData(self):
print(self.data)
if __name__ == '__main__': DHT({'one':2, 'two':4, 'three':5}).showData()
showData
will print the data you just entered.
Here's an approach that leaves the default collapse behavior unchanged while allowing a new section of navigation to always remain visible. Its an augmentation of navbar
; navbar-header-menu
is a CSS class I have created and is not part of Bootstrap proper.
Place this in the navbar-header
element after navbar-brand
:
<div class="navbar-header-menu">
<ul class="nav navbar-nav">
<li class="active"><a href="#">I'm always visible</a></li>
</ul>
<form class="navbar-form" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Add this CSS:
.navbar-header-menu {
float: left;
}
.navbar-header-menu > .navbar-nav {
float: left;
margin: 0;
}
.navbar-header-menu > .navbar-nav > li {
float: left;
}
.navbar-header-menu > .navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
.navbar-header-menu > .navbar-nav .open .dropdown-menu {
position: absolute;
float: left;
width: auto;
margin-top: 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.15);
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
.navbar-header-menu > .navbar-form {
float: left;
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-header-menu > .navbar-form > .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-header-menu > .navbar-left {
float: left;
}
.navbar-header-menu > .navbar-right {
float: right !important;
}
.navbar-header-menu > *.navbar-right:last-child {
margin-right: -15px !important;
}
Check the fiddle: http://jsfiddle.net/L2txunqo/
Caveat: navbar-right
can be used to sort elements visually but is not guaranteed to pull the element to the furthest right portion of the screen. The fiddle demonstrates that behavior with the navbar-form
.
Set the insetForSectionAt
property of the UICollectionViewFlowLayout
object attached to your UICollectionView
Make sure to add this protocol
UICollectionViewDelegateFlowLayout
Swift
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
}
Objective - C
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(top, left, bottom, right);
}
If you really have:
var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];
then simply:
var objs = $.map(s, $.parseJSON);
If you simply open the file for writing with the truncate-option, you'll delete the content.
std::ofstream ofs;
ofs.open("test.txt", std::ofstream::out | std::ofstream::trunc);
ofs.close();
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
public class ConfigMan
{
#region Members
string _assemblyLocation;
Configuration _configuration;
#endregion Members
#region Constructors
/// <summary>
/// Loads config file settings for libraries that use assembly.dll.config files
/// </summary>
/// <param name="assemblyLocation">The full path or UNC location of the loaded file that contains the manifest.</param>
public ConfigMan(string assemblyLocation)
{
_assemblyLocation = assemblyLocation;
}
#endregion Constructors
#region Properties
Configuration Configuration
{
get
{
if (_configuration == null)
{
try
{
_configuration = ConfigurationManager.OpenExeConfiguration(_assemblyLocation);
}
catch (Exception exception)
{
}
}
return _configuration;
}
}
#endregion Properties
#region Methods
public string GetAppSetting(string key)
{
string result = string.Empty;
if (Configuration != null)
{
KeyValueConfigurationElement keyValueConfigurationElement = Configuration.AppSettings.Settings[key];
if (keyValueConfigurationElement != null)
{
string value = keyValueConfigurationElement.Value;
if (!string.IsNullOrEmpty(value)) result = value;
}
}
return result;
}
#endregion Methods
}
Just for something to do, I refactored the top answer into a class. The usage is something like:
ConfigMan configMan = new ConfigMan(this.GetType().Assembly.Location);
var setting = configMan.GetAppSetting("AppSettingsKey");
As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:
array_push($md_array['recipe_type'], $newdata);
If it is not a typo, as pointed out earlier, it could be wrong compiler options like compiling 64 bit under 32 bit. It must not be a toolchain.
I found myself in a similar predicament today while trying to run a command through a Node.js module:
I was using the PowerShell and trying to run:
command -e 'func($a)'
But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:
command -e `"func($a)`"
Tomcat (Headless) can be integrated with IntelliJ Idea - Community edition.
Step-by-step instructions are as below:
Add tomcatX-maven-plugin
to pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>SampleProject</path>
</configuration>
</plugin>
</plugins>
</build>
Add new run configuration as below:
Run >> Edit Configurations >> + >> Maven
Parameters tab ...
Name :: Tomcat
Working Directory :: Project Root Directory
Command Line :: tomcat7:run
Runner tab ...
VM Options :: <user needed options>
JRE :: <project needed>
Invoke Tomcat in Run/Debug mode directly from IntelliJ Run >> Run/Debug menu
NOTE: Though this is considered a hacking of using using Tomcat integration features of IntelliJ - Enterprise version features, but I would consider this a programmatic way integrating tomcat to the IntelliJ Idea - community edition.
Take a substr of the CLOB and then convert it to a char:
UPDATE IMS_TEST
SET TEST_Category = 'just testing'
WHERE to_char(substr(TEST_SCRIPT, 1, 9)) = 'something'
AND ID = '10000239';
Thanks @dotnetom, @greg-herbowicz
If it returns "this.state is undefined" - bind timer function:
constructor(props){
super(props);
this.state = {currentCount: 10}
this.timer = this.timer.bind(this)
}
if you give it 234.545332233 it will give you 234.54
let textData = Double(myTextField.text!)!
let text = String(format: "%.2f", arguments: [textData])
mylabel.text = text
This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/
I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.
This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279
In Visual Basic, you can call a parameterless method without the braces (()
). In C#, they're mandatory. So you should write:
String guid = System.Guid.NewGuid().ToString();
Without the braces, you're assigning the method itself (instead of its result) to the variable guid
, and obviously the method cannot be converted to a String
, hence the error.
The way I've learned to implement this in a compact and readable manner for 1-D arrays, so far:
h = np.array([1,2,3,4,5])
v1 = np.vstack(h)
v2 = np.c_[h]
h1 = np.hstack(v1)
h2 = np.r_[v2[:,0]]
numpy.r_ and numpy.c_ translate slice objects to concatenation along the first and second axis, respectively. Therefore the slicing v2[:,0] in transposing back the vertical array v2 into the horizontal array h2
numpy.vstack is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.
Well there is quick to run a html which needs permission or blocked by CORS Just simply open the folder using VSCODE and install an extension called "live server"
And then just click on the bottom which says go live, thats it. Screenshot
Extending @Ryogi answer above, you can take advantage of the lower.tail
parameter like so:
qt(0.25/2, 40, lower.tail = FALSE)
# 75% confidence
qt(0.01/2, 40, lower.tail = FALSE)
# 99% confidence
I also had same problem. Purposely my build output path was "..\bin" and it works for me when I set the build output path as "\bin".
For Antlr 4 the java code generation process is below:-
java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g
Update your jar name in classpath accordingly.
One solution is to install both x86 (32-bit) and x64 Oracle Clients on your machine, then it does not matter on which architecture your application is running.
Here an instruction to install x86 and x64 Oracle client on one machine:
Assumptions: Oracle Home is called OraClient11g_home1
, Client Version is 11gR2
Optionally remove any installed Oracle client (see How to uninstall / completely remove Oracle 11g (client)? if you face problems)
Download and install Oracle x86 Client, for example into C:\Oracle\11.2\Client_x86
Download and install Oracle x64 Client into different folder, for example to C:\Oracle\11.2\Client_x64
Open command line tool, go to folder %WINDIR%\System32, typically C:\Windows\System32
and create a symbolic link ora112
to folder C:\Oracle\11.2\Client_x64
(see commands section below)
Change to folder %WINDIR%\SysWOW64, typically C:\Windows\SysWOW64
and create a symbolic link ora112
to folder C:\Oracle\11.2\Client_x86
, (see below)
Modify the PATH
environment variable, replace all entries like C:\Oracle\11.2\Client_x86
and C:\Oracle\11.2\Client_x64
by C:\Windows\System32\ora112
, respective their \bin
subfolder. Note: C:\Windows\SysWOW64\ora112
must not be in PATH environment.
If needed set your ORACLE_HOME
environment variable to C:\Windows\System32\ora112
Open your Registry Editor. Set Registry value HKLM\Software\ORACLE\KEY_OraClient11g_home1\ORACLE_HOME
to C:\Windows\System32\ora112
Set Registry value HKLM\Software\Wow6432Node\ORACLE\KEY_OraClient11g_home1\ORACLE_HOME
to C:\Windows\System32\ora112
(not C:\Windows\SysWOW64\ora112
)
You are done! Now you can use x86 and x64 Oracle client seamless together, i.e. an x86 application will load the x86 libraries, an x64 application loads the x64 libraries without any further modification on your system.
Probably it is a wise option to set your TNS_ADMIN
environment variable (resp. TNS_ADMIN
entries in Registry) to a common location, for example TNS_ADMIN=C:\Oracle\Common\network
.
Commands to create symbolic links:
cd C:\Windows\System32
mklink /d ora112 C:\Oracle\11.2\Client_x64
cd C:\Windows\SysWOW64
mklink /d ora112 C:\Oracle\11.2\Client_x86
Notes:
Both symbolic links must have the same name, e.g. ora112
.
Despite of their names folder C:\Windows\System32
contains the x64 libraries, whereas C:\Windows\SysWOW64
contains the x86 (32-bit) libraries. Don't be confused.
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
Styling alert()-boxes ist not possible. You could use a javascript modal overlay instead.
CONCAT with a null value returns null, so the easiest solution is:
UPDATE myTable SET spares = IFNULL (CONCAT( spares , "string" ), "string")
This one is just extension of article you found.
public class WebClientEx : WebClient
{
public WebClientEx(CookieContainer container)
{
this.container = container;
}
public CookieContainer CookieContainer
{
get { return container; }
set { container= value; }
}
private CookieContainer container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest r = base.GetWebRequest(address);
var request = r as HttpWebRequest;
if (request != null)
{
request.CookieContainer = container;
}
return r;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = base.GetWebResponse(request, result);
ReadCookies(response);
return response;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
ReadCookies(response);
return response;
}
private void ReadCookies(WebResponse r)
{
var response = r as HttpWebResponse;
if (response != null)
{
CookieCollection cookies = response.Cookies;
container.Add(cookies);
}
}
}
Because I often find myself working with multiple environment variables, I find it useful to keep them in a separate .env
file (make sure to ignore this from your source control). Then (in Linux) prepend export $(cat .env | xargs) &&
in your script command before starting your app.
Example .env
file:
VAR_A=Hello World
VAR_B=format the .env file like this with new vars separated by a line break
Example index.js
:
console.log('Test', process.env.VAR_A, process.env.VAR_B);
Example package.json
:
{
...
"scripts": {
"start": "node index.js",
"env-linux": "export $(cat .env | xargs) && env",
"start-linux": "export $(cat .env | xargs) && npm start",
"env-windows": "(for /F \"tokens=*\" %i in (.env) do set %i)",
"start-windows": "(for /F \"tokens=*\" %i in (.env) do set %i) && npm start",
}
...
}
Unfortunately I can't seem to set the environment variables by calling a script from a script -- like "start-windows": "npm run env-windows && npm start"
-- so there is some redundancy in the scripts.
For a test you can see the env variables by running npm run env-linux
or npm run env-windows
, and test that they make it into your app by running npm run start-linux
or npm run start-windows
.
I've built a module that makes in-memory pagination incredibly simple.
It allows you to paginate by simply replacing ng-repeat
with dir-paginate
, specifying the items per page as a piped filter, and then dropping the controls wherever you like in the form of a single directive, <dir-pagination-controls>
To take the original example asked by Tomarto, it would look like this:
<ul class='phones'>
<li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
<a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
<a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
<p>{{phone.snippet}}</p>
</li>
</ul>
<dir-pagination-controls></dir-pagination-controls>
There is no need for any special pagination code in your controller. It's all handled internally by the module.
Indeed this is a bug, although intentional for 2 years now.
The problem lies with some unclear specs and the complexity when document.title
and back/forward are involved.
See bug reference on Webkit and Mozilla. Also Opera on the introduction of History API said it wasn't using the title parameter and probably still doesn't.
Currently the 2nd argument of pushState and replaceState — the title of the history entry — isn't used in Opera's implementation, but may be one day.
Potential solution
The only way I see is to alter the title element and use pushState instead:
document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );
Anacoda3-4.2.0 Uses python 3.5 You can find the same in the link given below : https://repo.continuum.io/archive/Anaconda3-4.2.0-Windows-x86_64.exe
I faced the same problem and found the correct version by checking the available Anaconda 4.2.0 distributions in installer archive here
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
Maven uses variable $JAVACMD as the final java command, set it to where the java executable is will switch maven to different JDK.
<?php
$args = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args );
?>
This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products
Check out Simon Ince's Conditional Validation in MVC.
I am working through his example project right now.
Another approach is achieved by using CountDownTimer
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new CountDownTimer(5000, 1000) { //5 seconds
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}.start();
}
Copy of answer OP posted in question:
Solution
After the update from the previous edit, I looked a bit about the connection between client and server and I found out that even when mongod.exe was not running, there was still something listening on port 27017 with netstat -a
So I tried to launch the server with a random port using
[dir]mongod.exe --port 2000
Then the shell with
[dir]mongo.exe --port 2000
And this time, the server printed a message saying there is a new connection. I typed few commands and everything was working perfectly fine, I started the basic tutorial from the documentation to check if it was ok and for now it is.
If your'e using Web Forms then Grid View can work very nicely for this
The code looks a little like this.
aspx page.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>
You can either input the data manually or use the source method in the code side
public class Room
{
public string Name
public double Size {get; set;}
public int Quantity {get; set;}
public double Amount {get; set;}
public int Duration {get; set;}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)//this is so you can keep any data you want for the list
{
List<Room> rooms=new List<Room>();
//then use the rooms.Add() to add the rooms you need.
GridView1.DataSource=rooms
GridView1.Databind()
}
}
Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.
The View would look like this.
@model YourProject.Model.IEnumerable<Room>
<table>
<th>
<td>@Html.LabelFor(model => model.Name)</td>
<td>@Html.LabelFor(model => model.Size)</td>
<td>@Html.LabelFor(model => model.Quantity)</td>
<td>@Html.LabelFor(model => model.Amount)</td>
<td>@Html.LabelFor(model => model.Duration)</td>
</th>
foreach(item in model)
{
<tr>
<td>@model.Name</td>
<td>@model.Size</td>
<td>@model.Quantity</td>
<td>@model.Amount</td>
<td>@model.Duration</td>
</tr>
}
</table>
The controller might look something like this.
public ActionResult Index()
{
List<Room> rooms=new List<Room>();
//again add the items you need
return View(rooms);
}
Hope this helps :)
You have to append your project's path to PYTHONPATH
and make sure to use absolute imports.
For UNIX (Linux, OSX, ...)
export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"
For Windows
set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\project\
Absolute imports
Assuming that we have the following project structure,
+-- myproject
+-- mypackage
¦ +-- a.py
+-- anotherpackage
+-- b.py
+-- c.py
+-- mysubpackage
+-- d.py
just make sure to reference each import starting from the project's root directory. For instance,
# in module a.py
import anotherpackage.mysubpackage.d
# in module b
import anotherpackage.c
import mypackage.a
For a more comprehensive explanation, refer to the article How to fix ModuleNotFoundError and ImportError
This worked for me on Ubuntu:
Stop MySQL server:
/etc/init.d/mysql stop
Start MySQL from the commandline:
/usr/sbin/mysqld
In another terminal enter mysql and issue:
grant all privileges on *.* to 'root'@'%' with grant option;
You may also want to add
grant all privileges on *.* to 'root'@'localhost' with grant option;
and optionally use a password as well.
flush privileges;
and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with
/etc/init.d/mysql start
to detect when the iframe has loaded and its document is ready?
It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).
If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:
<img id="x" ... />
<script type="text/javascript">
document.getElementById('x').onload= function() {
...
};
</script>
there is no guarantee that the item won't already have loaded by the time the script executes.
The ways out of load-races are:
on IE, you can use the ‘readyState’ property to see if something's already loaded;
if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;
the old-school way of including it in the markup:
<img onload="callback(this)" ... />
Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.
The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.
http://php.net/manual/en/book.outcontrol.php
More Resources:
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
When you use Object.defineProperties
, by default writable
is set to false
, so _year
and edition
are actually read only properties.
Explicitly set them to writable: true
:
_year: {
value: 2004,
writable: true
},
edition: {
value: 1,
writable: true
},
Check out MDN for this method.
writable
true
if and only if the value associated with the property may be changed with an assignment operator.
Defaults tofalse
.
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
If you have more then one UITextField
s and you need to do something when (or before) keyboard appears or disappears, you can implement this approach.
Add UITextFieldDelegate
to your class. Assign integer counter, let's say:
NSInteger editCounter;
Set this counter to zero somewhere in viewDidLoad
.
Then, implement textFieldShouldBeginEditing
and textFieldShouldEndEditing
delegate methods.
In the first one add 1 to editCounter. If value of editCounter becomes 1 - this means that keyboard will appear (in case if you return YES). If editCounter > 1 - this means that keyboard is already visible and another UITextField holds the focus.
In textFieldShouldEndEditing
subtract 1 from editCounter. If you get zero - keyboard will be dismissed, otherwise it will remain on the screen.
For offline Javadoc from zip file rather than extracting it.
This is already answered which uses extracted zip data but it consumes more memory than simple zip file.
Comparison of zip file and extracted data.
jdk-6u25-fcs-bin-b04-apidocs.zip ---> ~57 MB
after extracting this zip file ---> ~264 MB !
So this approach saves my approx. 200 MB.
1.Open
Windows -> Preferences
2.Select
jre
fromInstalled JREs
then ClickEdit...
3.Select all
.jar
files fromJRE system libraries
then ClickJavadoc Location...
4.Browse for
apidocs.zip
file forArchive path
and setPath within archive
as shown above. That's it.5.Put cursor on any class name or method name and hit Shift + F2
[ ]{2,}
SPACE (2 or more)
You could also check that before and after those spaces words follow. (not other whitespace like tabs or new lines)
\w[ ]{2,}\w
the same, but you can also pick (capture) only the spaces for tasks like replacement
\w([ ]{2,})\w
or see that before and after spaces there is anything, not only word characters (except whitespace)
[^\s]([ ]{2,})[^\s]
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
PLEASE do not use object as a class name:
public class MyObject //better to choose an appropriate name
{
string id;
DateTime date;
public string ID
{
get { return id; }
set { id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
You should implement INotifyPropertyChanged
for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.
Your Viewmodel class/ dialogbox class should have a Property
of your MyObject
list. ObservableCollection<MyObject>
is the way to go:
public ObservableCollection<MyObject> MyList
{
get...
set...
}
In your xaml
you should set the Itemssource
to your collection of MyObject
. (the Datacontext
have to be your dialogbox class!)
<DataGrid ItemsSource="{Binding Source=MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
I figured out a way to telnet to a server and change a file permission. Then FTP the file back to your computer and open it. Hopefully this will answer your questions and also help FTP.
The filepath variable is setup so you always login and cd to the same directory. You can change it to a prompt so the user can enter it manually.
:: This will telnet to the server, change the permissions,
:: download the file, and then open it from your PC.
:: Add your username, password, servername, and file path to the file.
:: I have not tested the server name with an IP address.
:: Note - telnetcmd.dat and ftpcmd.dat are temp files used to hold commands
@echo off
SET username=
SET password=
SET servername=
SET filepath=
set /p id="Enter the file name: " %=%
echo user %username%> telnetcmd.dat
echo %password%>> telnetcmd.dat
echo cd %filepath%>> telnetcmd.dat
echo SITE chmod 777 %id%>> telnetcmd.dat
echo exit>> telnetcmd.dat
telnet %servername% < telnetcmd.dat
echo user %username%> ftpcmd.dat
echo %password%>> ftpcmd.dat
echo cd %filepath%>> ftpcmd.dat
echo get %id%>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat %servername%
del ftpcmd.dat
del telnetcmd.dat
Here is how I did this, somewhat similar to the solutions above. Just make sure you call the loadDots() method after all images are downloaded.
private int dotsCount;
private TextView dotsTextView[];
private void setupAdapter() {
adapter = new SomeAdapter(getContext(), images);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(0);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
private final ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < dotsCount; i++)
dotsTextView[i].setTextColor(Color.GRAY);
dotsTextView[position].setTextColor(Color.WHITE);
}
@Override
public void onPageScrollStateChanged(int state) {}
};
protected void loadDots() {
dotsCount = adapter.getCount();
dotsTextView = new TextView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dotsTextView[i] = new TextView(getContext());
dotsTextView[i].setText(R.string.dot);
dotsTextView[i].setTextSize(45);
dotsTextView[i].setTypeface(null, Typeface.BOLD);
dotsTextView[i].setTextColor(android.graphics.Color.GRAY);
mDotsLayout.addView(dotsTextView[i]);
}
dotsTextView[0].setTextColor(Color.WHITE);
}
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#00000000"/>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/introImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/image_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
android:gravity="center|bottom"
android:orientation="horizontal"/>
</FrameLayout>
One option seems to be using CSS to style the textarea
.multi-line { height:5em; width:5em; }
See this entry on SO or this one.
Amurra's accepted answer seems to imply this class is added automatically when using EditorFor but you'd have to verify this.
EDIT: Confirmed, it does. So yes, if you want to use EditorFor, using this CSS style does what you're looking for.
<textarea class="text-box multi-line" id="StoreSearchCriteria_Location" name="StoreSearchCriteria.Location">
The pattern you want is something like (see it on rubular.com):
^[a-zA-Z0-9_.-]*$
Explanation:
^
is the beginning of the line anchor$
is the end of the line anchor[...]
is a character class definition*
is "zero-or-more" repetitionNote that the literal dash -
is the last character in the character class definition, otherwise it has a different meaning (i.e. range). The .
also has a different meaning outside character class definitions, but inside, it's just a literal .
Here's a snippet to show how you can use this pattern:
<?php
$arr = array(
'screen123.css',
'screen-new-file.css',
'screen_new.js',
'screen new file.css'
);
foreach ($arr as $s) {
if (preg_match('/^[\w.-]*$/', $s)) {
print "$s is a match\n";
} else {
print "$s is NO match!!!\n";
};
}
?>
The above prints (as seen on ideone.com):
screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!
Note that the pattern is slightly different, using \w
instead. This is the character class for "word character".
This seems to follow your specification, but note that this will match things like .....
, etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.
The above regex also matches the empty string. If you need at least one character, then use +
(one-or-more) instead of *
(zero-or-more) for repetition.
In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
In Google's closure library project , there is a module which has do the job , below is the API and source code.
There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.
While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
I've found this the easy fix, simply add this to the css:
cursor: pointer;
Try this. Here is the code to get the sheet names in order.
private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int, string> excelSheets = new Dictionary<int, string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
One situation I've run into was when dealing with milliseconds. FF and IE will not parse this date string correctly when trying to create a new date.
"2014/11/24 17:38:20.177Z"
They do not know how to handle .177Z
. Chrome will work though.
You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.
In this case, you can do
perl -pe 's/(regex)/\n$1/'
-pe
puts perl into a "execute and print" loop, much like sed's normal mode of operation.
'
quotes everything else so the shell won't interfere
()
surrounding the regex is a grouping operator. $1
on the right side of the substitution prints out whatever was matched inside these parens.
Finally, \n
is a newline.
Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like
\(\d\d\d\)\d\d\d-\d\d\d\d
\(
or \)
matches a literal paren, and \d
matches a digit.
Better:
\(\d{3}\)\d{3}-\d{4}
I imagine you can figure out what the numbers in braces are doing.
Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.
perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'
A couple final thoughts.
using -ne
instead of -pe
acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/
is a regex match):
perl -ne 'if (m/foobar/) {print}'
If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l
. Not useful for the OP, who was working with newlines, though.
Bonus tip - if you have the pcre package installed, it comes with pcregrep
, which uses full perl-compatible regexes.
On a related or actually, on the completely opposite note -
"If you're the user of the aforementioned form and want to re-enable the autocomplete functionality, use the 'remember password' bookmarklet from this bookmarklets page. It removes all
autocomplete="off"
attributes from all forms on the page. Keep fighting the good fight!"
#include
works just like the C #include
.
#import
keeps track of which headers have already been included and is ignored if a header is imported more than once in a compilation unit. This makes it unnecessary to use header guards.
The bottom line is just use #import
in Objective-C and don't worry if your headers wind up importing something more than once.
You almost had it with Not
. It should be:
if (-Not (Test-Path C:\Code)) {
write "it doesn't exist!"
}
You can also use !
: if (!(Test-Path C:\Code)){}
Just for fun, you could also use bitwise exclusive or, though it's not the most readable/understandable method.
if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
Yes, you could append ;Connection Timeout=30
to your connection string and specify the value you wish.
The timeout value set in the Connection Timeout
property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).
Moreover, setting the timeout value to 0
, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.
you can also use just like this in newer version of sql,
select year('2001-02-16 20:38:40') as year,
month('2001-02-16 20:38:40') as month,
day('2001-02-16 20:38:40') as day,
hour('2001-02-16 20:38:40') as hour,
minute('2001-02-16 20:38:40') as minute
The fact that a HTTPS
request becomes HTTP
when you tried to construct the URL on server side indicates that you might have a proxy/load balancer (nginx
, pound
, etc.) offloading SSL encryption in front and forward to your back end service in plain HTTP
.
If that's case, check,
Host
, X-forwarded-proto
, X-forwarded-for
, etc). Tomcat
) is set up to recognize the proxy in front. For example, Tomcat
requires adding secure="true" scheme="https" proxyPort="443"
attributes to its Connector
Tomcat
automatically replaces scheme
, remoteAddr
, etc. values when you add RemoteIpValve
to its Engine
. (see Configuration guide, JavaDoc) so you don't have to process these headers in your code manually.Incorrect proxy header values could result in incorrect output when request.getRequestURI()
or request.getRequestURL()
attempts to construct the originating URL.
The introduction of some new testing facilities in Spring 4.2.RC1 lets one write Spring integration tests that don't rely on the SpringJUnit4ClassRunner
. Check out this part of the documentation.
In your case you could write your Spring integration test and still use mocks like this:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@InjectMocks
TestTarget sut;
@Mock
Foo mockFoo;
@Test
public void someTest() {
// ....
}
}
Closure is a feature in JavaScript where a function has access to its own scope variables, access to the outer function variables and access to the global variables.
Closure has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.
The inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope.
Example of Closure:
var globalValue = 5;
function functOuter() {
var outerFunctionValue = 10;
//Inner function has access to the outer function value
//and the global variables
function functInner() {
var innerFunctionValue = 5;
alert(globalValue + outerFunctionValue + innerFunctionValue);
}
functInner();
}
functOuter();
Output will be 20 which sum of its inner function own variable, outer function variable and global variable value.
There are lots of control flow libraries -- I like conseq (... because I wrote it.) Also, on('data')
can fire several times, so use a REST wrapper library like restler.
Seq()
.seq(function () {
rest.get('http://www.example.com/api_1.php').on('complete', this.next);
})
.seq(function (d1) {
this.d1 = d1;
rest.get('http://www.example.com/api_2.php').on('complete', this.next);
})
.seq(function (d2) {
this.d2 = d2;
rest.get('http://www.example.com/api_3.php').on('complete', this.next);
})
.seq(function (d3) {
// use this.d1, this.d2, d3
})
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:JSON.stringify(
[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]),
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
Controler
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
The awesome part of python is the things you can do with it. You don't have to use indexes for strings.
The following will work (using slices)
def palindrome(n):
return n == n[::-1]
What it does is simply reverses n, and checks if they are equal. n[::-1]
reverses n (the -1 means to decrement)
"2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?"
Regarding the above, you want to use xrange
instead of range (because range will create an actual list, while xrange is a fast generator)
My opinions on question 3
I learned C before Python, and I just read the docs, and played around with it using the console. (and by doing Project Euler problems as well :)
I've seen only one simple way of reading an arbitrarily long string, but I've never used it. I think it goes like this:
char *m = NULL;
printf("please input a string\n");
scanf("%ms",&m);
if (m == NULL)
fprintf(stderr, "That string was too long!\n");
else
{
printf("this is the string %s\n",m);
/* ... any other use of m */
free(m);
}
The m
between %
and s
tells scanf()
to measure the string and allocate memory for it and copy the string into that, and to store the address of that allocated memory in the corresponding argument. Once you're done with it you have to free()
it.
This isn't supported on every implementation of scanf()
, though.
As others have pointed out, the easiest solution is to set a limit on the length of the input. If you still want to use scanf()
then you can do so this way:
char m[100];
scanf("%99s",&m);
Note that the size of m[]
must be at least one byte larger than the number between %
and s
.
If the string entered is longer than 99, then the remaining characters will wait to be read by another call or by the rest of the format string passed to scanf()
.
Generally scanf()
is not recommended for handling user input. It's best applied to basic structured text files that were created by another application. Even then, you must be aware that the input might not be formatted as you expect, as somebody might have interfered with it to try to break your program.
Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux
For python3, on a Mac you must use pip3 to install selenium.
sudo pip3 install selenium
You can insert multiple records by inserting from a result:
insert into db (@names,@email,@password)
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword'
Just add as many records you like. There may be limitations on the complexity of the query though, so it might not be possible to add as many as 1000 records at once.
In regards to this question, this can be easily achieved using a few lines of SASS;
HTML:
<a href="https://www.urbandictionary.com/define.php?term=techninja" data-tool-tip="What's a tech ninja?" target="_blank"><i class="fas fa-2x fa-user-ninja" id="tech--ninja"></i></a>
CSS output would be:
a[data-tool-tip]{
position: relative;
text-decoration: none;
color: rgba(255,255,255,0.75);
}
a[data-tool-tip]::after{
content: attr(data-tool-tip);
display: block;
position: absolute;
background-color: dimgrey;
padding: 1em 3em;
color: white;
border-radius: 5px;
font-size: .5em;
bottom: 0;
left: -180%;
white-space: nowrap;
transform: scale(0);
transition:
transform ease-out 150ms,
bottom ease-out 150ms;
}
a[data-tool-tip]:hover::after{
transform: scale(1);
bottom: 200%;
}
Basically the attribute selector [data-tool-tip] selects the content of whatever's inside and allows you to animate it however you want.
Now there's a dedicated function on console for that:
console.trace()
Use IS
instead of =
This will solve your problem
example syntax:
UPDATE studentdetails
SET contactnumber = 9098979690
WHERE contactnumber IS NULL;
I got here searching for the same error, but from Node.js native driver. The answer for me was combination of answers by campeterson and Prabhat.
The issue is that readPreference
setting defaults to primary
, which then somehow leads to the confusing slaveOk
error. My problem is that I just wan to read from my replica set from any node. I don't even connect to it as to replicaset. I just connect to any node to read from it.
Setting readPreference
to primaryPreferred
(or better to the ReadPreference.PRIMARY_PREFERRED
constant) solved it for me. Just pass it as an option to MongoClient.connect()
or to client.db()
or to any find()
, aggregate()
or other function.
const { MongoClient, ReadPreference } = require('mongodb');
const client = await MongoClient.connect(MONGODB_CONNECTIONSTRING, { readPreference: ReadPreference.PRIMARY_PREFERRED });
SonarQube documentation recommends adding static
keyword to the class declaration.
That is, change public class FilePathHelper
to public static class FilePathHelper
.
Alternatively you can add a private or protected constructor.
public class FilePathHelper
{
// private or protected constructor
// because all public fields and methods are static
private FilePathHelper() {
}
}
Use -Wno-unused-variable
should work.
OK, here's the solution I settled on.
First you create a seed value using the "newseed()" function. Then you pass the seed value to the "srandom()" function. Lastly, the "srandom()" function returns a pseudo random value between 0 and 1.
The crucial bit is that the seed value is stored inside an array. If it were simply an integer or float, the value would get overwritten each time the function were called, since the values of integers, floats, strings and so forth are stored directly in the stack versus just the pointers as in the case of arrays and other objects. Thus, it's possible for the value of the seed to remain persistent.
Finally, it is possible to define the "srandom()" function such that it is a method of the "Math" object, but I'll leave that up to you to figure out. ;)
Good luck!
JavaScript:
// Global variables used for the seeded random functions, below.
var seedobja = 1103515245
var seedobjc = 12345
var seedobjm = 4294967295 //0x100000000
// Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
{
return [seednum]
}
// Works like Math.random(), except you provide your own seed as the first argument.
function srandom(seedobj)
{
seedobj[0] = (seedobj[0] * seedobja + seedobjc) % seedobjm
return seedobj[0] / (seedobjm - 1)
}
// Store some test values in variables.
var my_seed_value = newseed(230951)
var my_random_value_1 = srandom(my_seed_value)
var my_random_value_2 = srandom(my_seed_value)
var my_random_value_3 = srandom(my_seed_value)
// Print the values to console. Replace "WScript.Echo()" with "alert()" if inside a Web browser.
WScript.Echo(my_random_value_1)
WScript.Echo(my_random_value_2)
WScript.Echo(my_random_value_3)
Lua 4 (my personal target environment):
-- Global variables used for the seeded random functions, below.
seedobja = 1103515.245
seedobjc = 12345
seedobjm = 4294967.295 --0x100000000
-- Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
return {seednum}
end
-- Works like random(), except you provide your own seed as the first argument.
function srandom(seedobj)
seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
return seedobj[1] / (seedobjm - 1)
end
-- Store some test values in variables.
my_seed_value = newseed(230951)
my_random_value_1 = srandom(my_seed_value)
my_random_value_2 = srandom(my_seed_value)
my_random_value_3 = srandom(my_seed_value)
-- Print the values to console.
print(my_random_value_1)
print(my_random_value_2)
print(my_random_value_3)
If you want to load an assembly without locking it during the duration of the PowerShell session, use this:
$bytes = [System.IO.File]::ReadAllBytes($storageAssemblyPath)
[System.Reflection.Assembly]::Load($bytes)
Where $storageAssemblyPath
is the filepath of your assembly.
This is especially usefull if you need to cleanup the ressources within your session. For example in a deployment script.
A flexible way to do it :
(Not made for current date but good enough for durations)
/**
convert duration to a ms/sec/min/hour/day/week array
@param {int} msTime : time in milliseconds
@param {bool} fillEmpty(optional) : fill array values even when they are 0.
@param {string[]} suffixes(optional) : add suffixes to returned values.
values are filled with missings '0'
@return {int[]/string[]} : time values from higher to lower(ms) range.
*/
var msToTimeList=function(msTime,fillEmpty,suffixes){
suffixes=(suffixes instanceof Array)?suffixes:[]; //suffixes is optional
var timeSteps=[1000,60,60,24,7]; // time ranges : ms/sec/min/hour/day/week
timeSteps.push(1000000); //add very big time at the end to stop cutting
var result=[];
for(var i=0;(msTime>0||i<1||fillEmpty)&&i<timeSteps.length;i++){
var timerange = msTime%timeSteps[i];
if(typeof(suffixes[i])=="string"){
timerange+=suffixes[i]; // add suffix (converting )
// and fill zeros :
while( i<timeSteps.length-1 &&
timerange.length<((timeSteps[i]-1)+suffixes[i]).length )
timerange="0"+timerange;
}
result.unshift(timerange); // stack time range from higher to lower
msTime = Math.floor(msTime/timeSteps[i]);
}
return result;
};
NB : you could also set timeSteps as parameter if you want to control the time ranges.
how to use (copy an test):
var elsapsed = Math.floor(Math.random()*3000000000);
console.log( "elsapsed (labels) = "+
msToTimeList(elsapsed,false,["ms","sec","min","h","days","weeks"]).join("/") );
console.log( "half hour : "+msToTimeList(elsapsed,true)[3]<30?"first":"second" );
console.log( "elsapsed (classic) = "+
msToTimeList(elsapsed,false,["","","","","",""]).join(" : ") );
As others have stated, you have no guarantee as to the order when you iterate over the properties of an object. If you need an ordered list of multiple fields I suggested creating an array of objects.
var myarr = [{somfield1: 'x', somefield2: 'y'},
{somfield1: 'a', somefield2: 'b'},
{somfield1: 'i', somefield2: 'j'}];
This way you can use a regular for loop and have the insert order. You could then use the Array sort method to sort this into a new array if needed.
The problem is you likely only have the gcc for your current architecture and that's 64bit. You need the 32bit support files. For that, you need to install them
sudo apt install gcc-multilib
$string = "picture_0007_value";
$findChar =strrpos($string,"_");
if($findChar !== FALSE) {
$string[$findChar]=".";
}
echo $string;
Apart from the mistakes in the code, Faruk Unal has the best anwser. One function does the trick.
Here is an extension of Roberto14's answer that does the following:
THIS WILL ONLY ALLOW IMAGES
Checks if FileReader is available and falls back to extension checking if it is not available.
Gives an error alert if not an image
If it is an image it loads a preview
** You should still do server side validation, this is more a convenience for the end user than anything else. But it is handy!
<form id="myform">
<input type="file" id="myimage" onchange="readURL(this)" />
<img id="preview" src="#" alt="Image Preview" />
</form>
<script>
function readURL(input) {
if (window.FileReader && window.Blob) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image();
img.onload = function() {
var preview = document.getElementById('preview');
preview.src = e.target.result;
};
img.onerror = function() {
alert('error');
input.value = '';
};
img.src = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
}
else {
var ext = input.value.split('.');
ext = ext[ext.length-1].toLowerCase();
var arrayExtensions = ['jpg' , 'jpeg', 'png', 'bmp', 'gif'];
if (arrayExtensions.lastIndexOf(ext) == -1) {
alert('error');
input.value = '';
}
else {
var preview = document.getElementById('preview');
preview.setAttribute('alt', 'Browser does not support preview.');
}
}
}
</script>
Also, you can configure the port programmatically.
For Spring Boot 2.x.x:
@Configuration
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
public void customize(ConfigurableServletWebServerFactory factory){
factory.setPort(8042);
}
}
For older versions:
@Configuration
public class ServletConfig {
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container -> {
container.setPort(8012);
});
}
}
@marioosh added some extra information regarding cipher suite encryption .
A cipher suite is a collection of symmetric and asymmetric encryption algorithms used by hosts to establish a secure communication in Transport Layer Security (TLS) / Secure Sockets Layer (SSL) network protocol.
Ciphers are algorithms, more specifically they’re a set of steps for both performing encryption as well as the corresponding decryption.
A cipher suite specifies one algorithm for each of the following tasks:
SocketFactory « Default handshaking protocols « To avoid SSLException use https.protocols
system property.
This contains a comma-separated list of protocol suite names specifying which protocol suites to enable on this HttpsURLConnection. See the SSLSocket.setEnabledProtocols(String[]) method.
System.setProperty("https.protocols", "SSLv3");
// (OR)
System.setProperty("https.protocols", "TLSv1");
JAVA8 « TLS 1.1 and TLS 1.2 Enabled by Default: The SunJSSE provider enables the protocols TLS 1.1 and TLS 1.2 on the client by default.
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
Example for Java8 Network File:
public class SecureSocket {
static {
// System.setProperty("javax.net.debug", "all");
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
}
public static void main(String[] args) {
String GhitHubSSLFile = "https://raw.githubusercontent.com/Yash-777/SeleniumWebDrivers/master/pom.xml";
try {
String str = readCloudFileAsString(GhitHubSSLFile);
// new String(Files.readAllBytes(Paths.get( "D:/Sample.file" )));
System.out.println("Cloud File Data : "+ str);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readCloudFileAsString( String urlStr ) throws java.io.IOException {
if( urlStr != null && urlStr != "" ) {
java.io.InputStream s = null;
String content = null;
try {
URL url = new URL( urlStr );
s = (java.io.InputStream) url.getContent();
content = IOUtils.toString(s, "UTF-8");
} finally {
if (s != null) s.close();
}
return content.toString();
}
return null;
}
}
JDK 8 Security You can customize some aspects of JSSE by setting system properties, By Specifying the below property you can check the encryption data from the file.
System.setProperty("javax.net.debug", "all");
Exception
javax.net.ssl.SSLException: Received fatal alert: protocol_version
If handshaking fails for any reason, the SSLSocket is closed, and no further communications can be done.
Observer LOG Sample for the above example:
*** ClientHello, TLSv1.2
RandomCookie: GMT: 1505482843 bytes = { 12, 11, 111, 99, 8, 177, 101, 27, 84, 176, 147, 215, 116, 208, 31, 178, 141, 170, 29, 118, 29, 192, 61, 191, 53, 201, 127, 100 }
Session ID: {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods: { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
Extension server_name, server_name: [host_name: raw.githubusercontent.com]
***
[write] MD5 and SHA1 hashes: len = 213
0000: 01 00 00 D1 03 03 5A BC D8 5B 0C 0B 6F 63 08 B1 ......Z..[..oc..
0010: 65 1B 54 B0 93 D7 74 D0 1F B2 8D AA 1D 76 1D C0 e.T...t......v..
0020: 3D BF 35 C9 7F 64 00 00 2A C0 09 C0 13 00 2F C0 =.5..d..*...../.
0030: 04 C0 0E 00 33 00 32 C0 08 C0 12 00 0A C0 03 C0 ....3.2.........
0040: 0D 00 16 00 13 C0 07 C0 11 00 05 C0 02 C0 0C 00 ................
0050: 04 00 FF 01 00 00 7E 00 0A 00 34 00 32 00 17 00 ..........4.2...
0060: 01 00 03 00 13 00 15 00 06 00 07 00 09 00 0A 00 ................
0070: 18 00 0B 00 0C 00 19 00 0D 00 0E 00 0F 00 10 00 ................
0080: 11 00 02 00 12 00 04 00 05 00 14 00 08 00 16 00 ................
0090: 0B 00 02 01 00 00 0D 00 1A 00 18 06 03 06 01 05 ................
00A0: 03 05 01 04 03 04 01 03 03 03 01 02 03 02 01 02 ................
00B0: 02 01 01 00 00 00 1E 00 1C 00 00 19 72 61 77 2E ............raw.
00C0: 67 69 74 68 75 62 75 73 65 72 63 6F 6E 74 65 6E githubuserconten
00D0: 74 2E 63 6F 6D t.com
main, WRITE: TLSv1.2 Handshake, length = 213
[Raw write]: length = 218
0000: 16 03 03 00 D5 01 00 00 D1 03 03 5A BC D8 5B 0C ...........Z..[.
0010: 0B 6F 63 08 B1 65 1B 54 B0 93 D7 74 D0 1F B2 8D .oc..e.T...t....
0020: AA 1D 76 1D C0 3D BF 35 C9 7F 64 00 00 2A C0 09 ..v..=.5..d..*..
0030: C0 13 00 2F C0 04 C0 0E 00 33 00 32 C0 08 C0 12 .../.....3.2....
0040: 00 0A C0 03 C0 0D 00 16 00 13 C0 07 C0 11 00 05 ................
0050: C0 02 C0 0C 00 04 00 FF 01 00 00 7E 00 0A 00 34 ...............4
0060: 00 32 00 17 00 01 00 03 00 13 00 15 00 06 00 07 .2..............
0070: 00 09 00 0A 00 18 00 0B 00 0C 00 19 00 0D 00 0E ................
0080: 00 0F 00 10 00 11 00 02 00 12 00 04 00 05 00 14 ................
0090: 00 08 00 16 00 0B 00 02 01 00 00 0D 00 1A 00 18 ................
00A0: 06 03 06 01 05 03 05 01 04 03 04 01 03 03 03 01 ................
00B0: 02 03 02 01 02 02 01 01 00 00 00 1E 00 1C 00 00 ................
00C0: 19 72 61 77 2E 67 69 74 68 75 62 75 73 65 72 63 .raw.githubuserc
00D0: 6F 6E 74 65 6E 74 2E 63 6F 6D ontent.com
[Raw read]: length = 5
0000: 16 03 03 00 5D ....]
Cryptography and Secure Communication with whatsapp
@See
Okay lots of posts here, none of them helped me, days and days of google, and still no further I got to the point the wr-writing the whole app from scratch, and then I noticed this little nugget in my Web.confg
<httpCookies requireSSL="false" domain="*.localLookup.net"/>
Now I don't know why I added it however I have since noticed, its ignored in debug mode and not in a production mode (IE Installed to IIS Somewhere)
For me the solution was one of 2 options, since I don't remember why I added it I cant be sure other things don't depend on it, and second the domain name must be all lower case and a TLD not like ive done in *.localLookup.net
Maybe it helps maybe it don't. I hope it does help someone
CMD:
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment
PowerShell:
Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment
Powershell/.NET: (see EnvironmentVariableTarget Enum)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)
There is a version of string.Split
that takes an array of strings and a StringSplitOptions
parameter:
From this MSDN article:
There is some overhead associated with creating a StringBuilder object, both in time and memory. On a machine with fast memory, a StringBuilder becomes worthwhile if you're doing about five operations. As a rule of thumb, I would say 10 or more string operations is a justification for the overhead on any machine, even a slower one.
So if you trust MSDN go with StringBuilder if you have to do more than 10 strings operations/concatenations - otherwise simple string concat with '+' is fine.
Assuming you have lost these while upgrading versions like I did, follow these steps to restore:
You should then see the list of connections that will be imported